# Question
Title: drupal commerce multiple products on one page
I'm building a website in which people can reserve plays(theater). I'm using a product display for this.

The problem is, a specific 'play' is going on for a number of days, and people should be able to reserve for a specific day.

For example : a specific play might go on the 18th,19th, and 20th of September and customers need to be able to select a date from those available.

How can this be achieved with Drupal Commerce ?

One idea I had was to create multiple products with the specific date, but how do I show multiple products on one product display ?

Thanks.

# Answer
On your Product Display field setup a multivalued entity reference field of type 'node'. Now as per your example

1. you add a product for date 18, in reference field add reference to other dates as well.
2. For all dates will have reference to each other.
3. Now with view create a block display to show related nodes using relationship on reference field and take node id from context filter.
4. Put this block on product display page so it can take node id from context and show related products.
> 0 votes

# Answer
Commerce Attributes Date

> This module provides the ability to use date field type as Product Attributes.

Add date as an attribute to the Product. The product display will then have a select list (or radio buttons) where the user can select the date. That way prices can be different on different days and I'm confident that stock control (limited space for event) can be done.
> 0 votes

---
Tags: commerce
---


# Question
Title: Alphabetical view sorting in multilingual site not working for translated content
I have created a view that alphabetically lists all nodes of type "*glossary entry*". A glossary with many terms. Besides German I need the glossary in English, too. The translation has worked great using Entity Translation module. I only have the problem that the alphabetical order of the English version is not correct. The English glossary has the same sort order than the German (original) version:

> **German version:**
>
> 1. Adler (German word for eagle)
> 2. Hund (German word for dog)
> 3. Kuh (German word for cow)
>
> **English version:**
>
> 1. Eagle
> 2. Dog
> 3. Cow

I crawled many forums but couldn't find a solution for my problem. I already added the relationship *"Entity Translation"* in my view but the additional filter and sorts don't help me here.

What I need is a sort *"title (English Translation)"*. Does somebody has a clue how to get this work?!!

Please find here the view's query

# Answer
> 1 votes
I solved that by adding this field as a relationship to the view and so **`name:field`** became accessible as sort criteria, which I then chose instead of **`content:field`**.

---
Tags: i18n-l10n, views
---


# Question
Title: How to get SMS as send method in the Messaging&Notification module (D7)?
I cannot find anything for D7, only D6. Anyone knows howto? Alternatively; any way to send SMS via views-send-module?

# Answer
> 1 votes
I've used SMS Framework for D7 ,, built a sub-module for my SMS Getway provider (it might be already there for your case),, and with my custom module controlled the rest in notifying|messaging ,,, etc

> The SMS Framework is set of modules that enables interaction between mobile users and Drupal using SMS. Several popular SMS gateways are supported and the included API allows developers to add support for additional gateways. The API also allows other modules to implement SMS features.

---
Tags: 7, views
---


# Question
Title: Add a message to messages array using theme process or preprocess function
For testing purposes, I'm trying to manually add a message to the `$messages` array, in either process or preprocess page function. To be clear, I first tried using

```
template.php -> mytheme_preprocess_page (&$vars) {}

```

but then I realized there's no `$messages` array there, so instead I am doing it via **process.page.inc**.

The code I have tried, which is not working is:

```
function mytheme_process_page(&$variables) {
    $variables[messages][] = 'new test message';
    kpr($variables);
}

```

I have tried some variations on this, but nothing worked.

# Answer
> 3 votes
`$messages` isn't an array of messages; it's the rendered output of `theme_status_messages()`. From the point at which you're looking to add messages (template\_process\_page()), Drupal has already processed all the messages it's going to render.

If you're looking to print some debugging messages you can do something like this:

```
function MYTHEME_process_page(&$variables) {
  drupal_set_message('new test message');

  //This will overwrite any previous messages that were to be rendered
  $variables['messages'] = theme_status_messages(array('display' => null));
}

```

---
Tags: theming, status-messages
---


# Question
Title: Get "previous" and "next" buttons on view
The view I want to create consists of two parts:

1. An overview page with all the products, that is sortable using Draggable Views. The url given by /collection/
2. A specific page that is shown when a user clicks on a product in the overview. The url given by /collection/\[title\]

Now I want prev / next buttons on the product page, based on the order given by Draggable Views.

I've searched for a couple of hours but cannot find anything that will do the trick. Can someone point me at an option or function that accomplishes this?

Thanks in advance!

# Answer
This module might be able to do the trick Views navigation

> This module adds next and previous links on content pages when accessed from a view. It is intended for dynamic and/or paged view results, where the result set changes according to exposed filters, current user access rights,...
> 2 votes

# Answer
Its too late to answer but you can use flippy module
> 0 votes

---
Tags: 7, views
---


