# Question
Title: How do I programatically add address to commerce order
I've a subscribe form on my website which i've got working(ish). So far i've got it asking user to input name, address, email, password and the subscription level + starter kit (from a list of promoted commerce items).

Once a user hits 'subscribe' the module creates a blocked user account (it will be activated by Paypal IPN listener if they pay), adds the commerce order (at checkout stage, thanks to Ryan for the script!) and then redirects to paypal for appropriate payment.

Up to this point i'm happy with everything except that the recorded order doesn't contain the address the user entered on the subscribe form and I can't figure out how do do this.

Has anybody managed it before, just point me in the direction of the function and i'll go from there.

Thanks

# Answer
> 2 votes
To record the address on the order, you must create a customer profile of the relevant type (billing information or, if you have Commerce Shipping on the site, shipping information), populate its addressfield value, and reference it from the order you've created. My recommendation would be to use the entity\_metadata\_wrapper() from the Entity API to manipulate those field values.

The addressfield on the customer profile you need to populate is commerce\_customer\_address, and the reference field on the order is commerce\_customer\_billing (or \_shipping respectively).

---
Tags: commerce, entities
---


# Question
Title: Payment Information on hook_commerce_checkout_complete
I am developing module which connects Drupal Commerce with 3rd party invoicing system. For this purpose I need to send payment information (has it been paid? how much? in what way?) after the order is complete. I guess the `hook_commerce_checkout_complete()` hook is the best place to do that but I can't figure out how to obtain this payment information from an `$order` object/entity.

# Answer
> 1 votes
You can see the payment method the customer selected in the $order-\>data array, and to determine if the order was paid in full you'd use commerce\_payment\_order\_balance(). Any additional information would have to come from payment transaction entities whose order\_id match $order-\>order\_id.

---
Tags: commerce
---


title: View for Full Content?

text:
# Question
Title: View for Full Content?
I have a custom content type named "My content type".

I want to use a custom view to render a full content page for that content type. Currently I can only use a Default view that can be found in "Structure \> Content types \> My content type \> manage display" but that is not what I want. I want to get rid of that and be able to use a custom view (from Views module).

How can I achieve that?

# Answer
> 1 votes
I have found 3 solutions. As a matter of fact, my question should have been formed a bit differently, pehaps: **"How to override Drupal 7 node display with a View?"**

Below are three solutions. (I prefer the first listed here. It's very simple and quick and I believe the right way of doing this. Also there is no need to instal any additional modules. Perhaps in some slightly different scenarios, solution 2. or 3. may be more appropriate.)

So here it is:

1. Overriding node displays with custom template and embedding a view in template. See example here: What are the issues with overriding nodes with views?
2. Use Panels module to override the node output See example here: http://jamestombs.co.uk/2011-08-18/use-panels-override-node-output-drupal-7
3. Third option is to use Display Suite module, and then implement Dynamic Field option that renders a custom view. See more here: https://www.video2brain.com/en/lessons/using-display-suite-dynamic-fields

# Answer
> 4 votes
I would recommend you to have a look on the Display Suite module. This module allows you to add different view modes (displays) for your content. These view modes can then be used in several places. Beside that, the display suite module offers a lot of other very handy features to deal with any entity in your system and how they are displayed.

# Answer
> 0 votes
You may just configure the view to override the default Full Content view mode without changing the node template or using additional modules like DS or Panel.

This screenshot shows the configuration. The key is to override the default path and get the argument (nid) using a contextual filter.

# Answer
> 0 votes
A similar use-case scenario (which lead me here) not quite mentioned here is that you can add a new View of any content and simply make the Format (in the view) Show: Content | Full content. Set the path to whatever you like (or dynamically as in the above example) and 'bobs your uncle' as we say in the UK (means you're sorted).

In my use-case scenario I was looking for a way adding different content to a static URL based on Domain context (on a multisite build utilising the excellent Domain Access module).

I.E. the 'static' URL was "domain/where-to-go" and what I wanted to do was have Views add the Full Content (the full node) based in which 'domain' was requesting the page and so domain-x/where-to-go would load full content 'x' and domain-y/where-to-go would load page 'y' etc.

---
Tags: views, nodes
---


# Question
Title: Programmatically created content type module title not working
I created a module with a .info, .module and .install file that can be installed by customers. This module file to create content types from node consists basically atm of:

```
/**
* Implements hook_node_info()
*/
function mycontent_node_info() {
  return array(
    'mycontent' => array(
        'name' => t('My content'),
        'base' => 'mycontent',
        'description' => t('You can define your objects here'),
        'has_title' => TRUE,
        'title_label' => t('Object title')
       )
    );
}

/**
* Implement hook_form()
*/
function mycontent_form($node, $form_state) {
   return node_content_form($node, $form_state);
}

```

The problem is as follows:

I want to use entity translation. This works fine but the title module. It ist automatically installed, so the standard title of nodes can be replaced by clicking 'replace', but the default language is not filled.

E.g. if default language is German, the title is not saved. When I translate in English, the English title is saved. When I debug I can see that the complete (German or English) form is taken, the value of the form state are identical except the content itself and the language values 'de' and 'en'.

If I change en as default language then english title is not saved.

Because i can not see anything in the issue tracker of the title module I hope that I have to add anything to my code.

Thx in advance

maen

# Answer
Ok, I BELIEVE that this is a drupal core issue:

I thought I can create a module with another name as the node bundle I made.

```
/**
* Implements hook_node_info()
*/
function mycontent_node_info() {
  return array(
    'mycontent' => array(
      'name' => t('My content'),
      'base' => 'mycontent',
      'description' => t('You can define your objects here'),
      'has_title' => TRUE,
      'title_label' => t('Object title')
     )
  );
 }

 /**
  * Implement hook_form()
 */
   function mycontent_form($node, $form_state) {
     return node_content_form($node, $form_state);
   }

```

This is correct! But my module and hence my hook\_node\_info function had another name than my bundle.

So admin/strucure/types didn't show the bundle and the module title didn't recognize the bundle property.

So this is solved!
> 0 votes

---
Tags: i18n-l10n
---


# Question
Title: Is there a way to pass an argument to a view without using the url?
UPDATE: Shawn's answer is correct but I'd like to mention for anyone else looking to implement it. The arguments must match the contextual filters you've added, in the same order.

---

Right now I'm embedding views using

```
print views_embed_view('customview', 'customblock');

```

in a block. Is there a way that I can still embed a view in a block and pass in a parameter to it. I'd like to create a filter like this

```
print views_embed_view('customview', 'customblock', 'customcategory');

```

Is this possible?

# Answer
> 2 votes
Yes, your example does exactly what you're wanting. Read the docs on views\_embed\_view...

> "...: Any additional parameters will be passed as arguments."

---
Tags: blocks, views
---


# Question
Title: Object undefined in jquery, plus my links are pointing elsewhere
I asked this question on stackoverflow earlier, not realizing this site existed. Seems that this would be a better place for it.

In a nutshell, I've restored an existing drupal 7 site under the `public_html/migrated_site` folder on my hosted site.

When I browse that URL however I'm getting errors from jquery that the Drupal object doesn't exist, and all my links and images point to `public_html/migrated_site/sites/someothersite`...

..where `someothersite` is the name of the old subdierctory under `public_html` on the prior host.

I changed my `settings.conf` values to point to the migrated MySQL database, and that bit appears to have worked, in that the site is coming up, albeit unstyled and with the above jQuery and links errors.

However I'm not sure what could be going on above? I've tried a few `RewriteBase` settings in .htaccess in both `public_html` and `public_html/migrated_site` (particularly, adding `RewriteBase /~hisusersite/migrated_site`) but nothing seems to have made a difference.

# Answer
> 2 votes
The Drupal JS object not being defined is a symptom of it not loading core JS files. His previous site probably enabled JS aggregation that places the aggregated file in sites/someothersite/files/XXX.js. The same goes for the missing images. Have you copied over sites/someothersite/ from the previous host?

It sounds like sites/someothersite/settings.php was what his original host was using and configured for DB & files. Since you're now viewing the site on **gator1111.hostgator.com** Drupal is using sites/default/settings.php.

This primer on drupal multi-site settings might help to also explain what's going on.

---
Tags: migrations
---


# Question
Title: how to hide the tags and category in the front page
My site is `http://nbmdemo.16mb.com/`

How do I hide **tags:featured**

Also in `http://nbmdemo.16mb.com/?q=node/1`

Same thing with: **Category: Demo Articles**

# Answer
> 0 votes
You can hide it by going to **admin/structure/types/manage/YOUR-CONTENT-TYPE/display** and just drag the field(s) info the **Disabled** section.

# Answer
> 0 votes
That seems like you are showing nodes of content type article, if not substitute the content type you are displaying.

Go to the admin area \> structure \> content type \> \[article or your content type\] \> manage display.

Set the "tags" field to hidden, for both "label" and "format". Depending on the display type you are using, you may need to go up into the top right corner of this page and switch from "Default" to "Teaser" and modify those display settings as well.

helpful screenshot:

---
Tags: nodes, taxonomy-terms
---


# Question
Title: Allow user to edit commerce line item at checkout
I have a line item type with a custom amount field that allows the user to specify the amount they pay for the product in the add to cart form.

I also want to be able to allow the user to update the amount at any stage up until they have paid.

How can I make it so that users can edit this line item on the checkout page?

Ideally I would like to just have the equivalent of the add to cart form with my editable amount field output on the checkout page but I'll settle for any way to edit the line item on the checkout form.

I would like to keep custom code to a minimum but am willing to do whatever it takes if my only option is to go very custom.

If it matters to the solution, orders that contain this line item will only ever contain the one product, with quantity 1 and the variable price.

These orders use Commerce NoCart and Commerce Checkout Multilane to skip the regular cart step.

**\[EDIT\]**

An idea I just had was to create a custom checkout pane with my form on it and a submit function that updates the line other on the order. Does anyone see any reason why that wouldn't work?

Or does anyone know if something similar already exists that I could modify/extend faster than writing something new?

# Answer
Yep it seems my proposed solution should do the trick.

I somehow didn't previously see the Commerce Cart Form Checkout Pane module, which does pretty much exactly what I was asking for.

I also used the Commerce Line Item Cart Form module to add line item fields to the form.

**\[EDIT\]**
Turns out that those two modules I mentioned don't seem to play nice together so I'm just going to create a custom checkout pane with a custom form that updates the line item in it's submit function.
> 2 votes

---
Tags: 7, commerce
---


title: Question about users vs cck

text:
# Question
Title: Question about users vs cck
I need to add a field to represent a person's role on a board. I have a CCK for individuals that includes a field for their position. I now need to make some changes so that I can keep track of the current position as well as other positions they may have had in the organization.

Originally, I did not set this up as a "User" entity but as a content type. Now I"m wondering if this is the best way to structure my desired functionality?

Any Advice?

# Answer
Do these people need to login to the website? Do they have to change those profile settings themselves? do you plan that those entities will interact on that page? If any of these is yes, than you probably want users.

In all other cases this is probably a no and you are good to go with content types/ custom entities.

for keeping a record of past positions, you might want to try out field collections, you could create a field collection with start, end, position for instance and allow n entries of it.
> 2 votes

---
Tags: 7, users, entities
---


# Question
Title: What happens after module upgrade if you modify the default views
I want to modify a view supplied by a module. What happens to the view when I upgrade the module? Does it overwrite my changes? If it doesn't and the views in the upgraded version of the module has changed, how do I get the new version?

# Answer
> 3 votes
It should not necessarily change your view, views shipped with modules are usually kept in code, if you change that view, you override it and have it in the database, as long as this overridden view is in your database and a module update does not drop these changes on purpose you should be good to go.

But, always do a backup and test on a local/ different environment than live.

If it does indeed change stuff, you will have to clone the current view and maybe even mimic custom views hooks that are added by that module for that view.

btw. it's worth reading the commit messages since the latest release and or changelogs, if you can read code it's worth looking into the module.install file, and looking at the module\_update\_n hooks, there you can see if anything major might get dropped as well.

---
Tags: 7, views
---


# Question
Title: scheduled site backup at specific time / hour
How to schedule a backup of Drupal site (especially database) at specific hour on a shared host? I am using Backup Migrate module, but it doesn't support hours, only frequency. It currently makes daily backups around 8 pm.

I checked this shell script, which could be added to cron I think, but it doesn't send mail after backup and doesn't allow to specify "only structure" for cache tables.

# Answer
> 1 votes
Try Elysia Cron, in addition to Backup and Migrate, you can set the time of day to run as well as many other things.

Don't forget to read the documentation.

It is also worth noting that in the default configuration of Drupal 7 cron is triggered by users hitting your site. If the site is not used exactly at the time indicated in Elysia Cron it will be run as soon as someone loads something on your site. Therefore, it is impossible to get this to execute exactly when you want, but it should be close.

# Answer
> 0 votes
You could try a simple shell script that uses mysqldump to dump your Drupal site's database, tar and gzip, and then use mailx or mutt to send an e-mail with the gzipped tarball attached to the e-mail. Then set a cron job that runs that script at the specific time you wish.

---
Tags: 7, backups
---


title: Add a link to the Module list page

text:
# Question
Title: Add a link to the Module list page
In a Module list page (`admin/modules`) , We could see help, permission or configure links in Operations column. and also Module Filter customize it as a dropdown for each module listed.

Now I need to create a **new link** in that operations for every module installed. How should I do it?

I think I should go with `hook_page_alter()` but don't know how to start with since the $page array of `admin/modules` page is too long.

# Answer
I think not just form\_alter makes this happen, "**theme**" too plays a game here. When you look into coder review Module file, you could find that.

Code Review which is a submodule of Coder Module also adds a link to the `system_modules` form.

```
function coder_review_form_system_modules_alter(&$form, &$form_state, $form_id) {
  if (!user_access('view code review') || isset($form['confirm'])) {
    return;
  }

  $path = drupal_get_path('module', 'coder_review');
  $form['#attached']['css'][] = "$path/coder_review.css";
  foreach ($form['modules'] as $package_name => &$package) {
    if ($package_name[0] != '#') {
      foreach ($package as $module_name => &$module) {
        if ($module_name[0] != '#') {
          $module['links']['coder_review'] = array(
            '#type' => 'link',
            '#title' => t('Code review'),
            '#href' => "admin/config/development/coder/review/$module_name",
            '#options' => array('attributes' => array('class' => array('module-link', 'module-link-coder-review'), 'title' => t('Coder review'))),
          );
          $package['#theme'] = 'coder_review_modules_fieldset';
        }
      }
    }
  }
}

```

There is a particular line in this code that needs to be noted :

```
$package['#theme'] = 'coder_review_modules_fieldset';

```

This might be the reason your not able to get the link.

Function `theme_coder_review_modules_fieldset()` is implemented in *coder\_review.admin.inc* file. In its comment block you could also find something like this

```
/**
 * Returns HTML for the modules form.
 *
 * This was copied from theme_system_modules_fieldset() and modified to handle
 * additional links.
 *
 * @param array $variables
 *   An associative array containing the key:
 *   - form: A render element representing the form.
 *
 * @ingroup themeable
 *
 * @todo Create an issue for this and get this function into D8.
 */

```
> 0 votes

# Answer
The system\_modules() form is the one that provides that module list.

You can form alter that in a custom module like so:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_NAME_form_system_modules_alter(&$form, &$form_state, $form_id) {
  // Loop through the array of module packages.
  foreach (element_children($form['modules']) as $package) {
    // Loop through the array of module rows for each package.
    foreach (element_children($form['modules'][$package]) as $module_filename) {
      // Add an extra operation link for each module row.
      $form['modules'][$package][$module_filename]['links']['new_operation_link'] = array(
        '#type' => 'link',
        '#title' => t('Link text'),
        '#href' => 'link/url',
        '#options' => array(
          'attributes' => array(
            'class' => array('module-link', 'module-link-configure'),
            'title' => t('Link hover text'),
          ),
        ),
      );
    }
  }
}

```

Note that you need to change MODULE\_NAME to the name of your module and you have the change the link key, text, url, etc. to meet your requirements.

**\[EDIT\]**
I have now tested it and it works. Here is a working example with the placeholder values changed to make a link to google.

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_NAME_form_system_modules_alter(&$form, &$form_state, $form_id) {
  // Loop through the array of module packages.
  foreach (element_children($form['modules']) as $package) {
    // Loop through the array of module rows for each package.
    foreach (element_children($form['modules'][$package]) as $module_filename) {
      // Add an extra operation link for each module row.
      $form['modules'][$package][$module_filename]['links']['google'] = array(
        '#type' => 'link',
        '#title' => t('Google'),
        '#href' => 'http://google.com',
        '#options' => array(
          'attributes' => array(
            'class' => array('module-link', 'module-link-google'),
            'title' => t('Go to google'),
          ),
        ),
      );
    }
  }
}

```

You can also use relative internal links instead of the external google link above.
> 2 votes

---
Tags: 7, users, theming
---


# Question
Title: Login error: call to undefined function entity_load in User module
I’m new to Drupal and I have a problem where no users can login (HTTP 500 and WSOD on POST of valid credentials, Drupal 7). The error message is:

“E\_ERROR Error in file »user.module« at line 291: Call to undefined function entity\_load()”

Any ideas on how to approach troubleshooting this?

# Answer
Your error's stating that it can't find a function that should be in drupal core. Check you includes folder. There should be a file in there called common.inc, make sure the function entity\_load is defined in there.
> 0 votes

---
Tags: users
---


# Question
Title: nodes in views and views in search results
I'm building a website, where I don't want to display nodes directly. All nodes are presented using Views. The idea is that i've got 10 basic pages without content. On each of these page I've got one or more Views as blocks. In these Views i show my nodes.

THE PROBLEM: When I use drupal search I get results with direct links to nodes. Instead I would like get links to pages where the View is located, containing that node. I can easily achieve that by changing alias to page with that View. For example: I've changed alias content/function-one to /functions (page with View which presents functions) and it works, but there are another problems there.

* First, I can still access nodes directly by url /node/%nid.
* Second, I can have links only to pages with Views, but I still want to navigate to the nodes. I thought I can achieve it using anchors. I modified my alias to /functions#functionOne. But my href looks like /functions%23;functionOne and the anchor doesn't work.

So my goal is to disable access to nodes by /node/%nid and make my search results to give me link to the page that contains View with that node and navigate user to that node.

Any ideas how I can achieve that? Alternative approaches?

Thanks in advance

# Answer
Take a look at Rabbit Hole ( https://www.drupal.org/project/rabbit\_hole ) , it has several options as to what has to happen when a Node is viewed ( or trying to get viewed ) directly.
> 1 votes

# Answer
I'm thinking about setting nodes to display other nodes in a view or multiple views as EVA. Simple nodes (content nodes) should point to nodes considered categories (blanc nodes, taking just the view) (list of nodes in those views) using entity reference. Attach EVA blocks to your category nodes as field and customize your search. Could work with Display Suite very nice, using DS search option.
> 0 votes

---
Tags: views, search, path-aliases
---


# Question
Title: How to change date format in Views Calendar Pager?
I have multiple displays rendered in a Calendar View (Mo/Day/Upcoming/etc.) and everything's working as it should... except I changed a setting somewhere and applied it to all pages instead of current display and now the heading for the month display uses long format of the first date in the range of context (i.e. Tuesday, October 1 2014, Thursday, November 1, 2014, etc.)

I have "fixed" the issue by hooking theme\_date\_nav\_title() in the theme template.php and setting $params\['format'\] directly, but this is hacky... ***Where is this setting in Views?!***

# Answer
This is an issue in the calendar module that has been fixed in the 3.x-dev version. There is still no setting to set the header the way you want but at least it doesn't default to the 1st of each month without hacking the module.
> 0 votes

---
Tags: views, datetime
---


# Question
Title: Drupal 7 Orphaned fields, how should they be deleted?
Currently I uninstalled ubercart and there are still fields that exists in my database. I have the following fields that I want to delete:

* uc\_catalog\_image
* uc\_product\_image

http://prntscr.com/1hj1rt

How should one go about deleting these tables from the database? What would it affect if I just dropped those tables complete? And where else would I have to update if I did that manually?

# Answer
> 1 votes
I recommend using drush for this type of thing and let the field crud api do the heavy lifting.
`drush eval field_delete_field("YOUR_FIELD_GOES_HERE")`

---
Tags: 7, entities, ubercart, database
---


title: Deny location based access to nodes

text:
# Question
Title: Deny location based access to nodes
I need to restrict access to a node based on the distance of the current user to a location attached to the node (with Location module). The distance to decide, if access is allowed is node based and stored in a field of the node. Currently I achive this feature with hook\_node\_access(). I get the current location of the user through the Smart IP module and are able to calculate the distance by passing the coordinates of the user and the node to location\_distance\_between(), which is provided by the Location module.

Because hook\_node\_access() isn't considered by Views I think about accomplishing this feature with hook\_node\_access\_records() and hook\_node\_grants(). Since the distance is dynamically, I have no idea how to achive this. In my understanding hook\_node\_grants() is called before the database query, so I have no chance to get the distance right?

Any ideas?

Thanks, Daniel

# Answer
> 0 votes
Ok I got it with a little work around.

I use hook\_views\_query\_alter() to get all the distances of the relevant nodes. So I build an own query like this:

```
function mymodule_views_query_alter(&$view, &$query) {
  if($view->name === 'my_view' && $view->current_display === 'my_display') {
    // build the query to get the distances
    $location_query = db_select($query->table_queue['node']['table'], $query->table_queue['node']['alias']);
    $location_query->leftJoin('location_instance', 'li', $query->table_queue['node']['alias'] . '.vid = li.vid');
    $location_query->leftJoin('location', 'l', 'li.lid = l.lid');
    $location_query->leftJoin('field_data_field_distance', 'd', $query->table_queue['node']['alias'] . '.nid = d.entity_id');
    $location_query->fields('l', array('latitude', 'longitude'))
    ->fields('d', array('field_distance_value'))
    ->fields($query->table_queue['node']['alias'], array('nid'));

    // consider all filters which were set in the views ui
    foreach ($query->where[1]['conditions'] as $condition) {
      $location_query->condition($condition['field'], $condition['value'], $condition['operator']);

    }

    // execute the query
    $result = $location_query->execute()->fetchAll();
    // go through all results to check the distance
    foreach($result as $node) {
      // do the calculation of the distance
      // ...
      // check if distance is close enough
      if($distance <= $node->field_distance_value) {
        $nids[] = $node->nid;
      }
    }

    // remove all conditions from the views query, because we already used them
    unset($query->where[1]['conditions']);

    // let views just load all the relevant NIDs
    $query->where[1]['conditions'][0] = array(
      'field' => $query->table_queue['node']['alias'] . '.nid',
      'value' => $nids,
      'operator' => 'in',
    );
  }
}

```

Well, in this way I anticipate the Views query and change it, so that Views just needs to load the NIDs which were required.

# Answer
> 0 votes
**Option 1**

I use the Geofield module, which provides a similar function to the Location module. It provides the concept of a proximity filter. This allows you to implement views such as "show all nodes within 50km of specified point". I don't know whether the Location module has a similar function, or whether you might be willing to change modules. The Smart IP module claims some Views integration but D6 only, so you might need a bit of code to integrate with views.

This approach would not use access control at all - so that if the user specifically navigated by URL to a far away node, they would still see it.

**Option 2**

If you definitely want access control, then I think you will have to give up exact distances. You could divide your target area into regions, maybe around 50-500 of them - most simply using a simple grid. In your hook\_node\_access\_records, you decide which regions are close enough to the node (calculate distance to the region centre). Finally in hook\_node\_grants, you need code to take the output of the Smart IP module and calculate which region it is in, and set the appropriate grant.

If you need some more help with the details of either approach, feel free to edit your question to say which approach you prefer, what you have working and where you are stuck.

---
Tags: 7, views, location, users
---


title: Menu not showing on some content types

text:
# Question
Title: Menu not showing on some content types
I have an inherited website that uses panels, and the menu is not coming out on certain pages . how can I find out and fix it so that the menu comes out on all of the pages.

# Answer
> 1 votes
A couple places to start looking:

1. **Block configuration**

Is the menu placed as a block with specific logic that prevents it from appearing on certain pages. Go to 'Structure \>\> Blocks' and see if there is a block placed for your menu. Then under 'Visibility Settings'.
2. **Context**

Is the menu placed via Context? 'Structure \>\> Context', look for something that has to do with the menu.
3. **Page Manager**

Is the menu part of the page template or is it specifically placed in the content section of each page? Check out a page that shows the menu and a page that doesn't in the page manager, go to 'content' of the applicable variant and see if you can spot any differences.

With out some more information it is hard to determine what method is being used to place the menu.

# Answer
> 0 votes
Yes I found the answer, it was in a custom module that was looking for a context id that it didnt find. thanks

---
Tags: panels
---


# Question
Title: Getting form Array from a webform created with Webform module?
Is it possible to easily get the form Array from a webform created with Webform module?

I want to be able to call a copy of the form elsewhere

thanks

# Answer
> 1 votes
First off you'll need to know the form\_id. You can get this a million ways but the 2 I use frequently are using the devel module that has the dpm() function to display any variable you want to the screen. So in a hook\_form\_alter you can put dpm($form\_id) and get it that way. Another way is to just view the source and find the opening form tag. The id is in there as well.

Once you have the form id you can use drupal\_get\_form($form\_id) to get the form array.

---
Tags: forms
---


title: Quicktab Scrolling

text:
# Question
Title: Quicktab Scrolling
Is there anyway to set a quicktab to scroll the content within the tab when using a callback?

For example: I have a list of events that I would like to have in a set height tab and then have the opportunity to scroll through like a Twitter / Facebook widget.

# Answer
> 1 votes
This is a css thing. You need to right click on your page and select **Inspect Element** then find the name of the div class that has the content within the tab. Then just give it a fixed height and an overflow scroll. For example:

```
.mydiv { height: 100px; overflow-y: scroll; }

```

JS FIDDLE EXAMPLE

---
Tags: blocks
---


# Question
Title: How to find an article title for specific post
So, I am new to drupal, and I am using a small pdo library to directly fetch from database list of articles, to display them on a page that is not running drupal. But, the articles are posted using drupal cms.

My problem is that, also I am able to fetch the article content, node id ... but I can't seem to find the title of article itself.

I looked in my table, and these are all the data I have.

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

```

Just as example, I am doing

```
$db = new DB(...);
$stmt = $db->query("SELECT *, entity_id as id, body_value as content from field_data_body where entity_id < 10  LIMIT 8");
$result = $stmt->fetchAll();

foreach($result as $row){
  echo $row['title']; //error.
}

```

# Answer
> 1 votes
As with everything there are a few ways to do this. Here are a couple, if you know the node id.

Do a query on the node table:
`select title from node where nid = KNOWN_NODE_ID`
Use a Drupal function:
`$node = node_load(KNOWN_NODE_ID);`
`$nodeTitle = $node->title;`

---
Tags: database, nodes
---


# Question
Title: Populate $form_state['values'] with defaults from drupal_get_form()
I'm looking to resave a form's defaults values. In core the test module uses drupalPost() to test the form so I'm thinking this will be custom code.

# Answer
This is the function I've come up with.

```
/**
 * Given a form get the default values from it.
 *
 * @param array $defaults
 *   An empty array used to populate the default values.
 * @param array $form
 *   The form returned from drupal_get_form().
 * @param string $parent_key
 *   The key name of the parent.
 */
function get_defaults_from_form(array &$defaults, array $form, $parent_key = '') {
  foreach (element_children($form) as $key) {
    $values = $form[$key];
    if (isset($values['#value'])) {
      // Grab defaults at this level.
      if (!isset($defaults[$key])) {
        $defaults[$key] = $values['#value'];
      }
      else {
        $defaults[$parent_key . '-' . $key] = $values['#value'];
      }
    }
    elseif (isset($values['#default_value'])) {
      // Grab defaults at this level.
      if (!isset($defaults[$key])) {
        $defaults[$key] = $values['#default_value'];
      }
      else {
        $defaults[$parent_key . '-' . $key] = $values['#default_value'];
      }
    }
    elseif (is_array($values)) {
      // Go deeper if needed.
      get_defaults_from_form($defaults, $values, $key);
    }
  }
}

```

Use it like this:

```
$theme_name = 'seven';
// Load the required file for the form functionality.
$router_item = menu_get_item('admin/appearance/settings/' . $theme_name);
if ($router_item ['include_file']) {
  require_once DRUPAL_ROOT . '/' . $router_item ['include_file'];
}
// Get the form for this theme.
$form = drupal_get_form('system_theme_settings', $theme_name);
// Get the defaults.
defaults = array();
get_defaults_from_form($defaults, $form);
print_r($defaults);

```
> 2 votes

---
Tags: forms
---


# Question
Title: How to print meta property using custom meta tag module
I have implemented the custom meta tag module found here: http://www.phase2technology.com/blog/creating-custom-meta-tags-with-the-metatag-module/

The following code creates my new meta tag, the problem is that it creates a

```
<meta name="my_custom_metatag">

```

tag.

How can I make it print out a

```
<meta property="my_custom_metatag">

```

tag instead?

```
<?php
//
// Implements hook_metatag_info().
//
function my_metatags_metatag_info() {
  $info['groups']['my_metatags'] = array(
    'label' => t('My Custom Metatags'),
  );

  $info['tags']['my_custom_metatag'] = array(
    'label' => t('My Custom Meta Tag'),
    'description' => t('This is a custom meta tag'),
    'class' => 'DrupalTextMetaTag',
    'group' => 'my_metatags',
  );

  return $info;
}

```

Thanks!

# Answer
Telling your custom meta tag to use the property theme formatter should do the trick.

```
$info['tags']['my_custom_metatag'] = array(
  'label' => t('My Custom Meta Tag'),
  'description' => t('This is a custom meta tag'),
  'class' => 'DrupalTextMetaTag',
  'group' => 'my_metatags',
  'element' => array(
    '#theme' => 'metatag_property',
  ),
);

```
> 0 votes

---
Tags: meta-tags
---


# Question
Title: How to let admin upload background image for view page and webform page?
I would like admin to upload background image for each and every different pages in my drupal 7 site.

For normal content type like basic page, BackgroundField module works perfectly where admin can upload images in the file field.

But in webform pages and pages created by view, BackgroundField module can't be used.

Is there any way admin can upload their background image for both webform pages and view pages? As currently I'm using css to set the background images for these pages.

# Answer
> 0 votes
This module can do it for you Background Images.

---
Tags: 7, media
---


title: Custom module for form

text:
# Question
Title: Custom module for form
I have created form by implementing custom module. Can anybody please guide about writing submit function for my form.

```
function custom_form_module_form($form,&$form_state) {
  $form['name'] = array(
   '#title' => 'NAME',
   '#type' => 'textfield',
  );
  $form['company'] = array(
    '#title' => 'COMPANY',
    '#type' => 'textfield',
  );
  $form['phone'] = array(
    '#title' => 'PHONE',
    '#type' => 'textfield',
  );
  $form['email'] = array(
    '#title' => 'EMAIL',
    '#type' => 'textfield',
  );
  $form['message'] = array(
    '#title' => 'MESSAGE',
    '#type' => 'textarea',
  );
  $form['submit_button']=array(
    '#type'=>'submit',
    '#value'=>t('SEND'),
  );
  return $form;
}

```

**UPDATED**

```
 function custom_form_module_form_validate($form, &$form_state)
{
 if((!isset($_GET[($form_state['values']['name'])]))||
 (!isset($_GET[($form_state['values']['company'])]))||
 (!isset($_GET[($form_state['values']['phone'])]))||
 (!isset($_GET[($form_state['values']['email'])]))||
 (!isset($_GET[($form_state['values']['message'])])))
 {
  form_set_error(t('Please fill the entire form'));
 }
 $valid_email = $form_state['values']['email'];
 if (!valid_email_address($valid_email))
 {
  form_set_error('email', 'Sorry. Your email address,' . $valid_email . ', is not valid. Please submit a valid E-mail address.');
 }
 if(!($form_state['values']['company'] > 1))
 {
  form_set_error('company', t('Company does not appear to be valid.'));
 }
 if (!($form_state['values']['message'] > 2 ))
 {
  form_set_error('message', t('message does not appear to be valid.'));
 }
}

```

and below is my submit function. Is this right? because I am not receiving email as I specified my own email address.

```
function custom_form_module_form_mail($key, &$message, $params)
{
 $headers = array(
 'MIME-Version' => '1.0',
 'Content-Type' => 'text/html; charset=UTF-8;',
 'Content-Transfer-Encoding' => '8Bit',
 'X-Mailer' => 'Drupal'
  );
  foreach ($headers as $key => $value)
  {
   $message['headers'][$key] = $value;
  }
  $message['subject'] = $params['subject'];
  $message['body'] = $params['body'];
}

 function custom_form_module_form_submit($form, &$form_state)
{
  $valid_email = $form_state['values']['email'];
  $body[] = 'Email: '.$valid_email.'<br />URL: '.request_uri();
  $to = 'me@example.com';
  $params = array(
  'body' => $body,
  'subject' => 'Welcome!',
  );
  if (drupal_mail('custom_form_module_form', 'some_mail_key', $to, language_default(), $params, TRUE))
  {
    drupal_set_message('Thanks, we will be in contact with more information soon.');
  }
  else
  {
    drupal_set_message('There was an error subscribing you. Please try again later');
  }
}

```

# Answer
You can add `'#submit' => array('SOME_FUNCTION')` to your submit button and write your function normally.
> 2 votes

# Answer
There's some hook functions you can use. my\_module\_my\_form\_validate($form, &$form\_state) to validate the form, and my\_module\_my\_form\_submit($form, &$form\_state) to submit.

Example
> 2 votes

# Answer
I see there are couple of issues with your form validate function. First of we don' t need to write the $\_GET to get the form\_state values and also checking the string length of form values is not correct. I have corrected your validate function as.

```
 function custom_form_module_form_validate($form, &$form_state){
  if((!isset($form_state['values']['name']))||
 (!isset($form_state['values']['company']))||
 (!isset($form_state['values']['phone']))||
 (!isset($form_state['values']['email']))||
 (!isset($form_state['values']['message'])))
 {
   form_set_error(t('Please fill the entire form'));
  }
  $valid_email = $form_state['values']['email'];

  if (!valid_email_address($valid_email))
  {
    form_set_error('email', 'Sorry. Your email address,' . $valid_email . ', is not valid. Please submit a valid E-mail address.');
  }

  if(strlen($form_state['values']['company']) < 1)
  {
    form_set_error('company', t('Company does not appear to be valid.'));
  }
  if (strlen($form_state['values']['message']) < 2)
  {
    form_set_error('message', t('message does not appear to be valid.'));
  }
 }

```

Remember valid\_email\_address function should return true when the email is valid. The submit function is fine. If you have SMTP and SMTP port defined in your mail server then you will receive an email after submitting the function. If you are trying through the localhost you need to assign the SMTP server and SMTP port.

Hope this will help you.
> 1 votes

---
Tags: forms
---


# Question
Title: What is the order of preprocess functions?
I have started learning Drupal for few months. Now I'm doing some theming.

I would like to know the execution order of preprocess functions.

# Answer
The order in which the preprocess functions are called in Drupal 7 is

1. template\_preprocess
2. template\_preprocess\_HOOK
3. MODULE\_preprocess
4. MODULE\_preprocess\_HOOK
5. ENGINE\_engine\_preprocess
6. ENGINE\_engine\_preprocess\_HOOK
7. THEME\_preprocess
8. THEME\_preprocess\_HOOK
9. template\_process
10. template\_process\_HOOK
11. MODULE\_process
12. MODULE\_process\_HOOK
13. ENGINE\_engine\_process
14. ENGINE\_engine\_process\_HOOK
15. THEME\_process
16. THEME\_process\_HOOK

Source : https://api.drupal.org/api/drupal/includes!theme.inc/function/theme/7
> 10 votes

---
Tags: theming
---


title: Pathauto not working

text:
# Question
Title: Pathauto not working
I had installed pathauto module and it was generating desired url alias. But now its not working. All the newly created node shows node/node-\>nid. This issue stops working of my drupal\_get\_path\_alias function i added in views template. Can anyone help me out.

# Answer
> 0 votes
I fixed the issue by commenting $form\['additional\_settings'\]\['#access'\] = false; line in my template.php. Still i don't know why that issue happens for a single content type.

# Answer
> 0 votes
There might be some problem with redirects. To overcome this problem, follow below steps:

1. Go to URL: admin/config/search/path/delete\_bulk
2. Select option to delete all aliases.
3. Go to URL : admin/config/search/path
4. See if there are no aliases left, if any left delete them too.
5. If you have redirect module installed, go to URL: admin/config/search/redirect and delete all redirects if any.
6. Recreated all URL aliases, go to URL: admin/config/search/path/update\_bulk and select desired URL aliases to be created.

See if problem is fixed. If you still have issues comment below.

---
Tags: path-aliases
---


# Question
Title: How to customise order cart customer information pane
During checkout, I can add fields to billing or delivery information, but how can I add fields to customer information, or create another customized pane for them?

Example:

Student Information:

Name: Skill interest: Phone: Email: etc.....

# Answer
> 0 votes
You can achieve this using Ubercart Webform Integration module.

This module integrates two other modules: webform and ubercart. It allows you sell products directly from your webforms. It is particularly suited to be used as part of a registration system.

Using this module you can create additional field in check page.

---
Tags: 7, ubercart
---


title: Private files missing filename

text:
# Question
Title: Private files missing filename
I recently upgraded Drupal from version 7.12 to 7.23. After the upgrade, I noticed that when downloading private files, I no longer get the correct filename when I select "Save As" in the browser.

These are the steps I follow:

* I upload a file ("testfile.pdf") in a file field for a node
* I view the node, right click the file and choose "Save As"
* The filename in the download dialog (which should have been "testfile.pdf") now depends on the browser

+ Chrome: download.pdf
    + FF: \[random string\].pdf
    + IE: \[domain name\].pdf

I am using private files to be able to restrict access to files. In the release notes for Drupal 7.22, I read that a "Content-Disposition" header was removed from private file downloads.

Could this be the reason that private files no longer retain the filename when downloading?

# Answer
> 1 votes
If server does not provide `content-disposition`, especially `filename` part of it, browser is free to choose suggested name. FF defaults to what appears to some kind of UUID, IE to domain, Chrome bases it's guess on the script being called, as far as I can tell. On the other hand adding content disposition can prevent inline viewing of PDF files, and confuse browsers in a few more ways.

You can use `hook_file_download` to conditionally add header with a file name where it needs to be added:

> If the user has permission, return an array with the appropriate headers.

# Answer
> 1 votes
This is how you can use hook\_file\_download to put the Content-Disposition header back in:

```
function mymodule_file_download($uri) {
  return array(
    'Content-Disposition' => 'inline; filename="' . drupal_basename($uri) . '"',
  );
}

```

If any implementation of hook\_file\_download returns -1, access is denied anyway, so the above does not change the current access permissions for the file.

---
Tags: 7, files
---


title: How to theme output from module?

text:
# Question
Title: How to theme output from module?
I have a simple module that is extracting names from database table. I can display that names in hook\_block\_view like this:

```
function example_block_view($delta = '') {

  // $result - an array containing names
  // $names - a string containing names from $result array

  $block = array();

  switch ($delta) {
    case 'xxxxxx':

      $block['title']   = t('Example header');
      $block['content'] = $names;
      break;

  }

  return $block;
}

```

This will output string with names. But I want to use theme() function for outputting names. So I am continuing by this documentation page: https://www.drupal.org/node/722174

Therefore I edited my code to:

```
  $block['content'] = array(
    '#theme' => 'example',
    '#header' => 'Example header',
    '#rows' => $result,
  );

```

But I can't manage out by documentation what should I do next. What is the simplest example of displaying names by custom theme function in my case? Should I do something in template.php of my theme folder, or should I make an hook\_theme() in my module? How could I theme the list of names stored in `$result` array?

# Answer
I was experimenting a little bit with examples from @Shawn Conn and managed the minimum that needs to be done is to call theme() function in hook\_block\_view() and pass variables or arrays into it that will be used in example.tpl.php file:

```
$block['content'] = theme('example', array('items' => $result));

```

Then there must be theme\_hook in module registered. There is no need for any additional parameters:

```
function hook_theme() {

    return array('example' => array());
}

```

And finally create example.tpl.php in current theme folder:

```
<div>

<?php foreach($items as $item) { ?>

        <div>
            <?php print $item['name']; ?>
        </div>

<?php } ?>

</div>

```
> 1 votes

# Answer
You could use hook\_theme to register your theme function, but it sounds like you're wanting output an item list which can be done with theme\_item\_list:

```
  $names = array('one','two','three');
  $block['content'] = theme('item_list', array(
    'items' => $names,
    'title' => t('My Names'),
  ));

```

This will fill in your block's content with this:

```
<div class="item-list">
  <h3>My Names</h3>
  <ul><li class="first">one</li><li>two</li><li class="last">three</li></ul>
</div>

```
> 1 votes

# Answer
Have a look at Examples for Developers and the theming\_example module that is included in the package.

Register your module's theme implementations.

```
/**
 * Implements hook_theme().
 *
 * Defines the theming capabilities provided by this module.
 */
function theming_example_theme() {
  return array(
    'theming_example_list' => array(
      // We use 'variables' when the item to be passed is an array whose
      // structure must be described here.
      'variables' => array(
        'title' => NULL,
        'items' => NULL,
      ),
    ),
  );
}

```

The theme function.

```
/**
 * Theming a simple list.
 *
 * This is just a simple wrapper around theme('item_list') but it's worth
 * showing how a custom theme function can be implemented.
 *
 * @see theme_item_list()
 */
function theme_theming_example_list($variables) {
  $title = $variables['title'];
  $items = $variables['items'];

  // Add the title to the list theme and
  // state the list type. This defaults to 'ul'.
  // Add a css class so that you can modify the list styling.
  // We'll just call theme('item_list') to render.
  $variables = array(
    'items' => $items,
    'title' => $title,
    'type' => 'ol',
    'attributes' => array('class' => 'theming-example-list'),
  );
  $output = theme('item_list', $variables);
  return $output;
}

```

An example where the theme function is used.

```
/**
 * The list page callback.
 *
 * An example page where the output is supplied as an array which is themed
 * into a list and styled with css.
 *
 * In this case we'll use the core-provided theme_item_list as a #theme_wrapper.
 * Any theme need only override theme_item_list to change the behavior.
 */
function theming_example_list_page() {
  $items = array(
    t('First item'),
    t('Second item'),
    t('Third item'),
    t('Fourth item'),
  );

  // First we'll create a render array that simply uses theme_item_list.
  $title = t("A list returned to be rendered using theme('item_list')");
  $build['render_version'] = array(
    // We use #theme here instead of #theme_wrappers because theme_item_list()
    // is the classic type of theme function that does not just assume a
    // render array, but instead has its own properties (#type, #title, #items).
    '#theme' => 'item_list',
    // '#type' => 'ul',  // The default type is 'ul'
    // We can easily make sure that a css or js file is present using #attached.
    '#attached' => array('css' => array(drupal_get_path('module', 'theming_example') . '/theming_example.css')),
    '#title' => $title,
    '#items' => $items,
    '#attributes' => array('class' => array('render-version-list')),
  );

  // Now we'll create a render array which uses our own list formatter,
  // theme('theming_example_list').
  $title = t("The same list rendered by theme('theming_example_list')");
  $build['our_theme_function'] = array(
    '#theme' => 'theming_example_list',
    '#attached' => array('css' => array(drupal_get_path('module', 'theming_example') . '/theming_example.css')),
    '#title' => $title,
    '#items' => $items,
  );
  return $build;
}

```
> 1 votes

---
Tags: theming
---


# Question
Title: How to export data from drupal to Excel?
I've inherited a Drupal site. I need to extract the main page data out of the site to be able to import it into a different system, but I've never used Drupal and the site is live so I need to tread carefully in order to extract the data without affecting the site.

Currently the website has lots of content pages for manufacturers. Each manufacturer has a name, description, some images and other (mainly text) data. Say, for example, there are 2000 of these manufacturers. What I'd really like to be able to do is export an Excel file (or XML file, whatever) so each field has a different column in the spreadsheet, and each drupal page (i.e. each manufacturer) is a different row in the export spreadsheet. Ideally the images will be exported as full URLs in a column in the spreadsheet.

When I log into Drupal and click the 'content' button at the top, it gives me a list of every page on the site. I can filter this to only show 'Manufacturer' pages. When I edit a specific manufacturer page it gives me a form containing all of the editable fields for that manufacturer, prepopulated with the data to edit. I just need this information for each manufacturer dumped out into a spreadsheet.

So as a complete Drupal noob, where would I start in doing this? Would I just go straight to the database and try to piece it together (if so, is the data stored in a single table, or will there be some major queries involved in doing this - any pointers about which tables to look at would be greatly received) or is there a tool for getting a bulk export of this kind of thing? I guess I could even create a web page which displayed this information in an HTML table and just scrape it from there, but ideally an export would be nice.

# Answer
> 8 votes
You are in luck! There is a module for that. (I love saying that!)

1. Views Excel Export
2. Views

This is an extension for Views module, which pretty much can list any data from Drupal's DB; users, content, comments and any other entities. You will have to install the Views module and then install the Views Excel Export module which will export the list generated by Views to an Excel file. Without any code! Brilliant isn't it?

If you need instructions on how to install a module in Drupal, you can follow Installing modules (Drupal 7) on Drupal documentation.

# Answer
> 6 votes
There is also Views Data Export. It supports many data formats including Excel and CSV. It also depends on Views. It is designed to handle extremely large datasets by batching the export process but producing one file.

Views Data Export

# Answer
> 2 votes
Another option to consider might be the Forena module, which also comes with quite some community documentation.

Forena is built of the idea of using SQL to get data out of a database (which can be the Drupal database or an external one such as My SQL, Oracle, MS SQL, ...) and use XHTML and CSS to format it into web reports. There are quite some reasons for considering Forena. Visit the Forena HowTos page for some links (near the bottom) to some live demo / showcase links.

Any report can be saved (exported) in various file formats, such as CSV or XLS. To do so, just add `.csv` as an extention to the report (output) URL. That contains the CSV equivalent of that report. As a sample, consider the sample report located at `/reports/sample.states` (in your own site, one of the samples shipped with Forena). Change the URL to `/reports/sample.states.csv` (= just add `.csv` to it) to get the same report in `.csv` format. If you'd add such `.csv` to the URL of the Simple Table of States in the demo site, the result is like so ...

Same technique applies for other supported extensions (export formats), such as adding `.html`, `.xls` (MS Excell), `.pdf` or `.doc` (MS Word).

By the way, all *data blocks* are accessible directly via their url also, provided you have permission to access that block. Here are a few samples of that, for the sample report located at `/reports/sample.states`:

For short, to answer this specific answer I'd write the various (custom) SQLs I need, format it as reports that fit my needs, and then just save it as an XLS (or CSV?).

Disclosure: I'm a co-maintainer of this module,
I hope this does not violate the site's policy on self-promotion.

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


# Question
Title: "Manage display" tab missing in Manage fields window
I am editing and working with fields for a Content type but can only see Field settings, widget type and delete tabs. The Manage display tab is missing.

How do I make it display?

I am running drupal 7

# Answer
> 1 votes
The tab might just be somewhere else. When you edit a content type, you see at least two tabs (provided that the core "Field UI" module is enabled):

* Manage Fields
* Manage Display

If you go to "Manage Fields" and then click on "Edit" for a given field, you will see the "Field Settings", "Widget type" and "Delete" tabs, as you say, but not the "Manage Display" tab. To see it, you need to go to the content type edit screen, it will display the list of fields and their display properties.

Hope that helps,

# Answer
> 0 votes
You need to use the Form Builder module.

It's show the manage field,Display options on particular content type.

> This project allows users to build entire Form API structures through a graphical, AJAX-like interface. It has the ability to read and export FAPI arrays, and users are permitted to change any properties exposed by modules that expose forms to the Form Builder.

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


title: How to add input field in views fields?

text:
# Question
Title: How to add input field in views fields?
I have to store some hidden values in each views rows (**To store Latitude and Longitude of Gmap Locations**). How to add a input hidden field in Views Field. I tried bartik\_preprocess\_views\_view\_fields(&$variables) but it is not invoked.

# Answer
I added the latitude and longitude in views fields and overwritten the global: Custom Text field with the replacement tokens and added "element-hidden" class so that value will be there in views in hidden. Any other Solutions?
> 0 votes

---
Tags: views, google-maps
---


title: Link field to content

text:
# Question
Title: Link field to content
In my view I have 4 fields including an image. I want to link a field other than image field to the content but there is no such option as for the image field i.e "Link to". How can I get this option?Or is there any other way to do this?

# Answer
you can rewrite the output of that field and make it a link. Rewrite works for all fields - some fields do offer a link output in their settings though and might be the better option if available.

Steps to take:

1. add a path to the content and exclude it from output.

2. rewrite the output of the field you want to add a link to.
> 1 votes

# Answer
1) At your field, click on the link you which to add link. 2) Link image to: choose nothing 3) Look for REWRITE RESULTS and click on it 4) Check Output this field as a link 5) Insert your link path
> 0 votes

---
Tags: 7, views, navigation
---


# Question
Title: Drush Make doesn't do anything (Windows)
I've been trying to use `drush make` on a very simple test project (an empty folder containing just the make file) to see how it works, but nothing happens. In the shell, there's a one second delay after I press ENTER, and then the empty prompt comes back. There's no error or confirmation message, and nothing changes in the test folder (not even en empty folder is created).

The command I use is simply: `drush make test.make.yml test`
(Of cource I'm already in the correct folder when I type this command.)

If I omit the last parameter (e.g. `drush make test.make.yml`), then drush waits one second, then asks if I want to "make new site in the current directory ? (y/n)". But if I press Y, still nothing.

`drush make -h` shows the expected help information.

I'm using drush v.6 on a Windows 8.1 xampp local setup. The usual drush commands (e.g. `drush dl views`, etc) work fine, though. (As far as I can tell anyway: I'm not an advanced user.)

I tried with the example file provided in the drush/make documentation, and I also tried to simplify the content of my make file to the max:

```
api: 2
  core: 7.x
  projects:
    drupal:
      version: 7.36

```

Still nothing.

Is there something I'm missing?

# Answer
> 4 votes
I might be mistaken, but I think the YAML format for Makefiles is for Drush v.7 and later. I am using the "old" format with Drush v.6 (and Drupal 7), also on Windows

Might that work with the sample below?

```
; Drush Make API version
api = 2
; Drupal core
core = 7.x
projects[drupal][version] = 7.36

```

Hope it helps,

---
Tags: drush
---


# Question
Title: css file defined in .info file is not loading in Drupal 7
This is the my .info file details

```
name = Tripsinn
description = A flexible, recolorable theme with many regions.
package = Core
version = VERSION
core = 7.x
stylesheets[all][] = css/responsiveslides.css
stylesheets[all][] = css/style.css
scripts[] = js/responsiveslides.min.js

```

but these css are not loading

URL: http://dev.easysites.in/tripsinn/

this is a custom drupal theme under development.

# Answer
As far as I can see in the URL you posted, both `css/style.css` and `js/responsiveslides.min.js` are being loaded fine, but there is no trace of the `css/responsiveslides.css` file. Maybe you are not placing that file in the appropriate directory?

Hope that helps,
> 1 votes

---
Tags: theming
---


# Question
Title: Region not rendering on views page but works perfectly on regular pages!
I have a navigation\_bar region set up in my .info file which renders perfectly on regular drupal pages but I have two pages which are made from Views, but nothing renders. I am using the superfish module to display my menu block which is in the navigation\_bar region. My search bar is in the header region and it displays fine on all pages. When I tried to move the menu into the header region it still doesn't work ! Anyone have an idea what probably might be?

Thanks, Rita

# Answer
From the Blocks settings page at admin/structure/block/manage, go to the configuration for the block in question. In the block's "Visibility settings" section, make sure the "Pages" settings are configured in such a way that the block is not hidden from the View page you are having trouble with.
> 0 votes

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


title: Solr index fields not showing a field

text:
# Question
Title: Solr index fields not showing a field
I have a field within a field collection that I need indexed. It's not showing up in the `/admin/config/search/search_api/index/solr_node_index/fields` page. I tried using this to try to add it myself, but I don't really know how to reference it. I know that the field collection is just an array of id numbers that you can reference, but I need to reference the actual field. Any help is appreciated.

# Answer
> 0 votes
There is an apachesolr field collection module available, which makes me think that field collection support is probably not out of the box with the apachesolr stuff.

As a matter of fact, if you look at the issue queue for the apachesolr module you can find this ticket #1810228 : Process Field Collection Items. It confirms that field collections are not supported out of the box, and the comments point to the apachesolr field collection module, and indicate that the module may be buggy...

I'd say try it, but test your integration thouroughly. And do try both available versions (alpha and dev), and see how it goes.

---
Tags: 7, entities, search
---


title: Drupal Commerce Title length

text:
# Question
Title: Drupal Commerce Title length
I'm facing a problem with commerce product title length. I want to increase the lenght over 255. What I've tried so far is:

* Change DB field from varchar to text
* Change the maxlength of the form field
* Change the formfield to a textarea

Any of the form changes lead to an error. Any idea how to increase the length?

# Answer
> 1 votes
I wouldn't increase the length of the field, but instead ask yourself why you are storing so much information in the title. There is a very good chance you simply need to split the information out into different fields or use a textarea to store ancillary information. You don't know how many assumptions commerce makes about the title field with regards to logic and formatting and the general Commerce wisdom is to not mess with the internals.

# Answer
> 1 votes
Sam's answer and comments should be taken as the best advice for this, but as a technical exercise it shouldn't be too difficult:

```
// Alter the schema
function MYMODULE_schema_alter(&$schema) {
  $schema['commerce_product']['fields']['title']['length'] = 512;
  $schema['commerce_product_revision']['fields']['title']['length'] = 512;
}

// Change the DB in an update hook
function MYMODULE_update_7100() {
  $schema = drupal_get_schema_unprocessed('commerce_product');

  $new_field = array('length' => 512) + $schema['commerce_product']['fields']['title'];
  db_change_field('commerce_product', 'title', 'title', $new_field);

  $new_field = array('length' => 512) + $schema['commerce_product_revision']['fields']['title'];
  db_change_field('commerce_product_revision', 'title', 'title', $new_field);
}

// Change the form
function MYMODULE_form_commerce_product_product_form_alter(&$form, &$form_state, $form_id) {
  $form['title']['#maxlength'] = 512;
}

```

Completely untested, use with caution.

---
Tags: commerce
---


title: Display Product Field twice

text:
# Question
Title: Display Product Field twice
I simply want to display Product Details twice on my page.

I use **Display Suite** for displaying all my fields on the node (Product Display) and for displaying the field twice, I would like to use a **Dynamic Field**. It lets me select the field but when I view my node I get a 500 Error.

Can someone help me please? Thank you very much in advance for your help!

# Answer
You can use Display Suite to duplicate your fields, go into Structure -\> Display Suite -\> Fields and add a dynamic field. Fill out the details specific to your node, etc.

On the Manage Display page of your content type you need to configure this field and select your product details, etc.
> 0 votes

---
Tags: entities, commerce, display-suite
---


# Question
Title: Boolean fields configuration - How to enter a string in ON/OFF value bigger than allowed?
How to enter a bigger string than allowed in boolean fields?

When I try to submit a string bigger than a certain value, the string is automatically cutted.

I want to put this text:

> (4% du montant total de la location et 0.5 .- par jour et par personne pour l’assistance/rapatriement en cas de location à l’étranger)

But only this is allowed:

> (4% du montant total de la location et 0.5 .- par jour et par personne pour l’assistance/rapatriement en cas de location à l’étr

# Answer
Trim the field down to something suitable so it makes sense, something like - 4% du montant total de la location et 0.5, and put the rest into the description field.
> 0 votes

---
Tags: entities
---


# Question
Title: Programmatically creating a node doesn't save custom fields
I'm using this code in Rules, after saving a certain type of content, in execute custom PHP code. By now, i'm just trying to create anothe node of that type after the first is created. The problem is that this code creates a new node indeed, but without any custom fields. It has only language associated to it. Any idea on what's wrong? I followed the tutorial at http://fooninja.net/2011/04/13/guide-to-programmatic-node-creation-in-drupal-7/

```
$nodo = new stdClass(); // Create a new node object
$nodo->type = "capitoli"; // Or page, or whatever content type you like
node_object_prepare($nodo); // Set some default values
$nodo->language = 'it'; // Or e.g. 'en' if locale is enabled
$nodo->uid = $node->uid; // UID of the author of the node; or use $nodo->name
$nodo->field_numero_capitolo[$nodo->language][0]['value']="2220";
$nodo->field_link[$nodo->language][0]['value']="aafafsf";
$path = 'node_created_on' . date('YmdHis'); // I prefer using pathauto, which would override the below path
$nodo->path = array('alias' => $path);
if($nodo = node_submit($nodo)) { // Prepare node for saving
    node_save($nodo);
    echo "Node with nid " . $nodo->nid . " saved!\n";
}

```

If I replace

```
$nodo->language = 'it';

```

with

```
$nodo->language = LANGUAGE_NONE;

```

this code create another node identical to the first one, not considering the values I used in the code and I can't figure out why.

EDIT: I tried doing as suggested in comments

```
$nodo->field_numero_capitolo['und'][0]['value']="2220";
$nodo->field_link['und'][0]['value']="aafafsf";

```

And it seems to work. What i did was to insert directly 'und'. Generally I think it is not a good idea to write directyl 'und', but these two fields are a link and a number, that should not change depending on language.

# Answer
If you're using Rules anyway why don't you use the Create new entity action which should take care of everything? You will need to use the Set a data value action multiple times and possibly the Save entity action too.

In answer to your question I think you need to set the language before node\_object\_prepare so your code would become:

```
$nodo = new stdClass(); // Create a new node object
$nodo->type = "capitoli"; // Or page, or whatever content type you like
$nodo->language = 'it'; // Or e.g. 'en' if locale is enabled
node_object_prepare($nodo); // Set some default values

```

Also you don't need the node\_submit($nodo) line
> 1 votes

# Answer
I better way is to simply use the entity api and entity\_metadata\_wrapper for entity CRUD operations:

```
$nodo = entity_create('node', array('type' => 'capitoli'));
$nodo_wrapper = entity_metadata_wrapper('node', $nodo);
$nodo_wrapper->author = $node->uid;
$nodo_wrapper->field_numero_capitolo->set('2020');
$nodo_wrapper->field_link->set("aafafsf");
$nodo_wrapper->save();

```

See http://www.drupalcontrib.org/api/drupal/contributions!entity!entity.module/function/entity\_metadata\_wrapper/7
> 0 votes

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


# Question
Title: Set the back-office theme to a specific url
(On drupal 6)

On some of the websites i have to manage, the translation page of a node ( mywebsiteurl.com/node/NodeNid/translate) use the main theme instead of the back office theme.

I have some ideas about how force the back office theme, but i doubt it's the right way.

I create a specific module and use a preprocess\_page function to force a

```
$GLOBALS['custom_theme'] = variable_get('theme', 'mybackofficetheme')

```

if i am in a translation page. But it doesn't works, so can you suggest me the best practice?

# Answer
I'm not familiar with using translation pages, but I've had good success using the themekey module for changing themes based on URL: https://www.drupal.org/project/themekey
> 0 votes

---
Tags: 6, theming
---


# Question
Title: Get values from views exposed filter in hook_views_pre_view
I would like to get the current values from an exposed filter in hook\_views\_pre\_view().

For example, if the input filter has some value I would like to change de pager: number of items, the problem is how to get this value from views without using $\_GET because I don't think it will work with views ajax.

What is the right way to get current exposed filters values from a view?

# Answer
> 1 votes
I've found it, there is a views method:

```
$input = $view->get_exposed_input();

```

---
Tags: 7, views
---


# Question
Title: Contextual filter for an indirect taxonomy term?
I know how to display similarly tagged items of a different content type in a view block (here is a good explanation and settings picture).

I have a scenario where the term IDs aren't *directly* associated with both content types. The term reference field on the page content type is attached, not to the view content type itself, but to **another taxonomy that is attached to the view content type** (the view content type uses a taxonomy that has a field which is also used in the page content type).

How can I filter my view to items that are "mapped to" the term?

# Answer
To rephrase (to see if I understood correctly): You have a content type pointing to term reference #1, that is pointing to term reference #2. You want to show the content that points to term #1, with the context being term #2.

In that case, you'd need to create a relationship (see Using Views Contextual Filter and Relationship to display reference on referenced node)

(The following explanation would work best with entity reference instead of term reference - I don't use that field type so I'm not sure the relationship exists with it)

But in short, you'd create a relationship to "referencing entity from field\_term\_reference" (the field on term #1 pointing to term #2). From there you could create the "referencing entity" relationship from the field on the content type pointing to term #1. The contextual filter would be to the term ID #2 using that relationship.
> 0 votes

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


# Question
Title: How to have node id value set depending on some other id?
I have database table which I need to import it in drupal database (basically create a node for each row of database table ) .
The non drupal database has mim Id .
I want to create a node which would have the mim Id == node id
So in all, how can I achieve such that Drupal's ID node will be SAME as article ID (this ID is used in an external media CDN server).

I tried looking at the CDN module but could not find a solution for the same

# Answer
> 0 votes
Take a look at migrate module and this hands-on guide (disclaimer: I work for that company, so to balance: lullabot's guide ) Both are good to understand everything that's necessary for what you asked.

You might want to consider creating a `field_old_node_id` field to ease on the transfer if you can't set the ID through this, and use Pages module to create a separate `/node/%nid` page that uses that field instead to display the node.

---
Tags: 7, nodes, cdn
---


# Question
Title: Update a field on a node after hitting save
I am working on a Drupal 7 custom module and would like to update a field on a node after hitting save. Based on some post that I have seen this should be possible.

As it is now I have the $node object is a parameter to the node\_submit hook after hitting save.

However, I am not able to update my field on this node object. Any pointers or examples of how to do this would be greatly appreciated.

Thanks, Derek

# Answer
> 1 votes
Depending on your exact usage, you'd want to use either

1) `hook_node_presave` \- Called on any node being saved (inserted or updated). see here

2) Attach a submit handler to the form: Allows to change the form's values before the submit is completed.

---
Tags: nodes, hooks
---


# Question
Title: How can I dynamically disable a single required field from validation in a form?
This is an extension of this question:

Need help with AJAX callback function for text field validation in form\_alter

I have a form with a Username autocomplete field (txn\_user). The editors want to be able to enter a UID (txn\_userid) as an alternative way of specifying the User for the form. They want to be able to enter the UID and skip the Username field altogether.

So in my form validation function, I want to be able to disable the required property (and all other validation) of the Username field during a Submit IF the editor typed in a UID field. In other words: the UID field should 'short-circuit' the Username field.

This is what I have so far (which doesn't work, obviously). Or do I need to do this via AJAX or straight JS?

```
function _validate_add_userpoints_userid(&$form, &$form_state) {
    $values = $form_state['values'];
    if( $values['txn_userid'] ) {
        $newuser = user_load($values['txn_userid']);
        if( ! $newuser) {
          form_set_error('txn_userid', 'You have entered an invalid UID. Either leave this blank and select a Username or enter a valid UID');
    }
    else {
        // this part works... the User Name is properly assigned.
        $form['txn_user']['#value'] = $newuser->name;
        $form_state['values']['txn_user'] = $newuser;
        $form_state['input']['txn_user'] = $newuser->name;

        // this part doesn't work... the User Name field is still required on submit.
        $form['txn_user']['#disabled'] = TRUE;
        $form['txn_user']['#ajax_processed'] = TRUE;
        $form['txn_user']['#required'] = FALSE;
        $form['txn_user']['#needs_validation'] = FALSE;
        unset($form['txn_user']['#process']);
    }
}

```

}

# Answer
Why dont you use conditional field module?

https://www.drupal.org/project/conditional\_fields

By this module you can disable the requirement of fields when something happens to another field. you can also implement your form as a content type so its node/add page will be your form. Then by using the different hooks you can add autocomplete field or do any thing else
> 0 votes

---
Tags: forms
---


# Question
Title: How to give class name to no results behavior in views
I added price column first to view \> hide it. I added special price column to view \> in no results behavior i added price field token as below:

```
[field_price]

```

How to give a css class name to the 'no results behavior text'?

Thanks,

D

# Answer
Can you add a class to the no results token? Like `<span class="some_class">[token]</span>`. Dunno if it works that way. Try that.
> 0 votes

---
Tags: theming
---


# Question
Title: Custom error for user registration page in D7 not working
I can't seem to figure out why this custom module refuses to execute for user registration validation. I've made sure I'm using the correct form id using firebug, verified the module is installed properly, but this module just refuses to show an error when the username is left blank during registration.

I thought the issue might have to do with the theme I'm currently using (Venture Theme), but I'm not really sure how to check the theme to verify the id's weren't changed. Anyone have an idea why this code won't run properly?

```
<?php
/**
* Implements hook_form_alter().
*/
function validation_form_user_register_form_alter(&$form, &$form_state) {
    $form['#validate'][] = 'validation_user_register_validate';
}

function validation_user_register_validate($form, &$form_state) {
  if (empty($form_state['values']['name'])){
        form_set_error('name', t('username is empty!'));
    }
}

```

# Answer
The reason why it's not displayed are:

1. Since the field is required, Drupal handles that already so your user-defined validation wouldn't run since Drupal make's sure the field passes "required" validation and when it reaches your trapping, it's never empty.
2. > First ensures required fields are completed, #maxlength is not exceeded, and selected options were in the list of options given to the user. Then calls user-defined validations.

Reference: function \_form\_validate

Here is an example that your functions are right.

```
if ($form_state['values']['name'] == 'asdasd'){
    form_set_error('name', t('username is asdasd!'));
}

```

That will trigger your validation since it passes the "required" validation and checked the username for something aside from being empty which conforms to the description of the \_form\_validate.
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Google Analytics custom dimension for anonymous/authenticated users
I use Drupal 6 and Google Analytics module. I'd like to have custom dimensions to add segmentation for anonymous/authenticated users. I have added a custom dimension with **\[user-role-name\]** token. But I have a lot of roles for authenticated users, and then I get a long list of roles in GA data. I'd like to have only anonymous vs authenticated.

Is there anyway I could filter it with GA module in order to send only this two roles names? Thanks.

# Answer
> 0 votes
There currently isn't a role token that provides only a anonymous/authenticated role. The only way to do this (without removing all roles) is to create your own custom token to use with GA.

---
Tags: google-analytics
---


# Question
Title: How to set form action to default contact form action
I'm editing a Drupal site, it has a hardcodeded contact form which I would like to have the same behaviour than the default contact form (applying filters, inserting info in the database and sending email).

Maybe it is an easy question but I don't know how to do it.

Thanks!

# Answer
I not sure will this help you. If you have no other solution, how about try to use webform module with form builder. I not sure what you mean filter, but its help to store in database and send email easily.

Hope this help you.
> 1 votes

---
Tags: forms, emails
---


# Question
Title: D7 module for payment associated to a node?
I am looking for a D7 module that will allow users to make a payment that is related to a node. So let's say I have a content type called 'Events', and have lots of nodes in the 'Events' content type, I want users to be able to pay in order to attend one of these Events. So maybe the user would view an Events node, and then they can pay for the node (not to view it... but pay for what the node is offering: e.g. an event)

Anyone know of anything??

I don't want to use Drupal Commerce because I don't want a shop per se, I just want to take payment related to a node.

Thanks so much!

# Answer
There are a number of options. Drupal Commerce is obviously really powerful, but if you want something light take a look at the Drupal Pay module. It is pretty light weight and integrates with webform and a number of other modules.
> 0 votes

# Answer
An option is to use the ubercart module. When you create a Event, you create a product (can be done automatically with rules). On each event page you show a block of the corresponding product. You disable in the store and cart section most things and you have a lightweight shop/solution.
> 0 votes

---
Tags: views, 7, commerce
---


# Question
Title: URL Alias for Taxonomy for multiple child terms
I am having a problem setting up the url alias for a vocabulary with recurring child terms. So for instance the vocabulary consists of categories and locations.

* Category 01
    + All
    + Location 01
    + Location 02
* Category 02
    + All
    + Location 01
    + Location 02
* Category 03
    + All
    + Location 01
    + Location 02

At the moment I have 2 separate vocabularies of event categories and event locations. For the node url I have setup the alias as

```
events/[node:field_event_category]/[node:field_event_location]/[node:field-event-start:value:custom:Y-m-d]-[node:title]

```

Now where I am stuck is setting up the url alias for the category and location.

Can anyone help with the best way to setup the vocabulary and url aliases? - Thank you.

# Answer
> 0 votes
From what I'm seeing, you're wanting to represent your 2 different taxonomies as a path hierarchy, but not a taxonomy hierarchy (i.e. Category terms don't have Location child terms). So you're looking to create something like:

* `events/` : All Events
* `events/X`: Events in Category X
* `events/X/Y`: Events in Category X & Location Y

Pathauto cannot create mixed-vocab url aliases however, so for a path hierarchy you can create a page view with a couple of contextual filters, one for Category & another Location. The linked example should walk you through how to do this.

---
Tags: taxonomy-terms, path-aliases
---


title: Website 'drupy' cannot be found

text:
# Question
Title: Website 'drupy' cannot be found
At our place it was decided to move away from PHP/Drupal (for bad or good) to a Python based solution (Django). One thing we seriously consider is to do a gradual transition and for that I wanted to look at `drupy` that I have read about some time ago.

But the website www.drupy.com is some advertisement site now and googling *drupy* got me a lot of videos on youtube. Did this project get renamed? Where can I find information?

Is there some generic transition guide for gradual transition from Drupal?

# Answer
> 6 votes
The project used to be on www.drupy.net (not .com), but that is an advertisement now as well.

The project was unfortunately discontinued (I like Drupal, but it is hard to move away from if you have to, and sometimes that is the better solution). The remainder can be downloaded from GitHub.

# Answer
> 3 votes
Looks like the maintainer left his domains to expire. The GitHub repo is still up however.

---
Tags: migrations
---


# Question
Title: How to diasplay stock quantity of goods in node-product.tpl.php
I need to get quantity of goods in stock and display a number in the product page node-product.tpl.php.

Here is what I added in the template, but `uc_stock_level()` seems not to work properly.

```
$stock = uc_stock_level($node->model);
if ($stock > 0) {
    print $stock;
} else {
    print $stock;
}

```

I am using Ubercart 2.

# Answer
> 0 votes
There is not much to `uc_stock_level()`. Check that you are supplying a model/SKU that is in the table and it is active. If that's the case, you might need to flush your cache to pick up new changes in your template file.

---
Tags: ubercart
---


# Question
Title: Can't use drush site-install to drop tables and reinstall in MAMP
I have a local multisite instance running MAMP 3.0.7.3, and I can't use the `drush site-install` command to do a re-install of one of my sites without actually dropping the database first.

If I try the command without dropping the database, I get the following output:

```
$ drush --uri="www.example.local" si -y my_great_install_profile --account-pass=admin --sites-subdir="www.example.com"
You are about to DROP all tables in your 'example_site' database. Do you want to continue? (y/n): y
<h1>Additional uncaught exception thrown while handling exception.</h1><h2>Original</h2><p>PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table &#039;example_site.registry&#039; doesn&#039;t exist: SELECT filename FROM {registry} WHERE name = :name AND type = :type; Array
(
    [:name] =&gt; drush_drupal_site_install
    [:type] =&gt; interface
)
 in _registry_check_code() (line 3188 of /Users/gravelpot/sites/www.example.local/includes/bootstrap.inc).</p><h2>Additional</h2><p>PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table &#039;example_site.registry&#039; doesn&#039;t exist: SELECT filename FROM {registry} WHERE name = :name AND type = :type; Array
(
    [:name] =&gt; drush_drupal_environment
    [:type] =&gt; interface
)
 in _registry_check_code() (line 3188 of /Users/gravelpot/sites/www.example.local/includes/bootstrap.inc).</p><hr />Drush command terminated abnormally due to an unrecoverable error.                                                                            [error]
<h1>Uncaught exception thrown in shutdown function.</h1><p>PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table &#039;example_site.semaphore&#039; doesn&#039;t exist: DELETE FROM {semaphore}
WHERE  (value = :db_condition_placeholder_0) ; Array
(
    [:db_condition_placeholder_0] =&gt; 1731533568552880e6a71ed3.80394544
)
 in lock_release_all() (line 269 of /Users/gravelpot/sites/www.example.local/includes/lock.inc).</p><hr />

```

I also have the same problem when trying to import a SQL dump file by doing something like `drush sql-drop` followed by `drush sqlc < path/to/file.sql`, which is a pattern I see suggested in a lot of blog posts.

I am using Drush 6.5 installed via composer. My co-workers have a similar configuration, and do not have this problem.

# Answer
Make sure nothing breaks Drush calls; attempt a `drush cc all` to see if the error still appears, and debug if it does.

To avoid dropping the database, the simple "hacked" answer is:

1. Edit site's settings.php file to use another database scheme (make sure it exists though).

```
$databases = array (
  'example1' =>
  array (
    'example1' => array (
      'database' => 'example2', // Changed from "example1".
      'username' => 'user',
      'password' => 'pass',
    ),
  ),
);

```
2. Use `site-instal` . This will drop "Example2" and install the site there, without hurting the original database.
3. Edit the site's configuration file back to original database scheme.

You need to use backquotes on the "drush sqlc" part:```drush sql-connect`` < path/to/file.sql`.
> 1 votes

---
Tags: database, drush
---


title: Using Masquerade to test UC coupons

text:
# Question
Title: Using Masquerade to test UC coupons
I'm dealing with an old D6 Ubercart site that uses UC Coupon & UC Free Order to enable free orders for users with a certain role when they enter free order code. I'm masquerading as one these users but I'm finding it won't pick up on coupon code when I enter it. It gives me the "Warning: Coupon does not exist or is not valid." error.

I'm thinking it might be a quirk with how masquerade works. It looks like my account address book entries are showing up in Billing Information despite masquerading as another user.

# Answer
Instead of using masquerade, you could use `drush uli [%uid]`

It gives you a clean login to the site, which you could open in an incognito mode on a browser, removing all other cookies. This will allow you to debug without feeling that other modules are interrupting.

Bonus: add `--uri=[%site-base-uri]` to automatically open in your default browser (although not incognito).
> 1 votes

---
Tags: 6, ubercart
---


# Question
Title: How can I Hide in Drupal 7 the bottom blocks in Add and Edit button for my content
I made a new content type in Drupal 7 without problems, but now I want to hide the bottom block in the content Add and Edit fonctions This block as some url's parameters, comments parameters ...I don(t want to show to the users or registered users

I cant't find where and how I mask this blocks, Thanks for your help

# Answer
> 0 votes
Sorry I have found the answer myself

If I use another login than admin the blocks are not shown,

Sorry

# Answer
> 0 votes
U can use the module tab tamer for that

---
Tags: entities
---


# Question
Title: How to automatically generate a table of contents for a list of nodes?
I want to generate a table of contents made up of the titles of the nodes listed within a view, which will then be displayed at the top of that view. The nodes are of just one content type.

I've spent the last couple of days looking through the pre-existing modules, but thus far they all seem to generate TOCs only for one particular node.

Can anyone point me in the correct direction?

# Answer
> 2 votes
You can make use of the attachment display in Views.

1. Create your normal view
2. Add an attachment display to that view:

3. Set "Attach to" to your normal view display
4. Configure the attachment display to show titles of your content types nodes.

---
Tags: views, nodes
---


# Question
Title: Entity registration, register to more event from one form in event detail
Hi I have created special content type called Event. It is simillar to facebook events. It has description, address where it will be held and date when it will be held. I succesfully added there registration form with Entity registration. So now I can register to one event. But I want to be able to register from one event to more events like this.

In event detail, registration form section, I want to have checkboxes. When I click on these checkboxes and click on register to event, it will register me to every clicked event, and to opened event too. These additional event, I will select in administration, when creating new event.

# Answer
> 2 votes
Install VBO module, create a entity view with checkboxes. See the Rules sections here. You can use that rule in VBO to register them automatically to the Events they selected.

# Answer
> 0 votes
Ultimately I found no solution to this problem, and so I had to write a custom module, which is just about finished. I will post the link to the Drupal.org location when it is finished.

# Answer
> 0 votes
You may use conditional fields to make multiple work flows.

For example, make your type of events as drop-down from taxonomy reference. Then each option value has a conditional field is possible.

But if you need completely different forms itself you can do this by creating registration types and add fields accordingly.

You can make a registration type switching in content type creation and which enables users to select the right event to register.

-- Najeem M Illyas

---
Tags: entities
---


# Question
Title: how to call a JQuery function inside an ajax callback function
I have a custom module, this module has a form with an ajax submit callback

```
$form['submit'] = array(
'#type' => 'submit',
'#ajax' => array(
    'callback' => 'mymodule_submit_driven_callback',
    'wrapper' => 'box',
),
'#value' => t('Submit'),
);

```

I into the callback function I need to call a JQuery function:

```
function mymodule_submit_driven_callback($form, $form_state) {
//call JQuery function here
}

```

How can I do this? Thanks.

# Answer
As Jose Daniel said: use ajax\_command\_invoke() in your ajax callback:

```
$commands[] = ajax_command_invoke(NULL, "your_function");
$output = array('#type' => 'ajax', '#commands' => $commands);
ajax_deliver($output);

```

Your JS-File:

```
(function ($) {
  $(document).ready(function(){
    $.fn.your_function = function() {
      // do cool stuff
    }
  });
})(jQuery);

```
> 1 votes

# Answer
You seem to be asking a question by proposing an answer ... Why again do you need to call a jQuery function from within in your callback?

Normally in D7 the ajax callback function creates a list of `Commands` to send back to the client and perform client side javascript using jQuery.

Did you read up on the Ajax framework used by Drupal?

> #ajax\['callback'\]: The callback to invoke to handle the server side of the Ajax event, which will receive a $form and $form\_state as arguments, and returns a renderable array (most often a form or form fragment), an HTML string, or an array of Ajax commands. If returning a renderable array or a string, the value will replace the original element named in #ajax\['wrapper'\], and theme\_status\_messages() will be prepended to that element. (If the status messages are not wanted, return an array of Ajax commands instead.) #ajax\['wrapper'\]. If an array of Ajax commands is returned, it will be executed by the calling code.

EDIT:

Also see the Ajax Examples in the Developer Examples module.
> 0 votes

# Answer
I solved it using ajax\_command\_invoke().
> 0 votes

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


# Question
Title: Two concerns: Available for security updates / Image captions
I am looking at revamping a set of sites from ASP to Drupal. I like a lot of what I see in Drupal, but have two concerns:

1. In reading about Drupalgeddon, it seems that the problem was that many people didn't even see the security notice before hackers started exploiting the vulnerability. I have no staff, so this means I need to be available immediately to install security updates when they are announced. I don't know that I want to be chained to my websites that way, or leave them potentially vulnerable if I decide to go on vacation for a month.
2. I've been amazed to find that Drupal has no innate ability to put captions on images. Doing that appears to require choosing between three modules (Image Caption, Image Field Caption, or Image Caption Formatter) with no documentation that compares and contrasts the modules to help with the choice. Putting captions on images is a pretty basic requirement, so it makes me wonder what else I'm going to find out I can't do easily once I start porting content.

Comments?

# Answer
1. No matter which CMS you use this will always be an issue. If you do not have time to be proactive about maintaining your software, you should look into paying someone to do it for you.
2. This is the result of Drupal's modular design. It's done this way so it can accommodate the wide-spectrum of use cases. It's a simplicity/flexible tradeoff that can be good and bad depending on the circumstances.
> 0 votes

---
Tags: media, migrations, security
---


# Question
Title: Can I move distribution profile modules from profile folder to sites/all/modules?
I just installed a distribution profile and ran `Drush up` to update modules.

I have some problems with the modules located at profiles/somefolder/modules: Drush moved out the old modules but no new modules are added.

Can I move the modules from profile folder to sites/all/modules?

The installation profile is Commerce Kickstart.

# Answer
If the modules in question are not enabled you can move the modules.

The paths to their location in the system table in the database will be updated when you visit /admin/modules.

However, If they are enabled you may run into issues.

See http://drupal.org/node/183681
> 2 votes

# Answer
To further complete the prior answer ... As so often in Drupal: there's a module for it ... called "Registry Rebuild", also mentioned on the link in the prior answers. And it integrates with Drush via the `Drush RR` command.

Basically what you do is to (1) just move your modules to another directory, and (2) Registry Rebuild will then rebuild the system table to get the modules in the right place.

I first learned/discovered it via DrupalEasy Podcast #133, which also explains how this module /drush cmd comes in handy for these kinds of moves.
> 1 votes

---
Tags: 7, distributions
---