# Question
Title: Two domains pointed at the same site, can't log in to one of them
A client has two domain names, a .ca and a .com, that both point to the same D7 site (same codebase, same database, no custom `sites` folder for either of them, so it's not a multisites situation; the Apache document root path is simply the same for both sites). Everything works fine except that nobody can log in to the .com version. There is no "unrecognized username or password" or other error generated, it just doesn't log them in. (Incorrect passwords *do* generate the error message.) Checking the log messages, I see that it opened and then immediately closed a session.

Changing cookie settings is not a viable approach here, because it's different top-level domains, not different subdomains.

One possible solution is to redirect one domain to the other instead of running them "in parallel" (I'm aware of the methods, pros and cons of this approach), but I'm interested in why this is and what else can be done about it.

# Answer
In this case, it seems that it's a conflict with the phpbbforum module. Probably some setting in there that's got it's cookie domain set to the .ca instead of figuring it out dynamically, similar to what @Drupalfan said. They're not actually using the forums at the moment anyway, so I've simply disabled that and logins now work through both domains without any other Drupal code or setting changes. I'll investigate it more closely (and try to remember to report back with a more complete solution) if and when they want to start using the forums.
> 0 votes

# Answer
I had this issue before. It is related to the cookie setting, try doing this:

```
<?php
if (isset($_SERVER['HTTP_HOST']) && substr_count($_SERVER['HTTP_HOST'], 'parentdomain.com') > 0) {
$cookie_domain = '.parentdomain.com';
}
?>

```
> 1 votes

---
Tags: users
---


# Question
Title: Integrating Video.js with Google Analytics
I'm wondering if anybody has gotten the Video.js module/library to play nicely with Google Analytics? I'm trying to do some integration via this plugin (https://github.com/mickey/videojs-ga), but am hitting a roadblock. I've added the script into my theme as second-to-last in the execution order, followed by another script consisting of the inline code noted in the example (as the final script on my page):

```
<script>
videojs('video', {}, function() {
  this.ga(); // "load the plugin, by defaults tracks everything!!"
});
</script>

```

At this point I think it's almost working, but chrome is throwing "Uncaught TypeError: The element or ID supplied is not valid." I've also tried replacing "video" on the above code with the ID of the video on the page that I am testing, and I'm getting the same error. I feel like I'm close, but I'm not sure what needs to be tweaked to get it working. Any ideas?

Right now I'm testing on http://mattweinercreates.com/video-js-testing, i you want to check out my environment.

# Answer
> 1 votes
I think I answered this after I posted. I was trying to use the ID on the `<video>` itself, but I instead tried using the ID of the div that contained the video, and that worked without issue. I still need to figure out how to update the code dynamically on a per-page basis so that the correct video is tracked, but it's at least working now.

EDIT: I was able to modify the "inline" code file from above to automatically pick up any videos on a page that the script is loaded on.

`(function ($) {
 $('.video-js').each(function() {
 videojs(this.id, {}, function() {
 this.ga(); // "load the plugin, by defaults tracks everything!!"
 });
 })
})(jQuery);`

---
Tags: 7, google-analytics
---


# Question
Title: Can Drush make include username, password and settings in one file?
I hear some talk about Drush make and features.

But not sure how to use them in combination.

Is there a way to have a Drupal site install with ALL settings, including install procedure (enter database name, site name, username ect...)

Include what modules to enable, set user permissions.

I know that Drush can do some of that.

But is it possible to have it ALL done within the drush.make file, can I add standard drush commands to that?

# Answer
> 1 votes
The responsibilities of Drush make involve downloading the files that make up your site. Site initialization can be done in an installation profile, which is selected at installation time, or perhaps in a script that you run to set up your site.

For Drupal 8, configuration can be imported via the `drush config-import` command. In Drupal 7, there are many options for managing configuration. A lot of people (perhaps the majority) use features, but I prefer ctools bonus export. Here is an example script I use to set up a test site for behat tests.

If you are just starting out, you might want to consider using Composer instead of Drush Make.

---
Tags: drush
---


# Question
Title: simplenews subscription form on front page with frontpage module
I want to place a Simplenews subscription form on my front page that I implemented using the Front Page module in 'full' mode. How do I do this?

# Answer
> 1 votes
Try this:

```
<?php $block = module_invoke('simplenews','block_view',5); print render($block); ?>

```

The number 5 shouldn't be sent as a string.

And if you are putting this in a textarea on Drupal's backend, you need the PHP input filter, which is generally a bad idea. Better to go through the theming system, add a region, and put the block there.

http://drupal.org/node/1088718

# Answer
> 0 votes
You should `print render($block['content']);` instead `print render($block);`
So solution will be:

```
<?php $block = module_invoke('simplenews','block_view',5);
 print render($block['content']); ?>

```

5= your block id (go to `http://example.com/admin/structure/block` and find simple newsletter block

---
Tags: emails
---


# Question
Title: Adding a link with nid in Global: results summary in Views
I have a Views block listing a certain amount of nodes, and I've added a header field: *Global: Result summary*.

I am on the page: http://myexample.com/node/145 for example and with the header field, I want to link to: http://myexample.com/node/145/events. I have put the following code in the field:

(@total)

But this omits the nid and goes directly to: http://myexample.com/node/events.

Does anyone know how to pass a URL argument for that field? I would ideally want to use `arg(1)`.

# Answer
Because the header uses the default Drupal PHP interpreter, Views variables aren't available there like they are in the arg php code. You can get them by doing something like this:

```
<?php
global $current_view;
print $current_view->args[0];
?>

```

Update: If you want to use PHP in views header, you can go to configure header, select "Global: Text area" and have to change text format to PHP code; you have to first install the PHP filter module.

Also if you use Global: Text area with PHP filter enabled this should work:

```
<a href="%/events">@total</a>

```
> 2 votes

# Answer
You don't get to add \[nid\] there.However you can use wildcard %.In your field of Global:Result Summary write like this

```
<a href="%/events">@total</a>

```

Hope it works for you.
> 0 votes

---
Tags: views
---


# Question
Title: How to have Drush make automatically find libraries download path?
I don't know from what URL's I got my libraries files from. Is there a way for Drush Make to find those URL's, a command?

Additionally, what URL/Path can I use for my own custom modules? Can I use a local path in a URL so the libraries are sourced locally?

# Answer
As Molot states, there's no way for drush to know about any arbitrary library; you need to know the source URL to give it.

For any custom module project, you can use `git` or `file` download `type` to retrieve it from a git repo or an HTTP source.

```
projects[example][type] = "module"
projects[example][subdir] = "custom"
projects[example][download][type] = "git"
projects[example][download][url] = "git://github.com/jane_doe/example.git"
projects[example][branch] = "dev"

projects[example][type] = "module"
projects[example][download][type] = "file"
projects[example][download][url] = "http://example.com/example.tgz"
projects[example][subdir] = "custom"

```

The same for libraries

```
libraries[ckeditor][download][type]= "get"
libraries[ckeditor][download][url] = "http://download.cksource.com/CKEditor/CKEditor/CKEditor%203.4/ckeditor_3.4.zip"
libraries[ckeditor][directory_name] = "ckeditor"
libraries[ckeditor][destination] = "libraries"

```

Lastly, for local files you can use the `file://` protocol in the `url` property to source the file from the local machine. See the Drush makefile docs for more information.
> 2 votes

---
Tags: drush
---


# Question
Title: Views Bulk Operations execute php loop over reference values
I am trying to finalize migration from d6 content profile to d7. I'd like to execute an arbirary php script using VBO to set a multi value entity reference field(users) based on the authors of a multi value node reference(bio content type) field.

I am looking for proper syntax for looping through each node reference item and populating the entity(user) reference with the uid from that node.

**Final working solution:**

```
$containing_node = node_load($entity->nid); //$nid is what node if you get from VBO
$w_containing_node = entity_metadata_wrapper('node', $containing_node);
$references = field_get_items('node', $containing_node, 'field_res_mem');
   foreach($references as $index => $value) {
     $my_index = 0;
     $reference_nid = $value['nid'];
     $rnode = node_load($reference_nid);
    $ruid = $rnode->uid;
    $w_containing_node->field_res_memuser[] = $ruid;
  }
$w_containing_node->save();

```

# Answer
For any field that has multiple values you can use `field_get_items()` to retrieve all values. For your specific case with the entity reference field, you'll need to retrieve the `target_id` property from each field item.

```
  $node = node_load($nid); //$nid is the node id you get from VBO
  $references = field_get_items('node', $node, 'field_MY_REFERENCE_FIELD');
  foreach($references as $index => $value) {
    $reference_nid = $value['target_id'];
    //@TODO: use $reference_nid to retrieve anything about referenced node
  }

```
> 0 votes

---
Tags: entities, views
---


# Question
Title: How to implement a Dropbox-like functionality for authenticated users to upload files?
I want to give my users some sort of upload functionality - kind of like a Dropbox. The Dropbox client module seems to have many bugs and the patches aren't fixing them for me.

So basically I am looking for users to be able to JUST upload files.

I don't want them to be able to view files which have been uploaded by others.

Any suggestions about a suitable solution?

# Answer
Check out the filedepot module.

> The filedepot module is full featured Document Management module that has a google docs like feel. It fulfills the need for an integrated file management module supporting role and user based security. Documents can be saved outside the Drupal public directory to protect documents for safe access and distribution.

It works great as a ftp-like solution which allows users to upload files, except that it has a UI and is accessible the same way as default drupal pages. Lots of configuration available so you can limit the actions of users. You can also integrate organic groups with filedepot and create groups and folders available only to certain groups, if you want to get into private files for users.

or create a webform for authenticated users only and give them a file upload widget. Then you can browse the submissions in a tabular format. This allows users to upload files but not browse them if you set the permissions up properly. They will still be able to see their upload of course.
> 4 votes

# Answer
All you need is the File Entity module. It provides a permission called "add and upload new files" that will do just what you want.
> 4 votes

# Answer
# Modules with a stable D7 release

### Scald (D6 beta and D7)

Here is a quote about the Scald: Media Management made easy module (from its project page):

> ... a popular and flexible way to handle media in Drupal.
>
> Scald can handle images, video, audio, tweets and even Flash files. Scald works with YouTube, Vimeo, Soundcloud and other many other providers. You can see a full list on the scald provider's page, you can also read our FAQ.
>
> For end-users Scald is a great option because you can use Scald with popular editing tools such as CKEditor, and with Plupload for multiple file uploads. Scald also has a very user-friendly media library, based on Views.
>
> For developers, one of the best things about Scald is that it treats all files as full-blown fieldable entities.
>
> Finally, Scald has been proven to scale. Some Scald sites have nearly a million media items. Users include Radio France (national public radio), ARTE (the Franco-German TV network), Le Figaro (the biggest newspaper in France). Scald is optimized for performance and uses its own caching system that works well with other caching layer (core filter cache etc.)

### Take Control (D6 and D7)

Here is a quote about the Take Control module (from its project page):

> ... is a set of set of modules for Drupal for managing various administrative tasks particularly related to the file system. Beginning with version 2.0, the module has been refactored into a core/add-on architecture, where a core module take\_control provides common routines and settings, whereas the bulk of front-end user interaction comes from add-on modules (e.g. file browser etc).
>
> Currently, there are 2 add-on modules:
>
> 1. **File Browser**: A complete File Browser/File Manager for Drupal. Allows you to manage your Drupal file-system directly through Drupal without needing FTP or your Hosting Control Panel access.
> 2. **Quick Permissions**: Many Drupal administrators are troubled by the: Drupal\_Security\_Do\_Not\_Remove\_See\_SA\_2006\_006 directive in Drupal file-system root's .htaccess file that effectively prevents write access to the file-system folder outside Drupal. This module allows you to take control of the file-system folder by specifying custom permissions on it from Drupal. Additionally, you can specify custom permission / delete any directory/file owned by Drupal using this module.

### Filedepot (D6 and D7)

Here is a quote about the Filedepot module (from its project page):

> ... is full featured Document Management module that has a google docs like feel. It fulfills the need for an integrated file management module supporting role and user based security. Documents can be saved outside the Drupal public directory to protect documents for safe access and distribution.
>
> Checkout the filedepot\_linkit module which supports browsing and inserting filedepot links from WYSIWYG editors.

### Document (D6 and D7)

The Document module is a *Document Management System* for Drupal. Here is a quote about it (from its project page):

> Features:
>
> * Complete integration with Drupal node system. This module adds a custom Node Type, Document. Each Document you create is a Drupal node, and hence enjoys all features available to a node.
> * Support for Document revisions/versioning - This module allows you to maintain multiple versions/revisions of the same document.
> * Views 2 Integration - The custom fields added by the module to the Document node type are accessible in Views, plus the module provides some useful out-of-the box Views.
> * Theming support
> * Searching - The documents being nodes are fully indexable by the Drupal search system. In addition, the module provides its own custom search for Documents.
> * A couple of blocks are available for document search that can be placed flexibly in your theme layout.

### elFinder file manager (D7)

The elFinder module integrates with elFinder, which is a open source AJAX file manager. Here is a quote about it (from its project page):

> Features:
>
> * Integrated with WYSIWYG API capable editors: CKEditor, FCKeditor, TinyMCE, BUEditor (D6), jWYSIWYG (D6), YUI, WYMeditor.
> * Multiple file upload.
> * File copying/moving with Drag & Drop support.
> * Quick file and directory rename.
> * Image resizing.
> * Lightbox-preview.
> * Context menu with generic file/directory operations.
> * Inline text file editing.
> * Favourites directory list.
> * Directory selection history.
> * Working with archives.
> * File descriptions.

### CMIS API (D7)

The CMIS API module aims to provide a generic API for integrating with CMIS compliant Enterprise CMS (ECM) systems.

# Modules with an unstable D7 release or for D6 only

There are a few more modules that might look like a possible fit, though they are, in general, perceived as rather buggy / unstaled, or only support old (D6) Drupal releases so far. Below are some more details about those modules.

### Media (D7, but perceived unstable these days)

Here is a quote about the Media module (from its project page):

> The Media module provides an extensible framework for managing files and multimedia assets, regardless of whether they are hosted on your own site or a 3rd party site - it is commonly referred to as a 'file browser to the internet'.
>
> Media is a drop-in replacement for the Drupal core upload field with a unified User Interface where editors and administrators can upload, manage, and reuse files and multimedia assets. Any files uploaded before Media was enabled will automatically take advantage of the many of the features it comes with.

### Media Browser Plus (D7, though only a beta version)

There is also the Media Browser Plus module, which is an enhancement module for the Media module, with additions such as:

* Adding tags to media when uploading.
* Searching media.
* Hierarchical taxonomy based organization e.g. “folders".
* Mirroring folder taxonomy to filesystem"
* Drag & Drop to move files between folders.
* Multi selection of files.
* Bulk operations on files.
* Media Basked to download multiple files at once.

### Asset (D7, though only a beta version)

Here is a quote about the Asset module (from its project page):

> ... proposes a new approach to the media management in Drupal, resolving a long-standing problem of reusable media files (images, videos, documents, etc) that evolved into the problem of reusable media content (images/videos/documents/etc with the attached content like description/licence/etc).
>
> The Asset module provides new entity called Media Asset and the set of Media Assets examples (Image, Video, Audio, Document, Image Gallery, Free HTML), which can be enabled optionally.

### Web File Manager (D6)

The 'Web File Manager' module is for D6 only. And issue WebFM for Drupal 7 has status *Closed (Won't fix)*. But there is also an ongoing discussion about a Ground-up rewrite of WebFM.
> 1 votes

# Answer
I created a new module that supports file uploads from various third-party services such as Dropbox, Google Drive, Box, OneDrive and Instagram:

I am planning to add more plugins in the future. Also the built-in plugin API allows other developers created their own plugins. Check `Example.php` plugin and `file_chooser_field/modules/file_chooser_field_instagram/plugins/Instagram.php`

The module uploads only user files (using user's account), it is not using shared folders/files.
> 0 votes

---
Tags: 7, users
---


# Question
Title: Drush, Omega 4 - Does not seem to recognize Drupal site
I've installed Drupal 7, Drush 7.0 and the Omega 4 theme. I'm using MAMP. Drush does not seem to recognize the /Applications/MAMP/htdocs/newsite/ as a Drupal folder (which it is). I'm attempting to create an Omega subtheme with the command line.:

drush omega-wizard

I then receive the following error:

And then this when I debug:

Thoughts? Help!!!

-Logan

# Answer
Not sure what has caused this but the solution is:

1) Enable the Omega theme (`drush en omega`) and set as default (`drush vset theme_default omega`)

2) Run `drush omega-wizard`
> 0 votes

---
Tags: drush, theming
---


title: Drush dl fails at untarring step

text:
# Question
Title: Drush dl fails at untarring step
I have drush 6.2.0.0 installed (via pear) on a synology NAS (Busybox). When attempting to use drush dl, it fails at the step where the downloaded file is to be untarred (see code box below for --debug messages). I did transiently have it working in April 2013, but have since made some changes to my system, and have been unable to re-produce my working setup.

I have tried all previous stable drush versions back to 5.4.0, with the same problem. If I manually repeat the steps from the cli, everything works fine, so I suspect that it is something to do with version incompatibility with the tar command drush is calling, but have been unable to find a way to get it to work.

```
drush dl views_raw_sql --debug
BusyBox v1.16.1 (2013-11-06 05:34:06 CST) multi-call binary.

Usage: dirname FILENAME

Strip non-directory suffix from FILENAME

Bootstrap to phase 0. [0.01 sec, 2.37 MB]                            [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drush() [0.02 sec, 2.49 MB] [bootstrap]
Cache HIT cid: 6.2.0-commandfiles-0-13d519746b450041a028af739ac40466 [0.03 sec, 2.5 MB]                                                                                [debug]
Bootstrap to phase 0. [0.3 sec, 5.76 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_root() [0.49 sec, 5.76 MB]                                                                                [bootstrap]
Initialized Drupal 7.24 root directory at /web/rooms [0.53 sec, 6.69 MB]                                                                                [notice]
Drush bootstrap phase : _drush_bootstrap_drupal_site() [0.53 sec, 6.7 MB]                                                                                [bootstrap]
Initialized Drupal site default at sites/default [0.54 sec, 6.7 MB]                                                                                [notice]
Cache HIT cid: 6.2.0-install_profile-66ecfeb9791a023150773849f1550c5d [0.54 sec, 6.7 MB]                                                                                [debug]
Cache HIT cid: 6.2.0-commandfiles-2-699657487b88e8b0c2ede2984aa12913 [0.54 sec, 6.7 MB]                                                                                [debug]
Drush bootstrap phase : _drush_bootstrap_drupal_configuration() [0.55 sec, 6.7 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_database() [0.56 sec, 6.71 MB]                                                                                [bootstrap]
Successfully connected to the Drupal database. [0.56 sec, 6.71 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_full() [0.58 sec, 7.16 MB]                                                                                [bootstrap]
Cache HIT cid: 6.2.0-install_profile-66ecfeb9791a023150773849f1550c5d [1.21 sec, 23.47 MB]                                                                                [debug]
Cache HIT cid: 6.2.0-commandfiles-5-bbe78d7a9b386ee3452d706cd9cfae92 [1.22 sec, 23.48 MB]                                                                                [debug]
Drush bootstrap phase : _drush_bootstrap_drupal_login() [1.23 sec, 23.79 MB]                                                                                [bootstrap]
Successfully logged into Drupal as Anonymous (uid=0) [1.25 sec, 23.96 MB]                                                                                [bootstrap]
Found command: pm-download (commandfile=pm) [1.25 sec, 23.96 MB]                                                                                [bootstrap]
Loading version_control engine. [1.76 sec, 24.14 MB]                                                                                [notice]
Loading package_handler engine. [1.77 sec, 24.15 MB]                                                                                [notice]
Executing: wget --version
Loading release_info engine. [1.79 sec, 24.18 MB]                                                                                [notice]
Including /usr/syno/php/share/pear/drush/commands/pm/download.pm.inc [1.81 sec, 24.28 MB]                                                                                [bootstrap]
Calling hook drush_pm_download_validate [1.81 sec, 24.36 MB]                                                                                [debug]
Returned from hook drush_pm_download_validate [1.81 sec, 24.36 MB]                                                                                [debug]
Calling hook drush_pm_download [1.81 sec, 24.37 MB]                                                                                [debug]
Downloading release history from http://updates.drupal.org/release-history/views_raw_sql/7.x [1.82 sec, 24.37 MB]                                                                    [notice]
Executing: wget --version
  GNU Wget 1.10.1

  Copyright (C) 2005 Free Software Foundation, Inc.
  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  Originally written by Hrvoje Niksic <hniksic@xemacs.org>.
Executing: wget -q --timeout=30 -O /tmp/download_file6l316N http://updates.drupal.org/release-history/views_raw_sql/7.x
Calling drush_delete_dir(/tmp/views_raw_sql7H5oRi, 1) [2.48 sec, 24.37 MB]                                                                                [debug]
Calling is_readable(/tmp/download_file6l316N) [2.49 sec, 24.37 MB]                                                                                [debug]
Calling is_writable(/tmp) [2.49 sec, 24.37 MB]                                                                                [debug]
Calling rename(/tmp/download_file6l316N, /tmp/views_raw_sql7H5oRi) [2.49 sec, 24.37 MB]                                                                                [debug]
Downloading project views_raw_sql to /tmp/drush_tmp_1386803829_52a8f27534ca9 ... [2.49 sec, 24.38 MB]                                                                                [notice]
Executing: wget -q --timeout=30 -O /tmp/download_filebSRmyk http://ftp.drupal.org/files/projects/views_raw_sql-7.x-1.0-rc1.tar.gz
Calling is_readable(/tmp/download_filebSRmyk) [3.02 sec, 24.38 MB]                                                                                [debug]
Calling is_writable(/tmp/drush_tmp_1386803829_52a8f27534ca9) [3.02 sec, 24.38 MB]                                                                                [debug]
Calling rename(/tmp/download_filebSRmyk, /tmp/drush_tmp_1386803829_52a8f27534ca9/views_raw_sql-7.x-1.0-rc1.tar.gz) [3.02 sec, 24.38 MB]                                               [debug]
Downloading views_raw_sql-7.x-1.0-rc1.tar.gz was successful. [3.02 sec, 24.38 MB]                                                                                [notice]
Calling md5_file(/tmp/drush_tmp_1386803829_52a8f27534ca9/views_raw_sql-7.x-1.0-rc1.tar.gz) [3.02 sec, 24.38 MB]                                                                       [debug]
Md5 checksum of views_raw_sql-7.x-1.0-rc1.tar.gz verified. [3.02 sec, 24.38 MB]                                                                                [notice]
Mime type for /tmp/drush_tmp_1386803829_52a8f27534ca9/views_raw_sql-7.x-1.0-rc1.tar.gz is application/x-gzip [3.03 sec, 24.38 MB]                                                    [notice]
Calling chdir(/tmp/drush_tmp_1386803829_52a8f27534ca9) [3.03 sec, 24.38 MB]                                                                                [debug]
Executing: tar -C /tmp/drush_tmp_1386803829_52a8f27534ca9 -xzf views_raw_sql-7.x-1.0-rc1.tar.gz
/usr/local/php/bin/tar: 2>&1: Not found in archive
/usr/local/php/bin/tar: Exiting with failure status due to previous errors
Calling chdir(/volume1/web/rooms) [3.04 sec, 24.39 MB]                                                                                [debug]
Unable to untar /tmp/drush_tmp_1386803829_52a8f27534ca9/views_raw_sql-7.x-1.0-rc1.tar.gz. [3.04 sec, 24.39 MB]                                                                    [error]
Using destination directory sites/all/modules [3.04 sec, 24.39 MB]                                                                                [notice]
Verifying signature for svn version control engine. [3.04 sec, 24.39 MB]                                                                                [debug]
Executing: svn info sites/all/modules
sh: /usr/local/php/bin/svn: not found
Verifying signature for bzr version control engine. [3.05 sec, 24.4 MB]                                                                                [debug]
Executing: bzr root sites/all/modules
sh: /usr/local/php/bin/bzr: not found
Calling _drush_recursive_copy(/tmp/drush_tmp_1386803829_52a8f27534ca9/views_raw_sql, sites/all/modules/views_raw_sql) [3.06 sec, 24.39 MB]                                            [debug]
copy(/tmp/drush_tmp_1386803829_52a8f27534ca9/views_raw_sql): failed to open stream: No such file or directory filesystem.inc:257 [3.06 sec, 24.39 MB]                             [warning]
Project views_raw_sql (7.x-1.0-rc1) could not be downloaded to sites/all/modules/views_raw_sql. [3.06 sec, 24.39 MB]                                                              [error]
Returned from hook drush_pm_download [3.06 sec, 24.39 MB]                                                                                [debug]
Command dispatch complete [3.06 sec, 24.37 MB]                                                                                [notice]
 Timer  Cum (sec)  Count  Avg (msec)
 page   2.514      1      2514.15
Peak memory usage was 25.5 MB [3.07 sec, 24.37 MB]                                                                                [memory]

```

# Answer
> 5 votes
Since there is no solution accepted and I had spent hours figuring it out. First I ran the drush command with the debug option to see what's the problem.

```
drush dl entity --debug

```

I knew that drush could not untar and it needed bsdtar.exe file on windows. I downloaded bsdtar.exe from Google code bsdtar.exe from Google Code I downloaded it and set the path to it, see image. I tried the drush command again and it worked.

# Answer
> 1 votes
It looks like, for some reason, your drush is looking for the **tar** binary in

```
/usr/local/php/bin/tar

```

it should be something like:

```
/bin/tar

```

Maybe you've done something funky with your environment variable PATH configuration. You can `echo $PATH` to test.

If you can't figure out why the path to tar is wrong, a workaround would be to symlink /usr/local/php/bin/tar to /bin/tar (assuming the latter is present)

To locate tar, type

```
whereis tar

```

Then you could create a symlink from the one drush is trying to use to the actual tar binary

e.g:

```
sudo mkdir -p /usr/local/php/bin
sudo ln -s /bin/tar /usr/local/php/bin/tar

```

---
Tags: drush
---


title: Taxonomy view resulting content fields

text:
# Question
Title: Taxonomy view resulting content fields
I have a view that lists a set of taxonomy terms. When the user clicks on one of the taxonomy terms in the view it sends them to a results page showing a list of all the content types that have this taxonomy term. The problem is views made this results page without any options for me to change it. Right now it only shows the title field and a read more link. I would like to add more of the content types fields to the result. For example the content type has images One thing i would like to do is add the image field to that results page so each result has an image. How do you add fields to the views results page that is after the user clicks the term on the taxonomy view.

Current view shows a list of taxonomy terms. When user clicks on one of the taxonomy terms in the view it will send them to a page showing a list of content that are associated with that taxonomy term. I want to edit the list of content that is associated with the selection, not the list of taxonomy terms.

# Answer
By default the output at *taxonomy/term/%* (with % being the term ID) is a collection of teasers for nodes to which the term ID is assigned.

You can alter the teaser display for each content type by going to *Structure \> Content types \> \[type\] \> Manage Display \> Teaser*. This is the simplest method, but note that this will alter the teaser display for the content type site-wide, not just on the taxonomy term results page.

If you want to alter the overall display of the results and you don't want to alter the teaser output everywhere else, @ShawnCohen's answer is your best bet. Views provides some powerful options for customizing a result set, including *Relationships* (mentioned by @Screenack in the comments).
> 2 votes

# Answer
The "results page" you're talking about is a display set up by the Taxonomy module.

Views allows you to override this display by going to the Views administration page (**/admin/structure/views**) and clicking **Enable** on the **Taxonomy term** view. From there you can edit the view and change the fields just as you can with your original taxonomy view.
> 1 votes

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


title: Include Vimeo's Froogaloop library

text:
# Question
Title: Include Vimeo's Froogaloop library
I have a custom module that has a JavaScript file in it. The JavaScript file is calling on the Vimeo API, which has a custom library created for it (similar to jQuery).

How can I use this library in the custom module's .js file? I've tried putting Froogaloop (the Vimeo library) inside of sites/all/libraries and then using its syntax it in the .js file within the custom module, but it's not picking the library up.

# Answer
> 1 votes
Is your js file even working?

Is your JavaScript file jQuery?

**In Drupal, you wrap your jQuery code like this**

```
(function ($) {

    //code goes here

})(jQuery);

```

For Example:

```
(function ($) {

    $(document).ready(function() {
         $(".button").click(function () {
             $(this).next('.content').hide();
         });
    });

})(jQuery);

```

**Not sure if you did this already.**

Did you also add the frugaloop js to your module? Putting it on the libraries folder doesn't do anything unless you call it.

Use the function drupal\_add\_js to call it.

---
Tags: javascript
---


# Question
Title: How to import a Google calendar so that it can be styled?
I am wondering if anyone has any ideas regarding solutions for a custom/styled Google Calendar embed on a Drupal Website. I have a client that would like their events updated via Google calendar but is displeased with the look of Google Calendar.

I have tried tons of different modules, but nothing seems to really work well. The FullCalendar module came the closest, but the calendar appeared empty (same for other modules as well - just no events appeared in it).

I did try using the Aggregator module, but it includes some extra fields and the information shows up in Spanish for some reason!

Any help would be greatly appreciated! I'm pulling my hair out trying to figure out a way to just import these freaking Google Calendar events, or embed the calendar in a way that it is styleable.

# Answer
> 0 votes
If you are embedding it using iframe, you cannot style it with your own css or javascript as this would be considered **cross site scripting**.

Basically you cannot style or alter anything that is not in your own domain.

The only possible way to style it would be if Google Calendar has a setting on their website to change the style, but you would only be able to do that through their website.

---
Tags: datetime, feeds, javascript
---


# Question
Title: Views suggestion preprocessor template.php and views-view-field--suggestion.tpl.php working in harmony?
This is tricky to explain properly...

I have a view, and I want to override the output of one of the fields, so I created a template.tpl.php file, called:

```
views-view-field--frontpage-fold--page--field-video-background-files.tpl.php

```

I at first had the logic in that file, and everything worked as expected. Great!

Then to conform with best practice, I moved the logic part (that was at the start of my .tpl.php file), to a theme function override thingy. This looks like:

```
function MY_THEME_views_view_field__frontpage_fold__page__field_video_background_files(&$variables) {

```

And that works fine... With an exception.

THEY DON'T WORK TOGETHER!

Depending on how I fiddle around with clearing caches, and using views 'Rescan Template Files' button, I either get one working, or the other. Not both.

The result of this is that it's impossible to separate my logic into a template.php file and pass variables to my .tpl.php file.

Does anyone have any idea why this might be?

I'm fairly new to Drupal, and have found the following pieces of information, but don't quite understand what they're saying...

https://stackoverflow.com/questions/10433853/drupal-7-preprocess-views-not-working https://stackoverflow.com/questions/2383865/how-do-i-use-theme-preprocessor-functions-for-my-own-templates/2387782#2387782 https://www.drupal.org/node/939462

Can anyone clear this up for me, and suggest a solution?

# Answer
I think what you are looking for is:

```
function MY_THEME_views_view_field__frontpage_fold__page__field_video_background_files_preprocess(&$variables, $hook) {

```

Note the addition of *\_preprocess* at the end of your function name.

https://api.drupal.org/api/drupal/modules!system!theme.api.php/function/hook\_preprocess/7
> 0 votes

---
Tags: views, theming
---


title: How to redirect /user to /user/login

text:
# Question
Title: How to redirect /user to /user/login
My client wants the only login url to be /user/login So I need to redirect /user to /user/login

any idea how to accomplish this?

# Answer
You can use rules module to create a redirect when *anonymous* user view the `/user` page.

> The Rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module.

You can follow below step:

* Go to Administration -\> Configuration -\> Workflow -\> Rules
* Click on *Add new rule* link in top of page
* Fill the *name* and select `Drupal is initializing` from *React on Event* drop down in the form and save the form.
* click on *Add Condition* link in the page and select *User has role(s)* from the "Condition to add" drop-down and select `anonymous user` as user role and save the form.
* Click on *Add condition* link and select "Data comparison" from the "Condition to add" drop-down and set `site:current-page:path` as "Data selector" and click on continue button and set 'user' in the `value` field and save the form.
* Click on *Add Action* link and select `Page redirect` event and set `user/login` in the value field and save the form.
> 6 votes

# Answer
You can use the hook\_menu\_site\_status\_alter():

```
/**
 * Implements hook_menu_site_status_alter().
 */
function MODULENAME_menu_site_status_alter(&$menu_site_status, $path) {
  if (user_is_anonymous()) {
    if ($path == 'user') {
      drupal_goto('user/login');
    }
  }
}

```

Here is an example on how another module implement this hook.
> 3 votes

# Answer
Option 1: Refer the https://www.drupal.org/project/rename\_admin\_paths module. The purpose of this module is to secure drupal backend by overriding admin path.

Option 2: You can also redirect /user to /user/login by writing redirect rule in .htaccess file.
> 1 votes

---
Tags: 7, redirection
---


# Question
Title: Saving existing node doesn't update automatic alias
I have a node with pattern `/route/[node:title]`. Whenever I save a new node with automatic alias checked it saves perfectly.

Whenever I edit an existing node with Generate automatic alias checked it doesn't update the URL to the new title but instead keeps the old one. When I go back to editing I see that Generate automatic alias is unchecked all of a sudden and an alias is in place(The old title).

I'm using Pathauto and Pathauto persist but can't seem to find the problem, even when disabling and uninstalling Pathauto persist.

# Answer
Have you checked your settings at "admin/config/search/path/settings"? There you can config what to do with your alias, when an entity is updated.
> 6 votes

---
Tags: path-aliases
---


title: drupal_add_js not working

text:
# Question
Title: drupal_add_js not working
I have this code in my javascript:

```
(function ($) {
    Drupal.behaviors.myid_print_table_id_link = {
        attach: function (context, settings) {
            $.ajax({
              type: 'POST',
              url: '?q=myid_print/table_pager',
              success: function(data) {
                console.log(data);
              }
            }).done(function(o) {
              console.log(o);
            });
        }
    }
})(jQuery);

```

This calls a function called `myid_print_table_pager` declared in my hook menu:

```
 function myid_print_menu(){

     $items = array();
     $items['myid_print/table_pager'] = array(
         'title' => 'Table Pager',
         'page callback' => 'myid_print_table_pager',
         'type' => MENU_CALLBACK,
     );
     return $items;
  }
 }

```

Below is my function:

```
function myid_print_table_pager(){
    drupal_add_js('$(document).ready(function () { alert("Hello!"); });', 'inline');
    watchdog('message', 'I've been here!');
}

```

I'm pretty sure that the function `myid_print_table_pager` is invoke because `'I've been here!'` is seen in my `watchdog` table in my database. But why does the alert with the message `Hello!` has not been invoke?

# Answer
> 3 votes
I usually avoid calling `drupal_add_js()` and use the `#attached` property of the render array. The advantage of using #attached is that you don't need to implement additional hooks, the js is only added when needed, and (as I've been told) it works better with caching. Your code would look something like this:

```
function myid_print_menu() {
  $items = array();
  $items['myid_print/table_pager'] = array(
    'title' => 'Table Pager',
    'page callback' => 'myid_print_table_pager',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function myid_print_table_pager() {
  $build = array(
    '#markup' => 'Hello world!',
    '#attached' => array(
      'js' => array(
        array(
          'data' => '$(document).ready(function () { alert("Hello!"); });',
          'type' => 'inline',
        ),
      ),
    ),
  );
  return $build;
}

```

Disclaimer: untested code, please let me know if it doesn't work as expected.

# Answer
> 0 votes
You'ld better use hook\_page\_build to add your JS.

```
/**
 * Implements hook_page_build().
 */
function MYMODULE_page_build(&$page) {
  drupal_add_js('
    jQuery(document).ready(function () {

      console.log("Hello!");
      // Do your magic here:

    });', 'inline');
}

```

# Answer
> 0 votes
Try

```
function myid_print_table_pager(){
     drupal_add_js('(function($){$(document).ready(function(){alert("Hello!");});})(jQuery);', 'inline');
     watchdog("message", "I've been here!");
}

```

And

```
(function ($) {
    $(document).ready(function() {
        Drupal.behaviors.myid_print_table_id_link = {
            attach: function (context, settings) {
                $.ajax({
                  type: 'POST',
                  url: '?q=myid_print/table_pager',
                  success: function(data) {
                    console.log(data);
                  }
                }).done(function(o) {
                  console.log(o);
                });
            }
        }
    });
})(jQuery);

```

---
Tags: 7, ajax, routes, javascript
---


# Question
Title: Views - Excluding a nid screws up "More" link
I have a view for my news overview in which I'd like to show 5 latest items. This works perfectly. Until I want to exclude the NID i'm on right now.

I exclude the NID by using the contextual filter and exclude the current Nid.

However; this screws up the More link attached to the view. It wants to go to the excluded NID now(Because of the contextual I think).

How do I get the More link to go to my news overview(As it is without the contextual filter) but still exclude the current NID?

# Answer
1. Add "Content: Nid (Nid)" field and mark it 'Exclude from display'.
2. Now add "Global: Custom text" field, in its configuration add 'More link' into text box and then select "Output this field as a link" under REWRITE RESULTS and provide node/\[nid\] as a link path.
> 0 votes

---
Tags: views
---


# Question
Title: Insert *whatever* every nth row in Views
I am looking for a solution to insert "something" every nth row in a view. Technically, that "something" will be an Ad, but in Drupal terms it could be a block, a node, an entity, custom html row...really anything that can point me in the right direction.

# Answer
In under `Theme: Information` you'll find `Style output: views-view-table.tpl.php ...`. Override that. I selected the Theming info as opposed to other template overrides available because that is the one that has a `foreach` for rows. In your override you can add a counter to the `foreach()` along with an `if($counter%10 == 0) { ... }` with some markup or call to a block or something like that.
> 3 votes

# Answer
I would implement hook\_views\_pre\_render. Loop through and append, edit, or create new entries into `$view->result` as needed.

Using this approach you'd be injecting hand-picked stuff into your Views raw resultset and might be limited in your row style output unless you digged into Views quite a bit to override the row display handler (which I think is doable).
> 1 votes

# Answer
I think doing it in hook\_views\_post\_execute works best.

```
<?php

/**
 * Implements hook_views_post_execute().
 */
function my_module_views_post_execute(&$view) {
  $entity_id = my_module_fetch_entity_id(); //Random function
  $view->result[] = (object) [
    'entity' => $entity_id,
  ];
}

```

Source: https://bitbucket.org/snippets/intracto/eax4/drupal-insert-an-entity-in-a-views-result
> 0 votes

# Answer
If you want to print custom code after every nth (for example 4th) row **and keep the odd/even sequence** you can simply edit default views template.

Place right into your theme's folder this file `views-view-unformatted--taxonomy-term--page.tpl.php` with this code and you will see "*Your custom code goes here*" text after 4th row in default *Taxonomy term views*:

```
<?php foreach ($rows as $id => $row): ?>
  <div class="<?php
  switch ($id) {
    case 1:
    case 3:
    case 4:
    case 6:
    case 8:
    //add more IDs if you have more rows than 10 in your views
      $myclasses = 'views-row-even row';
    break;

    default:
      $myclasses = 'views-row-odd row';
  }
  print $myclasses; ?>"><?php print $row; ?></div>
  <?php if ($id == 3): ?>
    <div class="views-row-odd row">Your custom code goes here</div>
  <?php endif; ?>
<?php endforeach; ?>

```

Based on this solution: http://www.jasom.net/how-to-add-custom-code-adsense-after-first-row-in-drupal-7-and-drupal-8-views-one-line-solution
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to implement "Add another item" for custom forms?
I am writing a module which is basically a form that creates a relation between two end points.

I want a user to be able to create multiple relations at once. I want to add a button which says "add another item" just like how fields have when you select unlimited in their settings.

Is there a way I can do this to custom forms too ?

# Answer
One way to do this is by setting the form fields/field sets within a for function. Create a seperate function to increment the value via a submit button callback for instance and rebuild the form after you increment.

```
for($x=1; $x<=$variabletoincrement; $x++){
(insert form fields/field sets )
}

```

Here is code from form\_example\_tutorial\_9 which shows information on how to create dynamic fields. This information is much more thorough than my explanation:

http://api.drupal.org/api/examples/form\_example!form\_example\_tutorial.inc/function/form\_example\_tutorial\_9\_add\_name/7

http://api.drupal.org/api/examples/form\_example%21form\_example\_tutorial.inc/function/form\_example\_tutorial\_9/7
> 12 votes

# Answer
### Drupal 8+

Check out Example module's `AjaxAddMore.php`.

### Drupal 7

To have a simple and working code example:

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

  // #tree will ensure the HTML elements get named distinctively.
  // Not just name=[name] but name=[container][123][name].
  $form['#tree'] = TRUE;

  if (empty($form_state['number_names'])) {
    $form_state['number_names'] = 1;
  }

  for ($i = 1; $i <= $form_state['number_names']; $i++) {

    $form['container'][$i] = [
      '#type' => 'container',
    ];
    $form['container'][$i]['name'] = [
      '#type' => 'textfield',
      '#attributes' => ['placeholder' => t('Name')],
      '#size' => 20,
      '#required' => TRUE,
    ];
  }

  $form['add_item'] = [
    '#type' => 'submit',
    '#value' => t('Add another name'),
    '#submit' => ['MYMODULE_MYFORM_add_item'],
  ];

  if ($form_state['number_names'] > 1) {

    $form['remove_item'] = [
      '#type' => 'submit',
      '#value' => t('Remove latest name'),
      '#submit' => ['MYMODULE_MYFORM_remove_item'],
      // Since we are removing a name, don't validate until later.
      '#limit_validation_errors' => [],
    ];
  }

  // $form['submit'] = [
  //   '#type' => 'submit',
  //   '#value' => 'Submit',
  // ];

  return $form;
}

function MYMODULE_MYFORM_add_item($form, &$form_state) {

  // All we need is to increase the number used in our for loop above ...
  $form_state['number_names']++;
  // ... and rebuild our form.
  $form_state['rebuild'] = TRUE;
}

function MYMODULE_MYFORM_remove_item($form, &$form_state) {

  // Just the other way around until only one item is left ...
  if ($form_state['number_names'] > 1) {
    $form_state['number_names']--;
  }
  // ... and form rebuild again.
  $form_state['rebuild'] = TRUE;
}

```
> 10 votes

---
Tags: forms
---


# Question
Title: jQuery.browser.msie depreciated in 1.9 trying to fix in Drupal 7
The design template I am using needs jQuery 1.9. But Drupal 7 doesn't seem to support 1.9. Please correct me if I'm wrong The issue is that when in import jQuery 1.9 in Drupal 7 then here is the following error when in admin (overlay) trying to add content:

```
 Uncaught TypeError: Cannot read property 'msie' of undefined

```

This is coming from `overlay-parent.js`. It has the following code:

```
if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 8) {

```

It's causing an error because I am importing jQuery 1.9 and Drupal 7 runs code that contains the deprecated and removed `jQuery.browser` method.

The problem is that, after updating the code in `modules/overlay/overlay-parent.js` to:

```
if (navigator.userAgent.match(/msie/i) && navigator.userAgent.match(/7/)) {

```

These changes are not taking effect. Perhaps this has to be compiled into some minimized `.js` file but I am not sure. How to make these changes in Drupal 7? Any alternative ways to make jQuery 1.9 compatible Drupal 7?

# Answer
Drupal ships with a particular version of jQuery.

Using a different version of jQuery means refactoring various core javascript code.

If you want to use a more recent jQuery version, you can check the available versions provided by the jquery\_update module which provides that refactored replacement javascript.
> 2 votes

# Answer
I had the same problem, I didn't want use lower Jquery version, so I resolve problem with `#2` tiny patch in this page
> 0 votes

---
Tags: theming, javascript
---


# Question
Title: How to Filter views result by current logged in user's role
I know it can be done using PHP Code I am looking an option which will be using configurations.

# Answer
Try adding view relationship to "Content: Author", and then add contextual filter for field "(author) User: Roles".
> 4 votes

# Answer
This will help you

Can you filter views user list result based on the current users role
> 0 votes

# Answer
Currently logged-in user can be achieved by using `global variable`

```
<?php

global $user;

if (in_array('administrator', $user->roles)) {
        // do something
}

```
> 0 votes

---
Tags: views
---


# Question
Title: Inserting based on the results of a select query
Initially I had all columns under 1 table. In table shown below had one additional column for all `media items`.

> did | disclaimer\_title | disclaimer\_body | disclaimer\_media\_items

But for some reasons, I need to pull out the `disclaimer_media_items` column into separate schema. **So now I have 2 tables**.

**Table 1 schema**

> did | disclaimer\_title | disclaimer\_body

**Table 2 structure:**

> did\_media | disclaimer\_media\_items

Now what I want is when I insert media in table 2, the results get stored for table 1.

i.e. **I want to achieve same functionality of all columns under table 1 with two individual tables.**

I know 2 things can work, either `foreign key` or `Drupal joins`. How can I achieve this?

*Hope I explained it well.*

# Answer
> 1 votes
db\_merge is the solution for this.

---
Tags: database
---


# Question
Title: How to access/print fields in non-Drupal php files?
I'm using Drupal's php filter to add php code in node body of some of my nodes. Among other things, I'm also including a php file. That php file is doing some non-Drupal work and it is included in those nodes properly. However, I can't print Drupal's fields in that file.

Here is an example of php code in node's body field:

```
<?php

some work is happening here

include 'non-drupal.php'; // include non-drupal php file

some work is happening here

?>

```

Here is an example of non-drupal.php:

```
<?php

echo date('h:i:s'); // This works

print $title; // This doesn't work

?>

```

When I open that node, I can see the time, but there's no node title displayed.

Is it possible to print node fields from "external" php files?

EDIT (code added from dropbucket) I have tried with adding this code from Dropbucket, but it's not working either):

```
<?php

echo date('h:i:s'); // This works

function get_node_title($nid) {
return db_query('SELECT title FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetchField();
} // This doesn't work (There is no output, but no errors displayed either)

?>

```

# Answer
You could try it with drupal\_bootstrap, but it is not tested.

```
define('DRUPAL_ROOT', '/path/to/drupal');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$title = drupal_get_title();
echo $title;

```
> 2 votes

# Answer
Have you tried to used GLOBALS ? or drupal\_get\_title() ?

EDIT : Can you try instead :

```
$title = drupal_get_title()
// use your variable $title

```
> 0 votes

---
Tags: 7, nodes
---


title: Metatag on field collection page

text:
# Question
Title: Metatag on field collection page
I work on drupal 7, In content type add New **field** type **field collection**. Add content and use meta tag. In content page (node) meta tag display properly, In field collection page field-collection/field-name/id content display proper, we want to add meta tag (title, description, etc) of every field collection page.

# Answer
Using the metatag module, and context module, and the metatag content submodule thats bundled with metatag, you can assign metatags by nid or url. The problem would be that it wouldnt do this programmatically, but might be a quick fix if you havent got that many pages.

As far as I know, there isn't a way to use metatag to generate metatags based on tokens and patterns for a field collection.
> 0 votes

# Answer
By default, metatag support is disabled for field-collection-items. You can enable it by writing your own custom module implementing `hook__metatag_entity_type_is_supported_alter()` (see below). After enabling the custom\_module (or cache clear), you should be able to enable/disable metatags for field-collections under `admin/config/search/metatags/settings`. The field-collection metatag form elements won't appear on the host entity form (i.e. node form), but on the field-collection edit form.

*In my use-case I set the metatag values via the host-token to the host entity values, if an editor needs to set different values for a field collection item he needs to edit this particular item.*

```
/**
 * Implements hook_metatag_entity_type_is_supported_alter()
 *
 * Enable Metatag support for field-collection-items, to be able to set metatags
 * for gallery field-collection-items.
 */
function custom_module_metatag_entity_type_is_supported_alter(&$suitable, $entity_type, $entity_info) {
  // Enable Metatag support for field_collection_item's previously disabled in
  // metatag_entity_type_is_suitable().
  if ($entity_type == 'field_collection_item') {
    $suitable = TRUE;
  }
}

```
> 0 votes

---
Tags: entities
---


# Question
Title: How to resize <img> element within drupal block?
I created a custom block with *Full HTML* format selected using the following code:

`<img src="myimage.jpg" atl="myimage" width="xx" height="yy" />`

However, Drupal seems to always display the image at it's actual size. Is there a way to achieve this in a block?

# Answer
Is that everything that's in your block? I've tried to replicate this and it works fine for me.

Have you tried setting your CSS in the appropriate css file instead of adding it inline? Like:

```
#block-id-title img {
   height: 100px;
   width: 100px;
}

```

Or, try inspecting that img element in firebug or equivalent, and see how the css is being rendered. You might have a css styling set for all img tags which is unintentionally overriding your block image.
> 2 votes

---
Tags: 7, blocks
---


# Question
Title: How to stop redirecting to newest URL after updating a node
I have setup 2 aliases for each node of a content type called "property". The first alias is like example.com/texas/village-apartments and the second is example.com/texas/corp/village-apartments.

When you go to the second URL (the one with "corp") you see different pieces of information on the page, different buttons, menus and other items that do not really belong on a non-corp page.

Pathauto handles creating the first alias (without "corp"), then I manually created the corp aliases by going to admin/config/search/path/add and added each one.

This all works fine except for when I go to edit the node and add text or a picture or whatever. When I click save, I am redirected to the URL with corp and of course see different menus, blocks, etc.

Is there any way to configure things so that I am redirected back to the same URL path I was on when I clicked 'edit'?

Tim

# Answer
> 0 votes
There's no easy way. You might have to make your own module with code something like this:

```
function mymodule_node_presave(){
  $GLOBAL['dont_redirect']=true;
}
function mymodule_drupal_goto_alter(&$path){
  if ($GLOBAL['dont_redirect']==true){
    $path = "";
  }
}

```

# Answer
> 0 votes
Would this module work for your needs?

https://www.drupal.org/project/node\_save\_redirect

---
Tags: 7, path-aliases
---


title: Custom compound field update hook

text:
# Question
Title: Custom compound field update hook
I have a custom compound field working beautifully. Below is what I have defined in the hook\_field\_schema function:

```
function MODULE_field_schema(&$columns, &$indexes, &$keys) {
  $columns = array(
    'meat' => array(
      'type'        => 'int',
      'description' => 'Meat'
    ),
    'potatoes' => array(
      'type'        => 'int',
      'description' => 'Potatoes',
    ),
  );
}

```

Now I need to modify the schema like so:

```
function MODULE_field_schema(&$columns, &$indexes, &$keys) {
  $columns = array(
    'meat' => array(
      'type'        => 'int',
      'description' => 'Meat'
    ),
    'potatoes' => array(
      'type'        => 'int',
      'description' => 'Potatoes',
    ),
    'carrots' => array(
      'type'        => 'int',
      'description' => 'Carrots'
    ),
  );
}

```

The problem is that I am using this field on a few content types and I need a way to update those associated tables. Basically I need to know what hook I need to create to make this happen.

# Answer
I completed this in hook\_update\_n:

```
function MODULE_update_7201(&$sandbox) {

  // get all field names
  $field_names = array();
  $fields = field_info_instances('node');
  foreach ($fields as $node) {
    foreach ($node as $node_field => $field) {
      $field_names[$node_field] = TRUE;
    }
  }

  // load schema to update
  $columns = array();
  MODULE_field_schema($columns);

  // load all fields and check for type
  foreach ($field_names as $field_name => $junk) {

    // load field info
    $field = field_info_field($field_name);
    if ($field['type'] == FIELD_NAME) {

      // loop schema and check fields for existance
      foreach ($columns as $db_field_name => $db_field_schema) {
        if (!db_field_exists('field_data_' . $field_name, $field_name . '_' . $db_field_name)) {
          db_add_field('field_data_' . $field_name, $field_name . '_' . $db_field_name, $db_field_schema);
        }
        if (!db_field_exists('field_revision_' . $field_name, $field_name . '_' . $db_field_name)) {
          db_add_field('field_revision_' . $field_name, $field_name . '_' . $db_field_name, $db_field_schema);
        }
      }
    }
  }
}

```
> 2 votes

---
Tags: 7, entities
---


# Question
Title: Using ajax with pager in ctools modal window
Continuing my work from here, I have a modal window that displays a text field and submit button. When the form is submitted, a Solr search is run using ajax, and the first ten results are displayed in a table with a pager.

```
/**
 * Implementation of hook_menu.
 */
function nb_alters_menu() {
  $items = array();

  $items['imgsearch/%ctools_js/%node'] = array(
    'page callback' => 'imgsearch_page',
    'page arguments' => array(1, 2),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  $items['imgsearch/%ctools_js/imgadd/%/%'] = array(
    'title' => 'Add Image',
    'page callback' => 'nb_alters_add_image',
    'page arguments' => array(1, 3, 4),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Page callback for imgsearch modal popup window.
 */
function imgsearch_page($ajax, $node) {
  if ($ajax) {
  // Load the modal library and add the modal javascript.
    ctools_include('ajax');
    ctools_include('modal');

  $form_state = array(
    'ajax' => TRUE,
    'title' => t('Image Search Form'),
    'base_node' => $node,
  );

  // Add custom settings for form size.
  drupal_add_js(array(
    'imgsearch-modal-style' => array(
      'modalSize' => array(
        'type' => 'fixed',
        'width' => 750,
        'height' => 750,
      ),
    ),
  ), 'setting');

  // Use ctools to generate ajax instructions for the browser to create
  // a form in a modal popup.
  $output = ctools_modal_form_wrapper('imgsearch_form', $form_state);

  // If the form has been submitted, there may be additional instructions
  // such as dismissing the modal popup.
  if (!empty($form_state['ajax_commands'])) {
    $output = $form_state['ajax_commands'];
  }

  // Return the ajax instructions to the browser via ajax_render().
  print ajax_render($output);
    drupal_exit();
  }
  else {
    return drupal_get_form('imgsearch_form', $node);
  }
}

/**
 * Drupal form to be put in a modal.
 */
function imgsearch_form($form, $form_state, $node) {
  $form = array();

  $form['search_terms'] = array(
    '#type' => 'textfield',
    '#title' => t('Search text'),
    '#description' => t('Enter the search terms'),
  );

  $form['replace_div'] = array(
    '#prefix' => '<div id="imgsearch-replace-div">',
    '#suffix' => '</div>',
    '#weight' => 6,
  );

  $form['node'] = array(
    '#type' => 'value',
    '#value' => $node,
  );

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

  return $form;
}

/**
 * Drupal form submit handler.
 */
function imgsearch_form_submit(&$form, &$form_state) {
  // See apachesolr_saved_searches_get_results() in ozmosys project for code to run solr search.
  $return = nb_alters_search($form_state['values']['search_terms']);

  if (is_array($return['images']) && count($return['images'] > 0)) {
    // Create object to store file and target field info. To be stored in ctools cache.
    $file_info = new stdClass();
    // Calculate the field name.  It is a multivalue field, so we just need the next available option
    // in the $field_images['und'] array.
    $field_images = $form_state['base_node']->field_images['und'];
    $next_value = count($field_images);

    $file_info->fieldname = '#edit-field-images-und-' . $next_value . '-imgsearch-file-url';
    $file_info->fids = array();

    // Theme the results as a table.
    $header = array(t('Image'), t('File Name'), t('Add to field'));
    $rows = array();
    foreach ($return['images'] as $image) {
    // Create image style derivative for each image.
      $imagestyle = array(
        'style_name' => 'thumbnail',
        'path' => $image['filepath'] . $image['filename'],
        'width' => '',
        'height' => '',
        'alt' => '',
        'title' => $image['filename'],
      );
      $styled_image = theme('image_style', $imagestyle);
      $fid = $image['fid'];

      $rows[] = array(
        'image' => $styled_image,
        'name' => $image['filename'],
        'add' => ctools_ajax_text_button("select", "imgsearch/nojs/imgadd/" . $fid . '/' . $form_state['base_node']->nid, t('Select')),
      );

      $file_info->fids[$fid] = $image['filename'];
    }
    //Cache image name in ctools object cache so it can be used later in nb_alters_image_add()
    ctools_include('object-cache');
    ctools_object_cache_set('imgsearch', $form_state['base_node']->nid, $file_info);

    //$output = theme('table', array('header' => $header, 'rows' => $rows, array('class' => array('imgsearch-table'))));

    // Create a render array ($build) which will be themed as a table with a
    // pager.
    $build['imgsearch_table'] = array(
      '#theme' => 'table',
      '#header' => $header,
      '#rows' => $rows,
      '#empty' => t('There were no matching results found'),
    );

    // Attach the pager theme.
    pager_default_initialize($return['total_found'], $return['rows']);
    $build['imgsearch_pager'] = array('#theme' => 'pager');

    $output = drupal_render($build);
  }
  else {
    $output = '<div class="no-results>No images found</div>';
  }

  // Tell the browser to replace add the table with returned images to the form.
  $form_state['ajax_commands'][] = ajax_command_replace('#imgsearch-replace-div', $output);
}

```

My problem is getting the pager to work so that when the pager link is clicked, the search is run again via ajax, and the results are written to the appropriate div (imgsearch-replace-div) on the page. Currently, the pager link is to imgsearch/nojs/$nid?page=x, which is just to the page function that displays the modal, but it's the form submit function that runs the search again and replaces the div with the output. What do I need to do to get the form submission function to be run and the new set of results displayed, all via ajax?

Thanks.

# Answer
I was able to get this working, but not without substantial re-working of my page callback and getting rid of the submit function. Details are in a blog post series I'm working on starting here, but the gist of it is that you can't use a submit function to start the search. This is because the links generated by the pager code always link back to the original page url, so you have to call the actual search from within the page callback, and then pass the page number param to your search function to get the correct results.
> 0 votes

---
Tags: forms, ajax, chaos-tool-suite
---


# Question
Title: Panels default content when creating a new page
When I'm creating a new panel page within the Panels module I want the new page to automatically load up with the content and layout and settings of my default site template.

For example, I want the site name, logo, main menu and a few other things to show on every single page without manually adding it every time I create a new page.

Should I not be creating a new Panel page for each section of my site?

# Answer
> 0 votes
You want to create a new page by *cloning* (AKA copying) the one you've already made with all your content/layout/settings chosen.

Under `admin/structure/pages`, navigate to the `Edit` form for the page you've already created and would like to replicate (See screenshot).

Then, click on the Clone button on the top, right-hand menu of the page's Edit form (See screenshot).

Then just follow the wizard's instructions for cloning the page. Once you've cloned the page, you'll have a brand new page with all the same content, layout, and settings as the previous one.

---
Tags: panels, theming
---


# Question
Title: How can I capture JavaScript value for use on tpl.php
I have a custom module, in a javascript file that is located in the js folder of the module, I captured a value from a previously written function using an if statement. Ex: if($numb==6) show this img else show this img.

I need to access this value/var so I can display a particular image on my tpl.php when it loads.

How can I accomplish this in drupal7?

# Answer
What you can do in this particular case is add the HTML for both the images inside tpl file. On the js file, you can display/hide the images according to your IF condition.

To capture JS value for use in tpl, you can use javascript/ajax to send the information through a url / xmlhttp and then use hook menu to grab the information inside module file, then send the variable to the tpl
> 2 votes

---
Tags: 7, javascript
---


# Question
Title: Drupal 6 - Core Search Module Not Indexing Node Titles
Search is working fine on my site if the search includes text that is in the body of a node, but it appears that node titles are not being indexed.

I'm just using the core search module.

Is this by design in Drupal 6 or is this a bug and how can I fix it?

# Answer
> 0 votes
I was able to fix this issue by changing the **Indexing throttle** setting for `Number of items to index per cron run` from 100 down to 10.

Once reindexing was complete all node titles appear to be indexed and appearing in search.

---
Tags: 6, search
---


# Question
Title: Filter price according to Maximum Price of Product
I am using better exposed filters(https://www.drupal.org/project/better\_exposed\_filters) and have created a price filter and the range I have selected is 0 to 2000.But I want the maximum limit of the price filter to be the maximum price of the product on that page(I have multiple pages with different products).

Is there a way to do it using views?

# Answer
In view, add sort criteria for price filter i.e. Sort descending.
> 1 votes

# Answer
You can try this and add additional conditions based on your page count:-

```
/**
* Implements hook_js_alter().
*/
function hook_js_alter(&$javascript) {

 $query = new EntityFieldQuery();
 $query->entityCondition('entity_type', 'commerce_product')
 ->entityCondition('bundle', 'product') // replace with your bundle
 ->propertyCondition('type', 'product') // replace with your type
 ->fieldOrderBy('commerce_price','amount','DESC');
 $result = $query->execute();

 // Get the commerce product id for the max price
 reset($result['commerce_product']);
 $product_id = key($result['commerce_product']);
 $product =  commerce_product_load($product_id);

 $price = commerce_product_calculate_sell_price($product);
 $price = $price['amount']/100;

$settings = $javascript['settings']['data'];

foreach ($settings as $key => $value) {
  if (isset($settings[$key]['better_exposed_filters']['slider_options']['commerce_price_amount']['max'])) {
    $settings[$key]['better_exposed_filters']['slider_options']['commerce_price_amount']['max'] = $price;
  }
}

$javascript['settings']['data'] = $settings;
}

```
> 1 votes

---
Tags: views
---


# Question
Title: How to set maximum height in image style in Drupal 7?
I want to define an image style in Drupal 7 which changes the width of images to 200px and the max of the height to 150px. That means if a picture is 400x300 the image style should change it to 200x150 but if an image is 250x120 the image style should change only the width of it to 200px and the height shouldn't be changed.

How can I do it ? It seems it is not possible by 'admin/config/media/image-styles'.

# Answer
Your approach will differ depending on whether you want your images to be cropped or scaled to fit the appropriate size, but generally speaking, in most of the image style effects where you can specify a width and height, if you just enter one value, the value for the other will be automatically calculated ("Resize" is an exception, but since that can result in distorted images, you almost always want to use "Scale" or "Scale and crop" instead.) For example, if you add a "Scale" effect, leave the width field blank and set the height to 150px, when processing a 400x600px image, the system will notice that it needs to divide the height by 4 in order to reduce its height to 150px, and apply the same division to the width, resulting in a 100x150px image.

Again, depending on how you want images to be scaled or cropped, applying more than one action in sequence may also get you where you want to be. For example, scale to a certain width, then crop to a certain height. The "Scale and crop" action can do both of these together in one action, but might not do it in exactly the manner you want.
> 1 votes

# Answer
You might want to check the "Image max size crop" module, which sole mission is to add an image style that provides the functionality that you're looking for.
> 1 votes

---
Tags: 7, media
---


# Question
Title: Displaying Organic Group members based on a Views Contextual Filter
The end goal here is to get a list of organic group members based on a contextual filter.

The path for the view is groups/%/members, where the contextual filter is "OG membership: Group ID" and defaulted to custom PHP code. (Because the "Current OG from Context" wouldn't work.)

The custom PHP code is as follows (based off of this solution on d.o):

```
 if(arg(0) == 'groups' && arg(1) != null){
  $node_path = drupal_get_normal_path('groups/'.arg(1));

  $node_id = substr($node_path, 5);

  // Check if node referenced by arg(1) is a group
  if(og_is_group('node', $node_id)){
    return $node_id;
  }
  else {
    return null;
  }
}
else{
  return null;
}

```

There is a relationship to OG membership: OG membership from User there also. It makes no difference if the contextual filter is referencing the relationship or not.

If I "Preview with contextual filters" in the Views UI with a group's NID, the view works. So I know it's just the default value of the contextual filter.

I have something very similar in the "No Results Found" section for troubleshooting purposes, the only differences is it outputs some additional strings to clarifiy where the returns are firing. When I save the view and go look at the page, it returns "No results found" but also returns the correct NID/GID from the PHP. My suspicion is that the PHP code isn't validating with views for some reason.

The view needs to be a page, so I can't use the default *block* view provided by the OG module. ("OG members (user)")

The only thing I am set on is a working solution, so if you have a suggestion on doing it differently, I am open to other ideas.

Contextual filters I have tried that do not work are: -Content ID from URL -OG Group from context -Raw value from URL

Any help or point in the right direction would be greatly appreciated.

Thanks!

# Answer
> 1 votes
Okay so the problem turned out I was returning the wrong variable.

I needed to return $handler-\>argument instead of whatever variable I was using.

So my function I put in my contextual filter was:

```
if(arg(0) == 'groups' && arg(1) != null){
  $node_path = drupal_get_normal_path('groups/'.arg(1));

  $node_id = substr($node_path, 5);

  // Check if node referenced by arg(1) is a group
  if(og_is_group('node', $node_id)){
   // return $node_id;
   $handler->argument = $node_id;
   $node = node_load($node_id);
   $handler->validated_title = $node->title;
   return $handler->argument;
  }
  else {
    return null;
  }
}
else{
  return null;
}

```

(I cleaned up the code a little and adjusted it to strip out the unnecessary stuff.)

---
Tags: views, organic-groups
---


# Question
Title: How to disable the Submit button on a the delete page form?
I made a form\_alter and trying to disable the submit button by greying it out by using the #disabled option on the form api. I know i can just do a unset() on the submit button, but was wondering how to use the #disabled. I tried the following:

**$form\['actions'\]\['submit'\]\['#disabled'\] = TRUE;**

But that doesn't do anything it seems. Here' my krumo output:

# Answer
Yes, you are understanding the behavior of the '#disabled' key correctly. I tried the code you describe and it "just worked."

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

  dsm($form['actions']['submit']);
  $form['actions']['submit']['#disabled'] = TRUE;
  dsm($form['actions']['submit']);
}

```

My guess as to why the alteration is not creating the desired end result is that your function signature is not using the "&" with the $form variable. That character is needed for the $form variable to be "passed by reference" which allows for the changes to the variable to stick outside the function.
> 2 votes

# Answer
By referring Drupal 7 disable submit button your code is correct. Plz refer this or just try Hide submit button module..
> 1 votes

---
Tags: 7, forms
---


# Question
Title: Bibliography module url search as anonymous user
I have a problem with the Bibliography Module module and its filter/search functionality.

Via URL it is possible to search for specific keywords:

```
/biblio?f[search]=Smith%2C%20S.

```

would search the publications for Smith, S.

If I am logged into D7 as an admin, this works perfectly. But if I change to another user or log our completely, this is not working anymore and shows me:

> No items found Modify or remove your filters and try again.

I tried to change some permissions, even gave user all the permissions an admin has (just for testing). And it works just, if I enable the ultimate permission: *Bypass content access control*.

So obviously it is a permission issue. Any ideas, how to solve this issue?

# Answer
It sounds like you've practically have solve the problem; the issue is with content display permissions. The question need to ask yourself is what access control is being restricted. Is it node type viewable permission? Is it *view unpublished content* permission?

If you're looking for way to troubleshoot this see How to debug permissions.
> 0 votes

---
Tags: users
---


# Question
Title: ubercart 2 views - filter by order total weight
I use Ubercart 2 with Ubercart Views. I'd like to filter orders based on total weight.

It's possible to add total weight as a field, however it is not possible to add this field as a filter. I tried Views PHP Filter using `$row->weight` but this filter is not picked up (it filters `$row->title` ok). How can I filter by total weight?

# Answer
> 0 votes
My solution was to add custom php filter and add:

```
$ord_weight = db_result(db_query("SELECT SUM(qty * weight) FROM {uc_order_products} WHERE order_id = '$row->order_id'"));

```

---
Tags: views, 6, ubercart
---


# Question
Title: How do I view the user registration form (as a page/node) while signed in as Admin.
I can see the user registration form fields at Administration/Configuration People/Account Settings/Manage Display/User Account, however I cannot find a way to display this information as it would appear on a Drupal page/node. What am I missing?

Hank

# Answer
The **user/register** path in Drupal only displays a form for *anonymous users*. If you wish to view it as you're changing form elements, open up an anonymous tab (e.g. Igcognito in Chrome, Private Browsing in Safari, etc.) and reload the page as you make updates.
> 0 votes

# Answer
You can see the registration form on:

> admin/people/create
> 0 votes

---
Tags: forms, users
---


# Question
Title: How to dynamically assign submit hooks to webforms when generating blocks
in `mymodule_block_view` I am generating some blocks for my site, depending on configuration data stored in the database. Some of these blocks may have Webform front ends:

```
$block = module_invoke('webform','block_view','client-block-' . $r['webform_nid']);

```

At the point above when I fetch the webform, I would then like to attach a custom submit hook to the webform. The submit hook will need access to the values entered into the webform by the user, and also some variables which are available to the block (so would need to be passed through to the webform somehow).

The submit hook needs to be selected dynamically by the block code, it won't be the same every time.

Any help much appreciated.

**UPDATE - HOW I EVENTUALLY SOLVED THE ISSUE**

As Shawn says in his reply, `webform_block_view` returns a rendered webform, with no access to `$form_state`, so there is no way to pass information into the form. Instead, I figured out how to use `drupal_build_form` from within my `module_block_view` to generate the webform:

```
$node = node_load($webform_nid);
$form_state = array();
$form_state['build_info']['args'] = $node;
$form_state['rebuild'] = FALSE;
$form_state['foo']['bar'] = $bas; // block specific info passed into form
$block['content'] = drupal_build_form($webform_name,$form_state);

```

I then added code into my `module_form_alter` as per his suggestion, to add the custom submit hook to the form. The submit hook then checks the `foo` and `bar` variables passed through from `module_block_view` and behaves accordingly.

**WATCH OUT FOR ...**

One thing worth mentioning for anyone reading this page in future, is **NOT** to use `$form['storage']` for storing custom form data when using webforms, as the webform module rather rudely destroys `$form['storage']`. This took me a long time to discover!

From \_webform\_client\_form\_pages\_ in **webform.module**

```
// Determine what we need to do on the next page.
  if (!empty($form_state['save_draft']) || !$form_state['webform_completed']) {
    // Rebuild the form and display the current (on drafts) or next page.
    $form_state['rebuild'] = TRUE;
  }
  else {
    // Remove the form state storage now that we're done with the pages.
    $form_state['rebuild'] = FALSE;
    unset($form_state['storage']);
  }

```

# Answer
> 0 votes
`webform_block_view()` returns a block object that already has the rendered webform. At that point, you're not going to be able to make any form altercations need for your custom submission handlers.

However, you can add a `hook_form_alter()` invocation to your custom module. Webform generates a standard form id for each form `webform_client_form_NID`.

```
MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'webform_client_form_NID') { //@TODO: substitute NID for your webform NID
    $form['#submit'][] = 'MYMODULE_webform_client_form_NID_submit';
  }
}

```

If you need to pass data from your `hook_block_view` invocation to your `hook_form_alter` invocation, a global variable should help there.

---
Tags: hooks, webforms, forms
---


# Question
Title: How do you include a Dev module in a make file?
I am using Drush make files to automate my site development.

I have followed this tutorial to create a Make File via Drush.

Everything works fine, except when I run the make file, Drush says it can't find the Development versions of modules (for the modules where I have used the Dev version).

According to this tutorial, this is because you have to specify the Git Address and Revision ID of the module. How do you do that?

**Steps I have taken**

For example, lets say I want to include 7.x-1.x-dev release of the Fences module. This dev module was released on 2013-Sep-30.

On the project page, there is an option called View all Releases. However, on this page, none of the releases are dated 2013-Sep-30. The project page also has links to a Git page for the project. However, this doesn't seem to have been updated for a while as the newest update was 15 months ago.

How do I find the Git address for this Dev module or is there another way of including it in my make file?

# Answer
You're almost there - what you need to add to your make file looks like this and you have to specify the git url and commit identifier.

```
projects[path_breadcrumbs][version] = "3.x-dev"
projects[path_breadcrumbs][download][type] = "git"
projects[path_breadcrumbs][download][url] = "http://git.drupal.org/project/path_breadcrumbs.git"
projects[path_breadcrumbs][download][revision] = "c9c570b0b4bde1df0e5a322ab90197d7fc1cf9c6"

```

To find this, go to the project page on drupal.org and select 'view commits', ex

On the next page, select the one you are interested in that reflects the state of the module you want to add to your make file. For this example, I'm going to grab the last commit:

and I'm clicking the 'commit bdcf88a' link which takes me to:

http://drupalcode.org/project/path\_breadcrumbs.git/commit/bdccf8a

Now I know that the the \[download\]\[url\] is:

http://drupalcode.org/project/path\_breadcrumbs.git

and the full hash for the commit I am looking for is:

bdccf8a901b6d2359b6da195d23cadf7dd90c4ec

--

Further updates as requested -- if you're looking for a specific dev branch you may want to switch to the command line to do a --recursive clone to make sure you're getting all the branches. Following this question:

How do I git pull a dev branch?

I'm going to do a recursive pull of the git 7.x-1.x branch

```
git clone --recursive --branch 7.x-1.x http://git.drupal.org/project/fences.git

```

Now I can see what branches are available:

```
git branch -r
  origin/1343724-region
  origin/7.x-1.x
  origin/HEAD -> origin/master
  origin/master

```

Now I can checkout this branch for 7.x-1.x and check the log, which will give me the last commit and the one that was used to generate the development snapshot.

```
git checkout 7.x-1.x
git log

  commit 67206b5220cbebf52e8e6a290ccb977b2420b2ad
  Author: JohnAlbin <virtually.johnalbin@gmail.com>
  Date:   Tue Sep 4 13:44:40 2012 +0800

      Fix code comments on figcaption.

```

The date is different from what you may see on the project home page only because this is an automatic development snapshot created by the Drupal.org git bots but the development snapshot is always created from the branch with the same version number and the '-dev' part is never used in the branch name.
> 17 votes

# Answer
The current version of Drush only requires the branch name and the commit hash of the version of the module, since Drush Make now uses git by default and can find the path to the git repo.

```
projects[myproject][download][branch] = 7.x-1.x
projects[myproject][download][revision] = abcd123

```
> 2 votes

# Answer
schnippy's answer is correct, and should be accepted. The instructions above do apply to all modules. The only confusion remaining is the date 2013-Sep-30, which I believe is an artifact of the Drupal.org upgrade to Drupal 7. In any event, all that date is telling you is that drupal.org packaged a release on that date. The latest commit (2012-Sep-30) represents the very latest code available for that module. Even if some release is packaged and labeled with a later date, it won't have any newer code in it -- there *is* no newer code than the last commit.
> 1 votes

# Answer
IMHO it's much better download D.O. releases instead of GIT branches.

If you have declared the core version (the most usual) this line forces download the 2.x dev branch of fboauth module:

```
projects[fboauth][version] = 2.x-dev

```
> 0 votes

---
Tags: 7, version-control, drush
---


# Question
Title: Drupal Commerce PayPal Express Checkout review and confirm step is skipped
User is not seeing Confirm Order Page (Express Checkout review and confirm) during PayPal Express checkout.

> The EC module defines a new checkout page called Confirm order between the payment redirect and completion pages and a checkout pane called Express Checkout review and confirm that should only be used on this special page.

I am using 7.x-2.3 release of Commerce PayPal module. Testing with PayPal Sandbox accounts.

After logging into PayPal customer sees "continue" button and a message \*"You're almost done. You will confirm your payment on \**'s Test Store."\*. After clicking *"continue"* customer is brought right to the Order Complete page and the payment is registered in the system. Which is not the intended behavior of PayPal EC module.

These are Order history messages that have been recorded during checkout with PayPal express:

*Status has been set to Checkout: Complete (previously: Checkout: Confirm order).
Status has been set to Checkout: Confirm order (previously: Checkout: Payment).
Payment of $62.00 submitted via PayPal Express Checkout.
Order has been paid in full.
Status has been set to Checkout: Payment (previously: Checkout: Review).
Status has been set to Checkout: Review (previously: Checkout: Checkout).
Status has been set to Checkout: Checkout (previously: Shopping cart).
Product sample2 added to the cart.
Order has been created.*

**QUESTION: What could be the reason of why Express checkout review and confirm page is skipped?**

# Answer
> 2 votes
The only code that would trigger a skip of the order confirmation page is in the checkout router hook implementation `commerce_paypal_ec_commerce_checkout_router()`. If you take a look at that, you'll see that it skips the confirmation page if the order either doesn't have a record in its data array that Express Checkout was used or if the customer used EC but did not use the EC flow (as opposed to the Mark flow, which is when the customer chooses PayPal from the payment method checkout pane and is then redirected to PayPal):

```
<?php
  // If the current page is the Express Checkout page but the current order did
  // not use the Express Checkout flow...
  if ($checkout_page['page_id'] == 'paypal_ec' &&
    (empty($order->data['commerce_paypal_ec']['flow']) ||
     $order->data['commerce_paypal_ec']['flow'] != 'ec')) {
    // Update the order status to the next checkout page.
    // ...
  }
?>

```

This means if it's being skipped for you, you should first ensure it's being skipped when the EC button is being used from the cart form (that's the EC flow) as opposed to when the customer redirects from inside the checkout form.

The second place to look will be the order's data array to figure it if / why the order doesn't have a record that it was paid for via EC.

If the module itself is to blame, please open a bug report explaining how to reproduce the issue. Last I used it, it was all working fine.

---
Tags: commerce, payment-gateways
---