# Question
Title: Ubercart most selling product in drupal 7
I'm using Drupal 7 on my site with Ubercart 7.x - 3.4. I want is an existing module or a view customization tips to make the most selling / best selling product.

# Answer
Here is a view Export

```
$view = new view;
$view->name = 'best_sellers';
$view->description = 'Best Sellers';
$view->tag = 'Best Sellers';
$view->base_table = 'node';
$view->human_name = 'Best Sellers';
$view->core = 7;
$view->api_version = '3.0-alpha1';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Defaults */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '5';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Fields: uc_product_image */
$handler->display->display_options['fields']['entity_id']['id'] = 'entity_id';
$handler->display->display_options['fields']['entity_id']['table'] = 'field_data_uc_product_image';
$handler->display->display_options['fields']['entity_id']['field'] = 'entity_id';
$handler->display->display_options['fields']['entity_id']['label'] = '';
$handler->display->display_options['fields']['entity_id']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['entity_id']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['entity_id']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['entity_id']['alter']['trim'] = 0;
$handler->display->display_options['fields']['entity_id']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['entity_id']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['entity_id']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['entity_id']['alter']['html'] = 0;
$handler->display->display_options['fields']['entity_id']['element_label_colon'] = 1;
$handler->display->display_options['fields']['entity_id']['element_default_classes'] = 1;
$handler->display->display_options['fields']['entity_id']['hide_empty'] = 0;
$handler->display->display_options['fields']['entity_id']['empty_zero'] = 0;
$handler->display->display_options['fields']['entity_id']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['entity_id']['settings'] = array(
  'image_style' => 'thumbnail',
  'image_link' => 'content',
);
/* Field: Node: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['title']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['title']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['title']['alter']['trim'] = 0;
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['title']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['title']['alter']['html'] = 0;
$handler->display->display_options['fields']['title']['element_label_colon'] = 1;
$handler->display->display_options['fields']['title']['element_default_classes'] = 1;
$handler->display->display_options['fields']['title']['hide_empty'] = 0;
$handler->display->display_options['fields']['title']['empty_zero'] = 0;
$handler->display->display_options['fields']['title']['link_to_node'] = 1;
/* Field: Product: Buy it now button */
$handler->display->display_options['fields']['buyitnowbutton']['id'] = 'buyitnowbutton';
$handler->display->display_options['fields']['buyitnowbutton']['table'] = 'uc_products';
$handler->display->display_options['fields']['buyitnowbutton']['field'] = 'buyitnowbutton';
$handler->display->display_options['fields']['buyitnowbutton']['label'] = '';
$handler->display->display_options['fields']['buyitnowbutton']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['buyitnowbutton']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['buyitnowbutton']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['buyitnowbutton']['alter']['trim'] = 0;
$handler->display->display_options['fields']['buyitnowbutton']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['buyitnowbutton']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['buyitnowbutton']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['buyitnowbutton']['alter']['html'] = 0;
$handler->display->display_options['fields']['buyitnowbutton']['element_label_colon'] = 1;
$handler->display->display_options['fields']['buyitnowbutton']['element_default_classes'] = 1;
$handler->display->display_options['fields']['buyitnowbutton']['hide_empty'] = 0;
$handler->display->display_options['fields']['buyitnowbutton']['empty_zero'] = 0;
/* Field: Product: Sell price */
$handler->display->display_options['fields']['sell_price']['id'] = 'sell_price';
$handler->display->display_options['fields']['sell_price']['table'] = 'uc_products';
$handler->display->display_options['fields']['sell_price']['field'] = 'sell_price';
$handler->display->display_options['fields']['sell_price']['label'] = '';
$handler->display->display_options['fields']['sell_price']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['sell_price']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['sell_price']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['sell_price']['alter']['trim'] = 0;
$handler->display->display_options['fields']['sell_price']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['sell_price']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['sell_price']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['sell_price']['alter']['html'] = 0;
$handler->display->display_options['fields']['sell_price']['element_label_colon'] = 1;
$handler->display->display_options['fields']['sell_price']['element_default_classes'] = 1;
$handler->display->display_options['fields']['sell_price']['hide_empty'] = 0;
$handler->display->display_options['fields']['sell_price']['empty_zero'] = 0;
$handler->display->display_options['fields']['sell_price']['set_precision'] = 0;
$handler->display->display_options['fields']['sell_price']['precision'] = '0';
$handler->display->display_options['fields']['sell_price']['format_plural'] = 0;
/* Sort criterion: Order product: Qty */
$handler->display->display_options['sorts']['qty']['id'] = 'qty';
$handler->display->display_options['sorts']['qty']['table'] = 'uc_order_products';
$handler->display->display_options['sorts']['qty']['field'] = 'qty';
$handler->display->display_options['sorts']['qty']['order'] = 'DESC';
/* Filter: Node: Is a product */
$handler->display->display_options['filters']['is_product']['id'] = 'is_product';
$handler->display->display_options['filters']['is_product']['table'] = 'uc_products';
$handler->display->display_options['filters']['is_product']['field'] = 'is_product';
$handler->display->display_options['filters']['is_product']['value'] = '1';

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'best_sellers');
$handler->display->display_options['defaults']['title'] = FALSE;
$handler->display->display_options['title'] = 'Best Sellers';
$handler->display->display_options['defaults']['css_class'] = FALSE;
$handler->display->display_options['css_class'] = 'new-product-block';
$handler->display->display_options['block_description'] = 'Best Sellers';
$translatables['best_sellers'] = array(
  t('Defaults'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort By'),
  t('Asc'),
  t('Desc'),
  t('.'),
  t(','),
  t('Block'),
  t('Best Sellers'),
);

```

**How to**

1. Login to Drupal as an administrator. Go to Structure \> Views.
2. Click “Import View from Code”

Add "Popular Products" view
> 3 votes

# Answer
easyrec for ubercart integrates the product recommender functionality of easyrec (http://easyrec.org/) into an ubercart shop. It provides Drupal Blocks for the display of recommendations or product rankings. Also you can **integrate with views 3**.

Available Blocks

> * easyrec: other users also bought
> * easyrec: other users also viewed
> * easyrec: recommendations for user
> * **easyrec: most bought items**
> * easyrec: most viewed items

The Blocks are fully style-able using the module administration interface. Or can use one of the following drawing callbacks:

> * Views 3 support
> * Jquery Carousel
> * Image List
> * Text List
> * create your own using javascript or the drupal hook
> 0 votes

---
Tags: 7, views, ubercart
---


# Question
Title: Is there a setting to add a suffix and prefix to a list(integer) field like there was in Drupal 6?
I am in the process of migrating a Drupal 6 site to 7. Several of my content types have a field called "Rating" which was an integer field in D6 that used a `<select>` to choose a value 1-10.

In the process of migrating to D7 this field was converted to a list(integer) field. On the old site I was able to add a suffix of "/10" to this value in the field's settings so the field would always render as "#/10". However, in Drupal 7 there is no longer a place to set this suffix on the field's setting page.

Does this setting exist anymore for this field type? If not, do I have any options for adding this suffix outside of creating a custom "field--field-rating.tpl.php" template?

# Answer
You can do it with Simple Field Formatter module, see the below screenshot

Which allows site administrators to easily control the display of field values with following features

> * Prepend the field value with specified text/HTML
> * Append the field value with specified text/HTML
> * Reverse the Field Value
> * Trim the Field Value
> * Convert the field value to lowercase letters
> * Convert the field value to uppercase letters
> * Convert the first character of the field value to uppercase
> * Convert the first character of each word in the field value to uppercase (7.x-1.x-dev)
> * Replace some characters with some other characters in the field value (7.x-1.x-dev)
> * Link the field value to node(7.x-2.x-dev)
> 2 votes

---
Tags: 7, entities, migrations
---


title: URL field in Webforms

text:
# Question
Title: URL field in Webforms
I see only e-mail and textfield, but no URL.

How can I add to my form URL field with the validation rules for URL? e.g.

```
http://somesite.com

```

or

```
somesite.com

```

or

```
www.somesite.com

```

?

# Answer
> 2 votes
Well if you have tons of time you could implement a component type... but because that is unlikely you should just add a validation hook and a textfield to the webform. You could do a `valid_url($form_state['values'][[your_field_name']);` in your validation hook.

Someone asked this question on d.o previously here. You can find all sorts of examples on "things you may need to do special with a webform" here.

Another possible solution would be to install the Webform Validation module, add a regex validation to your field, and steal a known usable url validation regex like drupal has.

# Answer
> 2 votes
There is a module called webform\_link that could also help you.

> This module verifies that a valid URL is entered and displays the result as a link.

---
Tags: webforms
---


# Question
Title: Adding Profile2 fields to user registration
I have a custom module that overrides the /user/register page so that in addtion to username and email it also asks for about 10 or so Profile2 pieces of information.

The code I have so far:

```
    $form['hi'] = array(
      '#type' => 'fieldset',
      '#prefix' => '<div id="container_a">',
      '#suffix' => '</div>',
      '#title' => t('Additional Info'),
    );

    $form['hi']['l'] = array(
      '#type' => 'fieldset',
      '#prefix' => '<div id="left">',
      '#suffix' => '</div>',
    );

    $form['hi']['r'] = array(
      '#prefix' => '<div id="right">',
      '#suffix' => '</div>',
      '#type' => 'fieldset',

    );

    $form['hi']['l']['h_ph'] = $form['profile_memberlist']['field_home_phone']['und'][0];

```

The form renders a space for username, email and Home Phone. I fill out the form, and submit, and I get the following:

> Thank you for applying for an account. Your account is currently pending approval by the site administrator. In the meantime, a welcome message with further instructions has been sent to your e-mail \>address.

Error message

```
Notice: Undefined index: profile_memberlist in profile2_form_submit_build_profile() (line 471 of /var/www/html/example/sites/all/modules/profile2/profile2.module).
Warning: array_merge(): Argument #1 is not an array in field_default_extract_form_values() (line 36 of /var/www/html/example/modules/field/field.default.inc).
Recoverable fatal error: Argument 2 passed to drupal_array_get_nested_value() must be an array, null given, called in /var/www/html/example/modules/field/field.default.inc on line 38 and defined in drupal_array_get_nested_value() (line 6608 of /var/www/html/example/includes/common.inc).

```

I've double checked and the memberlist is the name ( machine name) of the profile2 I am trying to get populated.

# Answer
> 0 votes
I had this in my module:

```
unset($form['profile_memberlist']);

```

Which is what I needed to do so I could override and theme the way the form elements were presented. I commented that out but then I got a dual display of form elements, which I was able to disable with the follwing code:

```
$form['profile_memberlist'] = array(
      '#type' => 'hidden',
);

```

---
Tags: 7, forms, users
---


title: Drush database connection issue

text:
# Question
Title: Drush database connection issue
I am stuck with getting Drush to work properly on my development server. And I am pretty sure the main reason is linked to not being able to connect to my site database.

My setup is as following:

* Website: Drupal 7 (7.23) website running on my personal (Synology) NAS, that is in my LAN.
* PC OS: Windows8
* Drush: Used the Windows Installer (installed version: 5.8).

Drush got installed and is "partially" working, meaning: I can run some general Drush commands (e.g. drush status) and e.g. download modules. But e.g. enabling modules generates errors, I have less options for clearing cache, etcetera.

I know something is wrong with the Drush (configuration), as I get e.g. the following a warning message:

> PDO::\___construct(): \[2002\] No connection could be made because the target machine actively (trying to connect via tcp://127.0.0.1:3306) environment.inc 517

When I want to retrieve a status overview, I get the following:

```
    Z:\CMV-OpWeg>drush status
    PDO::__construct(): [2002] No connection could be made because the     [warning]
    target machine actively  (trying to connect via tcp://127.0.0.1:3306)
    environment.inc:517
     Drupal version         :  7.23
     Site URI               :  http://default
     Database driver        :  mysql
     Database hostname      :  127.0.0.1
     Database username      :  root
     Database name          :  cmv-opweg
     Default theme          :  garland
     Administration theme   :  garland
     PHP configuration      :  D:\System Utilities\Drush\Php\php.ini
     Drush version          :  5.8
     Drush configuration    :
     Drush alias files      :  C:\Users\BD/.drush/aliases.drushrc.php
     Drupal root            :  Z:/CMV-OpWeg
     Site path              :  sites/default
     File directory path    :  sites/default/files

```

And with some Drush commands the error:

> Drush was not able to start (bootstrap) the Drupal database.

From my preparations before getting Drush installed, I noticed in the above code that I am missing three distinct lines in my status overview that I do see referenced when doing some research:

```
     Database                :  Connected
     Drupal bootstrap        :  Successful
     Drupal user             :  Anonymous

```

This is the reason why I started this post with mentioning that I believe there is something wrong with the database connection. However, I do not understand this, as my Drupal site functions fine, which means that the settings in my "*settings.php*" must be okay.

One might think that these pointers should give ample leads to find a solution. I have gone through the chapter on Drush in "*The Definitive Guide to Drupal 7*" by Greg Anderson, and I can assure you that I have spend countless hours in the past weeks on getting Drush to work properly on my system by searching the internet high and low on anything I could find on Drush. And yes there are plenty of tutorials to find, plenty of posts from people that have issues that look like mine (but not exactly), but still I have not been able to get it to work, or I am just not seeing it.

What came up a lot is the advice to change the 'host' setting in my "*settings.php*" from "localhost" to "127.0.0.1.", which I did (as you can see from the status overview above). There were some references to specify the 'port' setting to "3306", which I also tested, but without success.

Now, I can not exclude the fact that perhaps my lack of knowledge and/or experience is a reason that I might be overseeing an obvious reason for my issue. I am fairly new at building sites (with Drupal), and in the past 6 months going through a pretty steep Drupal learning curve. I have read a couple of books on Drupal and started building a site without doing any coding. I came across Drush a couple of times, installed it a few months back, but could not get it to work, so left it as it was. Now I need to start theming my site and wanted to start using the Omega 3 subtheme that I created months back (but not yet really worked with). Now with the new Omega 4 theme out, it makes sense to skip Omega 3 and start with Omega 4. But in order to create a subtheme I need Drush to work, as there is no good documentation explaining the manual process (although I have asked for it). So as you can see, I am in need to get Drush working, which needs to happen anyway, as everything I read about it tells me that I really should start using it. So I could use the help of anybody "listening".

What I should mention also is the the fact that I guess it does not help that I am not an expert on linux, apache, php and working with the command line. From many of the internet posts that I have read I must conclude that I am missing a lot of background knowledge. But I am not giving up yet, and I am willing to learn. The appeal of what Drupal can do is big and most of the time I am enjoying the ride....

# Answer
From your comment:

> One thing I did not try yet is to use an alias containing connection parameters
> But that should not be necessary, as Drush should be able to read my settings.php file that contains that information already

Actually, it makes sense that Drush can't connect with the `settings.php` file in your case. Let's try to explain that.

You mentioned that `settings.php` contains `127.0.0.1` or `localhost` as the hostname of the MySQL server. This is a special address that means `myself` for every computer or device, including the NAS.

When the Drupal website runs on the NAS with its own webserver and connects to `127.0.0.1`, it connects to the MySQL server on the NAS.

On the other hand, when Drush runs on your PC and tries to connect to `127.0.0.1`, it designates the PC, so that connection fails with the mentioned error because MySQL is installed on the NAS, not the PC.

What makes your setup special is that you're installing Drush on a different machine (the PC) than the webserver (the NAS). Hence the suggestion to refer to Drupal as a remote installation from the point of view of the PC.

There's possibly an easier way, however, provided MySQL was configured to listen to the interface of the local network. If the NAS was at address, say `192.168.x.y`, on the local network, both the NAS itself and the PC could refer to this address via `settings.php`, and then it would work identically from the web server and from Drush.
> 1 votes

# Answer
Your database connection is dying/crippling because of low computing resources on your NAS, I would suggest using anyone of the following free cloud solution for dev work :

1. https://www.openshift.com/videos/openshift-express-getting-started-with-drupal
2. http://www.turnkeylinux.org/drupal7 (Use free tier from Amazon with one-click launch).
3. https://www.acquia.com/products-services/dev-desktop For Local devlopment on Windows

Both of the above come pre-installed with a complete drupal development env. including Drush.
> 0 votes

---
Tags: database, drush, configuration
---


title: Comments field displays only plain text

text:
# Question
Title: Comments field displays only plain text
I have a Drupal 7 site where people might want to put code snippets in a comment. I have the geshi module set up for syntax highlighting.

I have an article node set to the Full HTML text format, and some code snippets. The article is displayed properly, the code is highlighted.

I have created a comment on the article with the text format also set to Full HTML, and some code snippets. The comment displays the literal html code, as if the text format is plain text or something. I have BUEditor and Ajax markup installed, and the preview they give me shows it highlighted. But Drupal's preview is consistent with the real output.

I've tried googling for this problem, but between most people wanting the opposite and the term `comment` being on pretty much every webpage these days, I couldn't find anything.

# Answer
> 0 votes
I was doing the following:

```
    <csharp>line1
    line2
    line3</csharp>

```

Those extra 4 spaces in the beginning made Markdown put that in a `<pre>`, and then geshi still processed the csharp block. Taking out the spaces in the beginning made it work correctly.

---
Tags: 7, comments
---


title: Hide Views with custom module

text:
# Question
Title: Hide Views with custom module
Hi I would like to create a custom module where I can do extra checks on a view and if those checks are not pass deny access. I'm not sure what hook to implement to achieve this.

# Answer
You need to implement two Views hooks: hook\_views\_api() and hook\_views\_plugins(). Have a look at `views_views_plugins()` in Views' `/includes/plugins.inc` file for an example implementation of the plugin hook; specifically, look at the plugins in the `'access'` key.

Beyond that, look at the `views_plugin_access*` files in `/plugins/` for examples of actual implementations.
> 0 votes

---
Tags: views, 7
---


title: Re-using / Customizing content types

text:
# Question
Title: Re-using / Customizing content types
I have constructed a content type, 3 fields are timestamps.

I wish to reuse this content type (form input etc) to a client facing application, with the caveat being the form is modified. For example my module should be able to tweak the form (ie: Hiding the timestamps fields and updating them accordingly).

I don't want to rebuild the whole form and muck with the CCK API to get data to persist, so I am wondering if it is possible to simply re-call that form and it's functionality and tweak it ever so slightly???

I found this googleing:

//Showing a node edit page with drupal\_get\_form() and hook\_menu()

And implemented some of it:

```
function _tasks_create() {
  module_load_include('inc', 'node', 'node.task');

  $nid = '1';
  $node = node_load($nid);

  return drupal_get_form('task_node_form', $node);
}

function tasks_menu() {
  $items = array();

  $items['tasks/create'] = array (
    'type' => MENU_CALLBACK,
    'title' => t('Create New Task'),

    'page callback' => '_tasks_create',
    // Where is $node coming from???
    'page arguments' => array('task_node_form', $node),

    'access arguments' => array('create tasks')
  );

  return $items;
}

```

But I see two immediate issues:

1. $node in hook\_menu is undefined -- where do I get it from??
2. I have no idea what the $nid (Node ID) will ever be for my content type

I need to essentially re-display the form that I use in the admin, hiding everything but maybe three fields (that means no URI, menu options, etc).

I will probably need to hook into the submission of the form in this context only and update the timestamps accordingly.

What am I missing or doing wrong? Any ideas?

Alex

# Answer
Clive's answer is right.. You can not pass $node object before you created yet. If you want to show the same form which is shown in the /admin section you can do something like this:

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

  $items['tasks/create'] = array (
    'type' => MENU_CALLBACK,
    'title' => t('Create New Task'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('task_node_form'),
    'access arguments' => array('create tasks')
  );

  return $items;
}

```

and:

```
function task_node_form($form, &$form_state) {
  $form = array();
  $node = new stdClass();
  $node->type = 'YOUR TYPE';

  field_attach_form('node', $node, &$form, &$form_state, $langcode = NULL, $options = array())

  // Other code
}

```
> 0 votes

---
Tags: hooks, nodes
---


# Question
Title: Multisite Installation (Attempt) Goes To My Main Site
I am attempting to perform a multisite installation. My main (presently working) site is located in a subdirectory called "beta" of my ~/public\_html folder. This is the site for jackstahlco.com and it is working. I also want to have this installation of Drupal run two other sites.

The first other site I am trying to get to work is meadowlarknm.com. This site is presently resolving to jackstahlco.com, which is NOT correct. I created ~/public\_html/beta/sites/meadowlarknm.com/ and ~/public\_html/beta/sites/meadowlarknm.com/files. I copied default.settings.php into meadowlardnm.com/ and changed the permissions, as well as creating a 'files' directory. The settings.php also contains

```
$databases = array ();

```

and no other database configuration.

When I navigate to www.meadowlarknm.com, I just see the www.jackstahlco.com website, instead of the Drupal installation screen that I expect. You can go there to see what I'm talking about, unless I fix this problem immediately after writing this question.

I am suspecting that this may be a .htaccess issue, but I am not sure. It's a little bit weird that I am trying to run multi-site from a subdirectory, but it seems like this should be possible (if my understanding was complete.)

Here is my .htaccess (inside ~/public\_html, I did NOT change the .htaccess inside ~/public\_html/beta):

```
########## End - Rewrite rules to block out some common exploits

#  Uncomment following line if your webserver's URL
#  is not directly related to physical file paths.
#  Update Your Joomla! Directory (just / for root)

# RewriteBase /

RewriteCond %{HTTP_HOST} !^www\.jackstahlco\.com$ [NC]
RewriteRule .* http://www.jackstahlco.com/      [L,R=301]
RewriteRule ^$ beta/index.php   [L]
RewriteCond %{DOCUMENT_ROOT}/beta%{REQUEST_URI} -f
RewriteRule .* beta/$0 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* beta/index.php?q=$0 [QSA]
#
#RewriteCond %{HTTP_HOST} ^(www.)?jackstahlco.com$ [NC]
#RewriteRule ^(/)?$ /beta/$1 [L]

RewriteCond %{HTTP_HOST} ^(www.)?jackstahlcompany.com/puertadelsolsite$
RewriteRule ^(/)?$ puertadelsolsite [L]

RewriteCond %{HTTP_HOST} ^meadowlarknm\.com$ [NC]
RewriteRule ^(.*)$ http://www.meadowlarknm.com/$1 [L,R=301]

########## Begin - Joomla! core SEF Section
#
#RewriteCond %{REQUEST_FILENAME} !-f
#RewriteCond %{REQUEST_FILENAME} !-d
#RewriteCond %{REQUEST_URI} !^/index.php
#RewriteCond %{REQUEST_URI} (/|\.php|\.html|\.htm|\.feed|\.pdf|\.raw|/[^.]*)$  [NC]
#RewriteRule (.*) index.php
#RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
#
########## End - Joomla! core SEF Section
<IfModule mod_suphp.c>
 suPHP_ConfigPath /home/jsco
 <Files php.ini>
   order allow,deny
   deny from all
 </Files>
</IfModule>

```

Additionally, the following is in /home/jsco/public\_html/beta/sites/sites.php:

```
  $sites = array(
   'www.jackstahlco.com' => 'default',
   'www.meadowlarknm.com' => 'meadowlarknm.com',
  );

```

The end goal here is to re-do the existing sites on this server (some Joomla! as you may have guessed from the .htaccess) to a single Drupal system running multisite.

I don't believe this is a DNS issue. nslookup says these are all going to the correct place, and my domain-to-folder mapping on cPanel (sending everything to ~/public\_html) looks OK.

Additionally, the multisite wizard says MOST of my steps are OK.

```
OK Create sites/sites.php file
OK Fill up sites/sites.php file with domain-folder array
OK Create sites folders inside sites/ folder
OK Each site folder should have own settings.php file
NOT OK - Prefix inside each settings.php file should be unique. I think I want a different DB

```

Thank you very much for the help.

-Brian J. Stinar-

# Answer
Indeed this is not a DNS issue, the problem here is your `sites` directory is located in the wrong directory. It shouldn't be under `all` but in the root of `sites`. In your case it should be:

```
sites/jackstahlco.com/settings.php
sites/jackstahlco.com/files
sites/meadowlarknm.com/settings.php
sites/meadowlarknm.com/files

```

If you want the Drupal installation process popping up, you need to put an empty array connection info in the settings.php of the desired website.

```
$databases = array ();

```

The `sites.php` should be like this:

```
$sites = array(
    'jackstahlco.com' => 'default',
    'meadowlarknm.com' => 'meadowlarknm.com',
);

```

You don't need to specify the `www` prefix.
> 3 votes

---
Tags: multi-sites, .htaccess
---


title: How to align teaser images?

text:
# Question
Title: How to align teaser images?
Is it possible to align (left or right) teaser images that are uploaded through Imagefield in Drupal 7? Is there a clean solution whithout hacking into drupal code?

# Answer
You should use CSS to style your content. This happens in the theme of your site. The handbook on Drupal.org has a lot of documentation on how this is done.
> 1 votes

# Answer
The simplest way(If you did not "hack" any theme template files.):

```
.node-teaser .field-item img {
  float: left;
  margin-right: 10px;
}

```

(You can change float\[left/right\] and margin-right/left values as you need.)
> 1 votes

# Answer
You might want to try Display Suite or even better Fences to assign CSS class to your teaser image or its container and then style that selector in CSS. Class assignment will be done on admin UI side, so the only code invloved will be CSS added to your theme.
> 0 votes

---
Tags: media, nodes
---


# Question
Title: how to use css sprite in all my pages ( menu+ views)
i have a page contain view and menu and i want to use same icon for both, so i made a sprite image but i don't know how to use it in 2 different classes?

Any help with this would be much appreciated.

Cheers in advance.

# Answer
You can use same image in different classes already; i am not sure that i understood your problem(I was going to ask for details but my reputation is not enough to add comments yet; so i am adding answer.).

```
.class-one {
  background: url("/your/path/to/images/your-sprite-image.png") no-repeat 0 0;
  ...
}

.class-two {
  background: url("/your/path/to/images/your-sprite-image.png") no-repeat 0 0;
  ...
}

```

If you need to change image's position, you can change first 0 for left, second 0 for top position.

If they are the same; you can merge them:

```
.class-one, .class-two {
  background: url("/your/path/to/images/your-sprite-image.png") no-repeat 0 0;
  ...
}

```
> 0 votes

---
Tags: theming
---


# Question
Title: How to validate if node is ubercart product?
Im sure this is something simple, but I would really appreciate some help with it. How to check by php if the node is an ubercart product? Empty sku field might work but how can it be accessed ?

# Answer
I think the most solid way to test would be to check that the node's type is one that the uc\_product module considers to be a product node type. You can do that by using the `uc_product_types()` function:

```
$node_types = array_keys(uc_product_types());
if (in_array($node->type, $node_types)) {
  // The node is a product
}

```
> 3 votes

# Answer
Not really. The most solid way is to use the function Ubercart provides for just this purpose: uc\_product\_is\_product().
> 1 votes

---
Tags: 7, ubercart
---


# Question
Title: How to highlight location on an OpenLayers view
I have a view of locations displayed with OpenLayers. The map, with plot points, is displayed in a left column, and rows of the locations are displayed in a right column. When a user clicks on one of the locations, I want that row to highlight, and to highlight the plot point to the left. I also want to record that location ID in the user object as a location preference.

Can I simply do this with AJAX?

# Answer
OpenLayers Heatmaps module allows you to create Heatmaps layers through the Openlayers module and it don't have the views integration, but you can highlight the specified location like the below one and honestly I'm not using this before.

Features

> * Provides a new kind of behavior in the OpenLayers's maps settings.
> * customize the radius, intensity and opacity of each Heatmaps.
> 1 votes

---
Tags: views, javascript
---


title: tpl.php files in a module directory

text:
# Question
Title: tpl.php files in a module directory
I am trying to have one tpl file per view mode inside a module folder. But I can't get drupal to pick up the right tpl file.

I have been trying solutions on these pages:

http://www.metachunk.com/blog/adding-module-path-drupal-7-theme-registry

```
/**
 * Implements hook_theme_registry_alter()
 **/
function nwd_press_room_theme_registry_alter(&$theme_registry) {
    global $theme_key;
    $mod_path = drupal_get_path('module', 'nwd_press_room');
    $theme_registry_copy = $theme_registry;       // munge on a copy
    _theme_process_registry($theme_registry_copy, 'phptemplate', 'theme_engine', $theme_key, $mod_path);
    $theme_registry += array_diff_key($theme_registry_copy, $theme_registry);
    $hooks = array('node');

    foreach ($hooks as $h) {
        if (!isset($theme_registry[$h]['theme paths'])) {
                $theme_registry[$h]['theme paths'] = array();
        }
        nwd_press_room_insert_after_first_element($theme_registry[$h]['theme paths'], $mod_path);
    }

    dpm($theme_registry);

}

/**
 * Helper function for re-ordering arrays (needed by theme_registry_alter)
 */
function nwd_press_room_insert_after_first_element(&$a, $element) {

    if(is_array($a)) {
        $first_element = array_shift($a);
        if ($first_element) {
            array_unshift($a, $first_element, $element);
        } else {
            array_unshift($a, $element);
        }
    }
}

```

Since I still want the tpl file to be overridable in the theme. Does anyone have an example that works?

# Answer
> 1 votes
I created this module a while back. Could be useful here: https://drupal.org/project/view\_mode\_templates

How to use:

Download and install view\_mode\_templates module. In your custom module, implement the following hook which returns a list of templates you want to override:

```
/**
 * Implements hook_view_mode_templates().
 */
 function MODULE_view_mode_templates() {
  return array(
    'node_article',
    'node__article__teaser',
    'node__article__full',
    'taxonomy_term__tags__full',
  );
 }

```

Then you create your template in a templates directory. Eg. templates/node--article--teaser.tpl.php.

It works with any entity: nodes, users, field\_collection..etc.

# Answer
> 2 votes
Found the solution after extensive search and trial & error:

```
/**
 * Define the new view modes
 *
 * implements hook_entity_info_alter()
 * @param $entity_info
 */
function my_module_entity_info_alter(&$entity_info) {

    $entity_info['node']['view modes']['grid'] = array(
        'label' => t('Grid'),
        'custom settings' => TRUE,
    );

    $entity_info['node']['view modes']['list'] = array(
        'label' => t('List'),
        'custom settings' => TRUE,
    );
}

/**
 * Tell Drupal to also look for template files in the modules folder
 *
 * implements hook_theme_registry_alter
 *
 * @param $theme_registry
 */
function my_module_theme_registry_alter(&$theme_registry) {

    $path  = drupal_get_path('module', 'my_module');
    $theme_registry += drupal_find_theme_templates($theme_registry, '.tpl.php', $path);
}

/*
 * Implements template_preprocess_node().
 */
function my_module_preprocess_node(&$variables){

    // Add the theme hook suggestion to include view mode
    $variables['theme_hook_suggestions'][] = 'node__'.$variables['type'].'__'.$variables['view_mode'];

  }
}

```

---
Tags: 7, theming
---


# Question
Title: Rules - show information after certain time
I'm wondering how can I achieve this. I have built a page, on which the content of certain type was being unpublished after 2 weeks. I created rule for that (component + component schedule) and it worked without problem.

But now I have to change the behavior - instead of old content being just "removed from sight of users", it has to remain visible but display a message. Something in the line of "this content has expired, but you can check for available offers on the main page".

I thought that setting the rule and picking up the "display message on site" could be what I'm looking for, but seems like I was wrong. No idea if I can do it in Views (how to link specific Rule to it?), so I'm looking for help.

Any ideas how to achieve that message displaying to users after certain time has passed?

# Answer
If you want to achieve it with rules, you can do it with the following steps:

1. Add new rule
2. React on event: Content is viewed (under Node section)
3. Add new condition: Data comparison
4. Data to compare: `node:created`
5. Operator: 'is lower than'
6. Data value: Switch to the direct input mode and put '-2 weeks', or '-14 days'
7. Add new action: 'Show a message on the site' (under System section)
8. Put your message in as value, and select the type of the message. E.g. 'Status'
> 0 votes

---
Tags: 7, rules
---


# Question
Title: Add PayPal WPS payment payload information to Commerce admin e-mail
I'm using Commerce with the Commerce E-mail module to customize the e-mail sent to admins whenever there is an order (a payment is received) at the store. Payment is handled using PayPal WPS through the Commerce PayPal module.

On my site, buyers must input their e-mail addresses before moving on to PayPal, but these e-mail addresses (on my site) sometimes differ from the e-mail addresses registered on buyers' PayPal accounts.

For this reason, **I want the admin e-mail (sent when an order is paid for) to include both the e-mail address that the buyer input on my Drupal site as well as their PayPal e-mail address.**

Commerce E-mail provides a `[commerce-email:order-items]` token, but there is no token for the PayPal WPS information. This information is stored within Drupal; in the Order Admin UI, if you click on the payment details of the transaction, under **Payload** there is a printout of an Array that includes `[payer_email] => thepayeremail@example.com`.

**Payload array:**

```
Array (
    [13775355555-ipn] => Array
        (
            [mc_gross] => 17.00
            [invoice] => 555-1377531555
            [protection_eligibility] => Eligible
            [payer_email] => thepayeremail@example.com

```

How can I add the buyer's PayPal registered e-mail address (`[payer_email]`) into the admin e-mail sent by Commerce? It would be great if the solution would also allow use of other information in the payload array, such as the buyer's physical address.

# Answer
> 1 votes
You can extract those array and add them data object. After adding them to the token replace function you can use that to create custom tokens which will help you to get the tokens. That custom tokens can now be used to get the buyer's email address

```
// Write a code for porting data to token_replace()
$data = new val();
$data->mc_gross = variable_get('mc_gross', '');
$data->invoice = variable_get('invoice', '');
$data->protection_eligibility = variable_get('protection_eligibility', '');
$data->invoice = variable_get('payer_email', '');
token_replace(['payload']', (array) $data);

```

--------write this in module\_name.tokens.inc file------------------------------------------

```
 function hook_token_info() {
      $info = array();

      // Add any new tokens.
      $info['tokens']['payload']['mc_gross'] = t('Gross');
      $info['tokens']['payload']['invoice'] = t('Invoice');
      $info['tokens']['payload']['protection_eligibility'] = t('Protection Eligibility');
      $info['tokens']['payload']['payer_email'] = t('Email');
      // Return them.
      return $info;
    }

    function hook_tokens($type, $tokens, array $data = array(), array $options = array()) {
     $replacements = array();

    if ($type == 'payload') {
    foreach ($tokens as $name => $original) {
          switch ($name) {
            case 'mc_gross':
              $replacements[$original] = $data['mc_gross'] ;
              break;
            case 'invoice':
              $replacements[$original] = $data['invoice'];
              break;
            case 'protection_eligibility':
              $replacements[$original] =  $data['protection_eligibility'];
              break;
            case 'payer_email':
              $replacements[$original] = $data['payer_email'];
              break;
          }
        }
      }

      return $replacements;
    }

```

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


# Question
Title: Unable to add a submit button to a drupal Block
I am adding a submit button (in the callback function 'clearbutton\_submit()') - when I click on the button - nothing happens.

What am I doing wrong here?

```
function cacheclearbutton_block_info() {

$blocks['cacheclearbutton_uppercase'] = array(
// info: The name of the block.
'info' => t('CacheClear Button Block'),
'region' => 'sidebar_first',
'status' => 1,
);

return $blocks;
}

/**
* Implements hook_block_view().
*
* This hook generates the contents of the blocks themselves.
*/
function cacheclearbutton_block_view($delta = '') {
//The $delta parameter tells us which block is being requested.
switch ($delta) {
case 'cacheclearbutton_uppercase':
  $block['subject'] = t("uppercase this please");
  $block['content'] = block_content();
}
return $block;
}

function block_content() {

$block_contents = array();

$block_contents['clearbutton'] = array(
    '#type'         => 'button',
    '#value'        => 'Clear Cache by Module',
    '#submit'       => array('clearbutton_submit'),
);

return $block_contents;
}

function clearbutton_submit($form, &$form_state) {
    cache_clear_all();
    drupal_set_message(t('Setting a message from the submit handler'));
}

```

# Answer
A small change needed as below

> * Key was to chnage the type from button to submit
> * But I guess making a separate function to get the form will be better

```
function block_content() {

  //calling the form in the block
  $block_contents = drupal_get_form('_cacheclearbutton_clear_cache_form');

  return $block_contents;
}

// A separate function to return the form to clear the cache
function _cacheclearbutton_clear_cache_form() {
  $form = array();
  $form['clearbutton'] = array(
    '#type' => 'submit',
    '#value' => 'Clear Cache by Module Test',
    '#submit' => array('clearbutton_submit'),
  );
  return $form;
}

function clearbutton_submit($form, &$form_state) {
  cache_clear_all();
  drupal_set_message(t('Setting a message from the submit handler'));
}

```
> 1 votes

---
Tags: 7, blocks, forms
---


title: My breadcrumbs are skipping a level

text:
# Question
Title: My breadcrumbs are skipping a level
I've got a Main Menu and am using Superfish, not sure if this makes any difference.

But in the breadcrumbs the top level of the main menu is being skipped. Eg.

Instead of

Home - A - B

My breadcrumb looks like:

Home - B

B, being the page I am currently on.

What am I doing wrong?

# Answer
> 2 votes
Drupal core breadcrumbs can be flaky at times.

You may be interested in

1. Menu Position ( contrib module )
2. Custom Breadcrumbs ( contrib module )
3. hook\_preprocess\_breadcrumb ( theme preprocess function, set `$variables['breadcrumb']` )
4. theme\_breadcrumb ( theme function )

Using one or more of those methods, you can control breadcrumb behaviour.

# Answer
> 1 votes
You can use Easy Breadcrumb

> Easy Breadcrumb uses the current URL (path alias) and the current page's title to automatically extract the breadcrumb's segments and its respective links. Easy Breadcrumb is really a plug and play module, it auto-generates the breadcrumb by using the current URL, the user needs to do anything to get it working.

# Answer
> 0 votes
This module, Menu BreadCrumb, allows you to disable menus and re-order the weight in which they are used to create your breadcrumb trail. A very simple solution if you are using more than one menu containing the menu item on the same page. Although, if you are using multilingual menu modules you might have to apply this patch

---
Tags: routes
---


# Question
Title: Override autocomplete provided by module to not suggest current user(self)
I hope it's pretty clear from my question title itself. I want to override autocomplete provided by module such as privatemessage to not suggest the current user(self) who is trying to send message. I tried doing some research about it but all I got was about overriding JS file.

I have used automcomplete with my custom form long ago & when I prepared the JSON, I removed current user from the list. But what to do if I have to do the same for some contributed module ?

# Answer
This is the working code

> * Add this to your custom module
> * Replace MYMODULENAME with your custom module name

```
function MYMODULENAME_query_privatemsg_autocomplete_alter($query) {
  global $user;
  $query->condition('u.uid', $user->uid, '<>');
}

```
> 1 votes

# Answer
If you look at the code in Privatemsg module, the autocomplete callback function provides a hook hook\_privatemsg\_autocomplete\_alter(). You can use this hook and unset the current logged in user from the `$matches` array.

I don't have Privatemsg module installed in any of my current projects, so I cannot test it, but the following code should do it:

```
function YOURMODULE_privatemsg_autocomplete_alter(&$matches, $names, $fragment) {
  global $user;
  unset($matches[$user->uid]);
}

```
> 2 votes

---
Tags: 7, ajax, privatemsg
---


title: Closing MySql Connection in Drupal7

text:
# Question
Title: Closing MySql Connection in Drupal7
How can I explicitly close a MySql Connection in Drupal 7? I have a requirement of inserting back to rows to a DB table in Drupal.. I tried using `db_insert`/`db_update` and `db_query`.. In both cases I got the error Max number of SQL connections reached.. I am speculating that Drupal is maintaining these connections one per query and not closing them.. Hence I need to know if there is any way I can do it explicitly.

# Answer
> 2 votes
The specific function you are looking for in the database abstraction API is db\_close() but you may be able to solve your problem through another route by increasing your max connections.

See this earlier thread on drupal.stackexchange for guidance on increasing max\_connections. You might also be having a problem with slow / stalled queries that are trying up limited query slots, this thread offers advice on how to debug.

---
Tags: 7, database
---


# Question
Title: Multigroup (CCK3) / FlexiField-like solution for compound fields?
I've used FlexiField in the past to do multiply occurring series of field groups; now, working on a Drupal 7 project, I'm setting up a "Resume" content type and need a way to set up repetitive entries for education/work experience.

IE: for "Education", I need the ability to dynamically add new rows comprised of a combination of dates and places for each institution studied at.

**What is the best way to accomplish CCK3 multigroup/FlexiField-like functionality in Drupal 7?**

Thanks!

# Answer
> 3 votes
For the moment, I'm implementing this via Field collection. Granted, that is still very early development.

If somebody could provide a list of solutions in the "group content fields together and allow an infinite number of these groups via the 'add another' button", I'll accept that as my answer. I may have to upgrade my FlexiField project to D7 at some point and there's currently no clear upgrade path with that module.

# Answer
> 3 votes
Assuming you are using Drupal 6, there is a submodule called multigroup that allows you to group multiple fields together (creates the relationship) and gives you the ability to add unlimited values of each group.

If you are doing this in D7, you can use the Field Collection module, which does the same thing.

# Answer
> 0 votes
There is also a Composed Field module. The main difference is that it saves each collection of fields as a field, where as Field Collection module saves each collection of fields as an entity (node). Although it's an awesome module, Composed Field is currently in pre-beta, so you might want to stick with Field Collection for now.

# Answer
> 0 votes
One thing to keep in mind on this is if you are using Field Collections then you need to make sure to set the value of "Number of values" to more than one (1) if you want the field collection to repeat.

I banged my head on that for a little while before realizing the obvious when I was trying to alter an existing field collection in Profile2 (Recruiter distro).

# Answer
> 0 votes
New answer to an old question (but isn't that how Drupal usually works): you might want to try the Multifield module as an alternative to Field Collection or the other solutions posted here. It's meant for this type of problem.

---
Tags: 7, nodes
---


title: How to add descriptions to quicktabs

text:
# Question
Title: How to add descriptions to quicktabs
I would like to know I can add descriptions to quicktabs. Ideally, every tab would have it's own description that gets displayed.

Thanks

# Answer
> 1 votes
You can render quicktabs programmatically and where title field, you can add your descriptions. Here is link to manual: Creating QuickTabs programmatically not working

# Answer
> 0 votes
There is a patch for 6.x version which adds a description functionality to Quicktabs module.

> 1. Admin area has 2 new option for every tab:
>     * Description Text
>     * Description Type: Tip or Text
> 2. Front area has default styling for both
>     * Tip - simple hoverIn-hoverOut box with default styling.
>     * Text - simple text displayed below the tab title with default styling.

It is not a big patch, with some effort you can take the idea and apply it for the 7.x version.

---
Tags: blocks
---


# Question
Title: How do I hide specific node fields to users not registerd to that specific node?
I am building a site with a course content type. Users can only view some of the course details (such as date, location and description) unless they are registered on the course. Once registered their is certain webforms and file downloads related to the course which they can access too.

A company admin user (sponsor) should be able to access specific courses, and if they have access to a course they can invite people (delegates) to register on the course. Basically each individual course is by invite only.

I'm a little confused as to how to build this. I assume Organic Groups, and/or Entity Registration may be the right direction, but I've never actually used either Module. Does anybody have any suggestions on how I can build this? Which Modules should I use and does anybody have any tutorials or references which may help in this specific area?

# Answer
> 2 votes
You need to use Field Permissions module, with the help of this module you can do your stuff. Which allows site administrators to set field-level permissions to edit, view and create fields on any entity. With this module you can hide the certain node field to anonymous user.

> * Enable field permissions on any entity, not just nodes.
> * Role-based field permissions allowing different viewing patterned based on what access the user has.
> * Author-level permissions allow viewing and editing of fields based on who the entity owner is.
> * Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed.

# Answer
> 1 votes
Bala's answer is right. Field Permission module is the right module to use. But if you do not want to use contrib module or did not understand how to use it, you can do such kind of functionality by overriding default node template.. Copy node.tpl.php file to your theme folder and rename it like node--NAMEOFYOURCONTENTTYPE.tpl.php. And write such kind of thing, for ex. :

```
<div>
    // Authenticated user can see
    <?php if(user_is_logged_in():): ?>
    <div class="bodyField">
    <?php print render($content['body']); ?>
    </div>
    <?php endif; ?>

    // Everyone can see
    <div class="anotherField">
    <?php print render($content['field_FIELDNAME']); ?>
    </div>

    // Authenticated user can see
    <?php if(user_is_logged_in()): ?>
    <div class="anotherField">
    <?php print render($content['field_FIELDNAME']); ?>
    </div>
    <?php endif; ?>
</div>

```

---
Tags: users
---


# Question
Title: How to change field setting using on some condition based?
I want to change image property like resolution based on other field.Like I have a field that tells how the image will be shown. If I select a large image then minimum image resolution have to change higher.

There is no option to do it with conditional field. So Is there any other way?

# Answer
> 0 votes
Checked my condition pragmatically in `hook_node_validate` function.

# Answer
> 1 votes
It looks like you are looking for Formatter Field:

> The formatter field module provides a mechanism for specifying a formatter and formatter settings to be used for displaying a field, on a per-entity basis. By default, Drupal provides formatters and settings per entity bundle, but in certain situations it is necessary to choose the formatter at the entity level.
>
> For example, say you have a page **node with an image field**. Normally, you would select an image style as the formatter, and all page nodes would use that same image style. With this module, you can add a formatter field to page nodes, which is hooked up to the image field. **Then when the node is created or edited, the image style can be selected per-node**.

Emphasis mine.

---
Tags: 7, entities
---


# Question
Title: How to stop animation and turn off the delay time in superfish menu?
I created a superfish menu block and set the animation speed at fast and delay time to 0. Still it taking time to open the child menus. I disabled the animation using this article but still it taking time to open the menu. I want to open the child menu just when user hover on the parent menu.

# Answer
> 0 votes
Adding custom js did the trick.

```
jQuery(document).ready(function() {
    jQuery('ul.sf-menu').superfish({
       delay: 0,
       autoArrows: false,
       speed: 'fast',
       disableHI: true
    });
});

```

---
Tags: 7, navigation
---


# Question
Title: How to get number of results from MySQL query without getting all result data?
For a Google Maps application, I built an AJAX call that dynamically checks whether there are markers in a given viewport range. All marker information is stored in a node (note that I am using projective coordinates x, y instead of lat,lng) and the text in the body field also matches a condition. The MySQL query is as follows:

```
var $text = 'Test';
$query = db_select('field_data_body', 'b');
$query->join('field_data_field_x', 'x', 'b.entity_id = x.entity_id');
$query
  ->fields('b', array('entity_id'))
  ->fields('x', array('field_x_value'))
$query->where('b.body_value LIKE :text', array(':text' => $text));
$query->where('x.field_x_value >= :num1', array(':num2' => $xmin));
$query->where('x.field_x_value <= :num2', array(':num2' => $xmax));
$result = $query->execute();
if ($result->rowCount() < $maximum) {
 process_data($row->entity_id, $row->field_x_value);
}

```

Now, whenever the amount of markers exceeds a number $maximum, a clustering mechamism sets in. For this purpose, I really need to

1) check if there a less than $maximum results,

and **only in this case**

2) pull that data and process it.

Since quite many markers are stored in my database, my MySQL query should be as slim as possible, **ideally it would first only give me the number of results** (similar to a COUNT\* query) and **pull the result data only if needed**.

Can anybody advice me on whether my $query-\>execute()-\>rowCount() code does that job? Or does $query-\>execute() automatically pull all results, and rowCount() is a PHP counting routine? The $result object does not seem to contain the explicit data, therefore it seems plausible to me that the data might not have been pulled yet at that stage...

Thanks for your help!

# Answer
MySQL has no mechanism like that; you'll need to run two queries, the first a count query, and the second for the data if your condition on the first query result passes.

The PDO `rowCount()` method isn't used for `SELECT` queries, just `DELETE`, `INSERT` and `UPDATE` queries.

You'll need the `countQuery()` method to determine the count with a separate query, then simply run the original query if the count query gives the right result
> 0 votes

---
Tags: ajax, database
---


# Question
Title: First attempt to adding states to a custom Content type
```
// sample code
/**
 * Implementation of hook_form_FORM_ID_alter()
 */
function demo_form_sport_node_form_alter(&$form, &$form_state, $form_id) {
    $form['field_winter_sports'] = array(
    '#states' => array(
        'visible' => array(   // action to take.
            ':input[name=field_season]' => array('value' => t('winter')),
        ),
    ),
);

```

}

i am trying to alter a form from a "sport" node type. my "sport" node type has 2 fields.

1. field\_season List (text) Check boxes/radio buttons
2. field\_winter\_sports List (text) Check boxes/radio buttons

there are two options in field\_season, summer or winter.

if someone selects winter in field\_season, i want to make field\_winter\_sports visible, otherwise remain hidden.

with my current code, when i select winter right now, nothing happens.

# Answer
There are two things to consider:

* The name of the input element is visible in the HTML output of the page, and that could not match with the ID used for that form element from the form API. That happens with form elements created with the field API too.
I created a `field_season` field, which allows just a value to be select (which means it is rendered with radio buttons); the input element name that appears in the HTML output, which is the one jQuery sees, is `field_season[und]`, not `field_season`.

If I change the field to allow three choices (which means the form field is rendered as checkboxes), the input element name changes to `field_season[und][1]`, `field_season[und][2]`, and `field_season[und][3]`.

* When you want to tell to Drupal to alter the state of a form element when a radio buttons are used, you should not use `t()`, and the string to use as value in the state is not the string that appears to the users, but the value assigned to the value attribute of the `<input type="radio">` tag. For example, for the form element added from the following code, those values are 0, 1, and 2.

```
$form['registration_cancellation']['user_register'] = array(
  '#type' => 'radios',
  '#title' => t('Who can register accounts?'),
  '#default_value' => variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL),
  '#options' => array(
    USER_REGISTER_ADMINISTRATORS_ONLY => t('Administrators only'),
    USER_REGISTER_VISITORS => t('Visitors'),
    USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL => t('Visitors, but administrator approval is required'),
  ),
);

```

Since the input element name contains und, which is the string value for the `LANGUAGE_NONE` constant, I suspect the input element name could change basing on the language associated with the field, even if I suspect it would always be und, for radio buttons and checkboxes.

As side note, learningxm is correct when it says that you should use \`:input\[name=""\]' since that is what the example in the drupal\_process\_states() page shows.

```
$form['toggle_me'] = array(
  '#type' => 'checkbox',
  '#title' => t('Tick this box to type'),
);
$form['settings'] = array(
  '#type' => 'textfield',
  '#states' => array(
    // Only show this field when the 'toggle_me' checkbox is enabled.
    'visible' => array(
      ':input[name="toggle_me"]' => array('checked' => TRUE),
    ),
  ),
);

```

As noted by Clive, you are overriding the form element added using the field API; to change the states associated with the form element, you should just use the following code.

```
$form['field_winter_sports']['#states'] = array(/** Add here your states. **/);

```

I assume `field_winter_sports` is the correct form element ID.

I would also investigate using hook\_field\_widget\_form\_alter(), which is the hook thought to alter the form elements used for a field.
> 2 votes

# Answer
change `':input[name=field_season]' => array('value' => t('winter')),`

add commas `""` to `field_season` like this:

```
':input[name="field_season"]' => array('value' => t('winter')),

```
> -2 votes

---
Tags: entities
---


title: Breadcrumbs Not Displaying Properly

text:
# Question
Title: Breadcrumbs Not Displaying Properly
I am experiencing problems with breadcrumb trails inconsistently not displaying correctly. I am using the core breadcrumb module, without any others installed. (I did have Custom Breadcrumbs installed but have since uninstalled and removed it.)

I have links to nodes nested in parent items in the main menu like this: Home \> Chapter \> Topic \> Subtopic. Most nodes are displaying the breadcrumbs like that, which is what I want. However, a few are displaying like this: Home \> Subtopic (not showing the chapter and topic under which they are listed)

I believe I started getting this error when I changed the numerical weight of the menu items in structure \> menu. I have since changed their depth, changed their parent menu item, flushed caches, nothing has worked. It is only a few nodes with the problem and they were originally working as expected. I cannot recreate this problem either. If I create new nodes they show the proper breadcrumb trail. The items in question are all as they should be in weight and parent menu item position they should be. If I install Custom Breadcrumbs I can force the breadcrumb trail to the desired state. Is there a table that I can flush in the database that will fix this problem? Is there a way to fix this without deleting the node and recreating it?

**Edit:** I found the problem. I have links to these nodes in two different menus on the same page. Drupal is using the other menu I created instead of the Main-Menu to make the breadcrumb trail.

# Answer
The problem is having multiple menus with the node's links on the node's page at the same time. Instead of using the main-menu, Drupal is using the other menu you have created, which has no parent-items. You need to override it's default function.

1. Install Menu Breadcrumb
2. Go to admin/config/user-interface/menu-breadcrumb
3. Re-order the list to reflect the priority in which you want to be used for the breadcrumb trail
AND/OR
Deselect the menus you do not want to use for the Breadcrumb trail
> 0 votes

# Answer
It looks you need to fix the breadcrumbs for a particular contentHere is my idea.

> * In your theme, in template.php implement theme\_breadcrumns(), as below
> * Inside the theme\_breadcrumbs() implementation check type of node using

menu\_get\_object()

```
function YOURTHEMENAME_breadcrumb($variables) {
  $breadcrumb = $variables['breadcrumb'];

// Lets assume your content type name is chapter
  $node = menu_get_object();
  $node_type = $node->type;
  if($store == "chapter") {
     $links[0] =  l(t('Home'), '<front>');
     $links[1] =  t('Chapter');
     $links[2] =  t('Topic');
     $links[3] =  t($node->title); // Considering Sub topic as node title
     drupal_set_breadcrumb($links);
  }

```
> 1 votes

---
Tags: 7, breadcrumbs
---


title: How to use db API addExpression

text:
# Question
Title: How to use db API addExpression
I am trying to find a way of creating a view of both a custom entity type and a node. I was following this as a guide: https://drupal.org/node/748844 (see the way end for the D7 implementation, I have quoted it below, but for some reason, its not fully displaying...)

I am trying to understand this line

```
$query2->addExpression(':the_group_type', 'Type', array(':the_group_type' => 'Group'));

```

I see from online documentation that addExpression adds an expression to a list of fields, which I would assume means something like SUM(quantity). But I don't understand what the addExpression lines (there are actually two of them) are doing in this code.

Code listed below:

```
/**
 * Implements hook_views_pre_execute()
 */
function YOUR_MODULE_NAME_views_pre_execute(&$view){
    if($view->name == 'YOUR_VIEW_NAME'){
    //extracts my nodes
    $query2 = db_select('node', 'node');
    $query2->leftJoin('location_instance', 'location_instance', 'node.vid = location_instance.vid');
    $query2->leftJoin('location', 'location', 'location_instance.lid  = location.lid');

    //created and nid are the same fields used by my_view query
    $query2->addField('node', 'title', 'users_name');
    $query2->addField('node', 'nid', 'uid');
    $query2->addField('location', 'latitude', 'location_latitude');
    $query2->addField('location', 'longitude', 'location_longitude');
    $query2->addExpression(':the_group_type', 'Type', array(':the_group_type' => 'Group'));

    //set some conditions if necessary
    $query2->condition('node.type', 'group', '=')
           ->condition('node.status', 1, '=');

    $query1 = $view->build_info['query'];
    $query1 ->addExpression(':the_user_type', 'Type', array(':the_user_type' => 'User'));

    //union custom query with my_view default query
    $query2->union($query1, 'UNION ALL');

    //in order to prevent Cardinality violation errors i have to make a "total" query
    $total_query = db_select($query2,'total')->fields('total');

    //update views query and count_query with my new query.
    $view->build_info['query'] = $total_query;
    $view->build_info['count_query'] = $view->build_info['query']; //count_query is necessary for the pager
  }
}

```

# Answer
> 2 votes
Any valid SQL expression is allowed, and that includes placeholders (like in that code), literal values, or SQL functions calls (including aggregate functions, such as `COUNT(*)`).

`$query2->addExpression(':the_group_type', 'Type', array(':the_group_type' => 'Group'))` is equivalent, in plain SQL, to `'Group' AS Type`.
It is an expression that is widely used in the Views module. For example, if you enable the "Add Views signature to all SQL queries" option, the query executed by the Views module will be similar to the following one. (This is the query I get for the front page view.)

```
SELECT node.sticky AS node_sticky, node.created AS node_created, node.nid AS nid, 'frontpage:default' AS view_name
FROM
{node} node
WHERE (( (node.promote <> '0') AND (node.status = '1') ))
ORDER BY node_sticky DESC, node_created DESC
LIMIT 10 OFFSET 0

```

The `'frontpage:default' AS view_name` part is added using `SelectQuery::addExpression()` in a way similar to what the code you show does.

---
Tags: views, database
---


# Question
Title: How to hide page title based on node type using template_preprocess_page()
I am trying to hide the title of the current page (as printed by `page.tpl.php`) if the current page is 1) a node in full display (as opposed to teaser mode), AND 2) the node type is either *concert* or *bio*. I print the node title for these content types directly in the node content, so I want to hide the duplicate being printed by page.tpl.php. I am not able to get this to work directly in page.tpl.php, and my reading suggests the best practice is to handle template logic in template.php using preprocess and process functions. So, I am trying to hide the current page title (with the above 2 conditions) using `template_preprocess_page()`. This is my code.

```
<?php
    function MYTHEME_preprocess_page(&$variables) {
        if (!empty($variables['node']) && $variables['node']->type == 'concert') {
            hide($variables['title']);
        }
    }
?>

```

I read How do I test for node type to print a variable from template.php? and the documentation page for `template_preprocess_page()`, and various other sites, but I just can't seem to get this to work. I saw suggestions that you have to call `isset()` on `$variables['node']` before testing for the node type, but that didn't work either. I didn't see a clear solution posted anywhere, and I'm at my wit's end.

# Answer
> and my reading suggests the best practice is to handle template logic in template.php using preprocess and process functions.

Decoupling the logic from the rendering code simply means the code in template.php sets a variable that is checked in the template file. In this way, the logic is all contained in the template.php file, while the rendering code is all in the template files.

### template.php

```
function mytheme_preprocess_page(&$variables) {
  if (!empty($variables['node']) && $variables['node']->type == 'concert') {
    $variables['show_title'] = FALSE;
  }
}

```

### page.tpl.php

```
<?php if ($show_title && $title): ?><h1 class="title" id="page-title"><?php print $title; ?></h1><?php endif; ?>

```

`hide()` doesn't work because `$variables['title']` is a string, not a rendering array. `hide()` is always used with a rendering array, and it doesn't have any effect with a string, not even when the string is passed to `render()`.
Actually, passing a string (or any value that is not a reference to a variable containing an array) to `hide()` would cause a PHP error, since the function uses this code.

```
function hide(&$element) {
  $element['#printed'] = TRUE;
  return $element;
}

```

Unsetting `$variables['title']` with `unset($variables['title'])` doesn't work too, as `template_process_page()` would get the page title from `drupal_get_title()`.

```
if (!isset($variables['title'])) {
  $variables['title'] = drupal_get_title();
}

```
> 9 votes

# Answer
You can manage this using drupal\_set\_title().

```
function mytheme_preprocess_page(&$vars){
    if (isset($vars['node']) && $vars['node']->type == 'news'){
        drupal_set_title('');
    }
}

```
> 2 votes

# Answer
Try this assuming your if condition is correct :)

```
 function MYTHEME_preprocess_page(&$variables) {
        if (!empty($variables['node']) && $variables['node']->type == 'concert') {
            unset($variables['title']);
        }
    }

```
> 1 votes

# Answer
Less complicated way is by printing this in your page.tpl.php

```
<?php hide($title); ?>

```

But if you want it to be dynamic I would suggest to use the `preprocess_page` as suggested by others.
> 0 votes

# Answer
In CSS, I did this to my theme

```
/*    Front Page - hide title  */
body.front header h1 {
 position: absolute;
 left: -999em;
}

```

As recommended by http://www.alistapart.com/articles/now-you-see-me/

Why? Because you still want to have the header and h1 'visible' to screen readers for accessibility. If you simply strip off the value of the H1, you're robbing your blind and low vision visitors of some potentially important information.
> 0 votes

# Answer
the suggestion of **mytheme\_preprocess\_page** works for me but if is used `$vars['title_hidden'] = TRUE;`

```
function mytheme_preprocess_page(&$vars) {
  if (isset($vars['node']->type) && $vars['node']->type == 'type') {
    $vars['title_hidden'] = TRUE;
  }
}

```
> 0 votes

# Answer
The correct function is

```
function mytheme_preprocess_node(&$vars) {
}

```

instead of

```
function mytheme_preprocess_page(&$vars) {
}

```
> 0 votes

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


# Question
Title: How to filter filenames in views based on a match to currently logged username?
I am quite novice to Drupal. I am trying to figure out how to create views listing files such that only those files are listed where filename contains currently logged username?

# Answer
> 2 votes
If you could use tokens in views filters you could do something like File: name ... contains any word ... \[user:name\] and that would end up in the sql as file\_managed.filename LIKE '%username%' which would be cool. But you can't do that, to my knowledge.

You might achieve what you want using contextual filters having PHP code in both contextual filter and validator, maybe.

That said, depending on how much files and users you have and so on, it might be easier to tag the files with taxonomy terms. That way user wanting to change their username, eg. when they get married, won't brake your system. Also usernames having spaces, underscores, apostrophies etc. wouldn't be an issue.

**Edit:**

What do you know, this can be done with contextual filters! I don't know how practical or robust or performant this is but here goes:

1) Add a contextual filter of Global: null.
2) Provide some default value, doesn't matter what. For example Fixed value -\> 'blaa'.
3) Specify validation criteria -\> PHP code

```
global $user;

$view->query->where = array(
    1 => array(
        'conditions' => array(
            0 => array(
                'field' => 'file_managed.filename',
                'value' => '%' . $user->name . '%',
                'operator' => 'LIKE',
            )
        ),
        'args' => array(),
        'type' => 'AND',
    )
);
return true;

```

I figured this out with dpm($view). If you have other filters in the Filter criteria, this code will have to take that into account. Tampering with the $view like this is not really future proof, but theoretically possible.

# Answer
> 0 votes
You can get current logged username by using token \[current-user:name\] or just \[user:name\], provided you have Pathauto installed.

---
Tags: views
---


# Question
Title: How to get rid of the '-' sign before sub taxonomy term?
when I choose a taxonomy term with a parent, it shows *-termName* instead of *termName*, to indicate it is a sub-category. I checked the database, it only stores the termName, which means that somewhere we can rewrite the output to show just *termName*.

How can I achieve this?

# Answer
> 2 votes
In Drupal 6, the function that outputs the list of taxonomy terms is \_taxonomy\_term\_select(), which contains the following code.

```
  if ($tree) {
    foreach ($tree as $term) {
      if (!in_array($term->tid, $exclude)) {
        $choice = new stdClass();
        $choice->option = array($term->tid => str_repeat('-', $term->depth) . $term->name);
        $options[] = $choice;
      }
    }
  }

  return array(
    '#type' => 'select',
    '#title' => $title,
    '#default_value' => $value,
    '#options' => $options,
    '#description' => $description,
    '#multiple' => $multiple,
    '#size' => $multiple ? min(9, count($options)) : 0,
    '#weight' => -15,
    '#theme' => 'taxonomy_term_select',
  );

```

Since it uses theme\_taxonomy\_term\_select(), overriding that theme function is possible to remove those hyphens added at the beginning of the term name.

In Drupal 7, that code is contained in taxonomy\_allowed\_values().

```
  $options = array();
  foreach ($field['settings']['allowed_values'] as $tree) {
    if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
      if ($terms = taxonomy_get_tree($vocabulary->vid, $tree['parent'])) {
        foreach ($terms as $term) {
          $options[$term->tid] = str_repeat('-', $term->depth) . $term->name;
        }
      }
    }
  }

```

Unfortunately, the function calling it (options\_field\_widget\_form()) uses a theme function used for every form element (including the ones not associated with taxonomy terms), for example theme\_select().

```
  switch ($type) {
    case 'select':
      $element += array(
        '#type' => 'select',
        '#default_value' => $default_value,

        // Do not display a 'multiple' select box if there is only one option.
        '#multiple' => $multiple && count($options) > 1,
        '#options' => $options,
      );
      break;

    // …

  }

```

Fortunately, `options_field_widget_form()` uses some custom properties that allows to check if the select form element is being output for an entity. In fact, it uses the following code.

```
$entity_type = $element['#entity_type'];
$entity = $element['#entity'];

```

This is true also in the case the used form element is checkboxes, radios, or checkbox.
If `$variables['element']['#entity_type']` passed to the theme function for the select form element is set, and it is equal to the entity type for the taxonomy terms, then the theme function can assume it is outputting the select element for a taxonomy term, and remove the hyphens at the beginning of the term name.

---
Tags: taxonomy-terms
---


# Question
Title: Show entries in view only if other nodes with same term reference exist
I have a view of several fields from one content type (content type is called "summary"). A required field in the content type is a term reference, called "connector". "connector" is also a required field in a different content type ("details"). I only want to include the content of a node summary in the view if a node details exists with the same "connector" reference.

Is this possible when using views? Using the interface would be ideal, but since I am already doing some post-rendering for that view, it might be easiest to remove the unwanted entries there?

From what it sounds like, it should be possible to do this using the relation module. However, I can't wrap my head about how to configure it.

Any help highly appreciated!

# Answer
> 0 votes
After sifting through several modules, I decided that it's easiest to achieve this with theme pre-processing. Here is what I did:

I used the drupal 7 schema that I created years ago (http://upsitesweb.com/blog/2011/06/drupal-7-database-schema), to figure out which tables to join. The vocabulary I am using has the vid 14. I pre-processed the view and checked for each line, whether the corresponding node in the details content type exists, rewrite the view entries to only contain matched entries.

It must be possible to also achieve the same with contributed modules. However, it was faster and more efficient to use views pre-rendering instead, especially, since other aspects of this view are getting pre-rendered anyway.

```
function theme_views_pre_render(&$view) {
   if ($view->name == "summary_details") { //filtering summary entries without detail
      $nids = array(); // array of nodes
      $nodeswithdetails = array(); // manipulated results
      foreach($view->result as $key => $result) // check each node of the result array on it's nid
      {
        $nid = $result->nid;
        $return = theme_ensure_details($nid);
        if ($return == 1) {
           $nodeswithdetails[] = $view->result[$key];
        }
      }
      $view->result = $nodeswithdetails;
   }
}

function theme_ensure_details($nid) {

   $results = db_query('SELECT s.nid AS sum_nid FROM {node} n, {node} s, '
                      .' {taxonomy_index} t, {taxonomy_index} t1, '
                      .' {taxonomy_term_data} td WHERE t.tid=t1.tid '
                      .' AND t.tid=td.tid AND td.vid=14 AND n.type=:dettype '
                      .' AND n.nid=t.nid and s.type=:sumtype AND s.nid=t1.nid '
                      .' AND s.nid= :nid',
         array(':nid' => $nid,':revtype' => 'details', ':reptype' => 'summary'));

    $found = 0;
    foreach ($results as $row) {
       if ($row->sum_nid == $nid) {
       $found= 1;
    }
  }
  return $found;
}

```

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


title: Add conditional stylesheet to URL alias

text:
# Question
Title: Add conditional stylesheet to URL alias
I am attempting to add a conditional stylesheet to my user registration form which has an alias called "signup"

This is the code I am using, however this does not seem to work. I have tried loads of other different ways but I cannot seem to find any clear documentation on how to do this.

Any ideas on this? The simpoer the better, my code seems to be quite complex for something so simple.

Thanks

```
function mytheme_preprocess_page(&$variables, $hook) {
$matches = "signup";
$path = drupal_get_path_alias($_GET['q']);
$page_match = drupal_match_path($path, $matches);
if ($path != $_GET['q']) {
$page_match = $page_match || drupal_match_path($_GET['q'], $matches);
}
if ($page_match) {
drupal_add_css(drupal_get_path('theme', 'mytheme') . '/style.css');
}

```

Also tried this to no avail

```
function mytheme_form_alter(&$form, &$form_state, $form_id) {
global $user, $theme;
switch ($form_id) {
    case 'user/register':
      $form['#attached']['css'] = array(
        drupal_get_path('theme', 'mytheme') . '/css/new.css',
      );
    break;
 }

```

# Answer
> 2 votes
You're right, that **is** overly complex.

First of all, make sure your `mytheme_preprocess_page()` function is actually getting called by adding print & then exit statements. If it's not getting called, clear your theme registry by clearing the site's cache.

Once you're sure the preprocessing function is getting called, this will do the trick for you:

```
if (preg_match('#user/register#', $_GET['q'])) {
  drupal_add_css(drupal_get_path('theme', 'mytheme') . '/style.css');
}

```

`$_GET['q']` always contains the 'internal' Drupal path, not the alias. The internal path for the normal registration form is user/register, so that's what you want to check for.

# Answer
> 0 votes
The simplest and best practice to add a css to user registration form is implementing hook\_form\_FORM\_ID\_alter():

```
function YOURTHEME_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  drupal_add_css(drupal_get_path('theme', 'YOURTHEME') . '/YOURCSS.css');
}

```

---
Tags: theming
---


# Question
Title: How to reset form page after it has been successfully submitted?
User is allowed to submit answers from the question node view page.

The form is redirected to the same question node view page after submission. But the form displayed still displays the older values. How can I reset these values?

```
function answers_custom_node_view($node, $view_mode, $langcode) {

  if (arg(0) == 'node' && is_numeric(arg(1)) && $node->type == 'question') {
    global $user;
        if(node_access("create", "answer", $user)) {
        $node1 = (object) array(
            'uid' => $user->uid,
            'name' => (isset($user->name) ? $user->name : ''),
            'type' => "answer",
            'language' => LANGUAGE_NONE,
        );
        $form_state['build_info']['args'] = array($node1);
        form_load_include($form_state, 'inc', 'node', 'node.pages');
        $form = drupal_build_form('answer_node_form', $form_state);
        $output = drupal_render($form);
        $node->content['answer_form'] = array(
            "#type" => "markup",
            "#markup" => $output,
        );
      }
   }
}

function answers_custom_form_alter(&$form, &$form_state, $form_id) {
   if($form_id == "answer_node_form") {
       if (arg(0) == 'node' && is_numeric(arg(1))) {
        $nid = arg(1);
        $node = node_load($nid);
        if($node->type == "question") {
             $form['#submit'][] = "answers_custom_destination";
        }
       }
   }
}

function answers_custom_destination($form, &$form_state){
   if (arg(0) == 'node' && is_numeric(arg(1))) {
    $nid = arg(1);
    $node = node_load($nid);
    if($node->type == "question") {
        $form_state['rebuild'] = TRUE;
        $form_state['redirect'] = drupal_get_path_alias('node/'. $node->nid);
     }
   }
}

```

# Answer
> 4 votes
That happens because you are using `$form_state['rebuild'] = TRUE;` which is telling Drupal to rebuild the same form, which also mean the form will be repopulated with the last values the users entered. When you then set `$form_state['rebuild']` to `TRUE`, `$form_state['redirect']` is ignored, since the user is already redirected to the page containing the form.

The code I would use is the following one.

```
function answers_custom_form_answer_node_form_alter(&$form, &$form_state) {
  if (arg(0) == 'node' && is_numeric(arg(1))) {
    // See https://api.drupal.org/api/drupal/includes%21menu.inc/function/menu_get_object/7.
    $node = menu_get_object();

    if ($node->type == "question") {
      $form['#submit'][] = "answers_custom_destination";
    }
  }
}

function answers_custom_destination($form, &$form_state) {
  // Since the form submission handler is added only when the user is seeing node/%node,
  // there is no need to verify that again.
  $form_state['redirect'] = FALSE;
}

```

As side note, since the form alter hooks and the form submission handlers share `$form_state`, which is passed by reference, if something needs to be shared between those functions, it can be added to `$form_state`. As long as the added array index doesn't conflict with an array index used by Drupal or third-party modules, all is fine.

For example, this code would use `$form_state` to share a value between the hook altering the form, and the form submission handler.

```
function answers_custom_form_answer_node_form_alter(&$form, &$form_state) {
  if (arg(0) == 'node' && is_numeric(arg(1))) {
    // See https://api.drupal.org/api/drupal/includes%21menu.inc/function/menu_get_object/7.
    $node = menu_get_object();

    if ($node->type == "question") {
      $form_state['answers_custom_question'] = $node;
      $form['#submit'][] = "answers_custom_destination";
    }
  }
}

function answers_custom_destination($form, &$form_state) {
  // Since the form submission handler is added only when the user is seeing node/%node,
  // there is no need to verify that again.
  $form_state['redirect'] = drupal_get_path_alias('node/' . $form_state['answers_custom_question']->nid);
}

```

### Reference

---
Tags: 7, nodes, redirection, forms
---


title: jQuery animation isnt repeating

text:
# Question
Title: jQuery animation isnt repeating
Im pretty sure that my jQuery should below should work but when I use it in a Drupal site the animation doesn't repeat like it should.

http://smartpeopletalkfast.co.uk/t/

```
$(document).ready(function() {
    if ( $(window).width() > 960) {

    function fadeOutFunc() {
        $('.image-list .bottom').delay(1000).fadeOut(500, function() {
            $('.image-list .bottom').delay(1000).fadeIn(500,fadeOutFunc);
        });
    }

    fadeOutFunc();

    //  jQuery('.image-list .bottom').css('opacity','0.6');

    }
});

```

# Answer
Try putting js code using Drupal Behaviours

```
(function($, Drupal)
{
  Drupal.behaviors.animation = {
    attach:function()
    {
      if ( $(window).width() > 960) {

      function fadeOutFunc() {
        $('.image-list .bottom').delay(1000).fadeOut(500, function() {
          $('.image-list .bottom').delay(1000).fadeIn(500,fadeOutFunc);
        });
    }

    fadeOutFunc();
    }
  };
}(jQuery, Drupal));

```
> 0 votes

---
Tags: javascript
---


# Question
Title: How to: Multilingual site with one front page that makes user choose a language first
I want to have a front page like www.mysite.com/frontpage that shows up for every new visitor and helps him select a language and then move on to whatever language homepage the user selected.

# Answer
You can create a custom block to display the language enable into site and a link to respective page of particular language.

To display the custom block in home page, you can use panels, create different template for the home page (page--front.tpl.php).
> 0 votes

# Answer
Read https://drupal.org/documentation/multilingual

Install https://drupal.org/documentation/multilingual

One configured your site will have /es and /en, for example. Simply add now a front end ui linking to each one and that's it :-)
> -3 votes

---
Tags: i18n-l10n
---


# Question
Title: How to make the name of an organic group unique
can someone explain how to make groupnames unique? If i create 2 groups with the same name, i want to become a validation error. Actually i tested og in the commons distribution an there i can create groups with same names, but in the list of all groups are only one of the same groups listed.

Thanks for your help.

Greats Daniel

# Answer
> 1 votes
Assuming your og groups are based on node entities.

> * You can have unique group titles with help of unique\_field module.
> * With help of this module you can set the title field as unique fields the content type generating groups on your site.

---
Tags: organic-groups
---


title: Different fields per taxonomy term

text:
# Question
Title: Different fields per taxonomy term
A classified like site requires very different fields per category or taxonomy term. For example car will need fields like milage, model etc.. while a house will have no. of bedrooms, sqr. feet etc. I am finding different ways to do this but not sure which is scalable. I will also be using faceted search api.

First Method: Create a generic entity with common fields and programmatically create custom entity per category which will be related using entity reference.

Second Method: Create single entity or content type with all fields and write logic to hide and show fields per category.

Third Method Create content type per category.

# Answer
If the fields differ markedly, that's a case for a different content type.

e.g "Vehicle" and "House" would be two distinct content types with their own fields - much easier in the long run.
> 1 votes

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


# Question
Title: New content type not listed in content types
First time I created the content type 'address', I simply clicked save, not 'save & edit fields'. As a result, my new content failed to be listed under `admin/structure/types`. Then I simply tried the same thing again, with the same result of nothing being listed. When I did this though, A Drupal message said that the content type 'address' had been updated.

3rd time I clicked 'Save & edit', I wanted to manage fields, but that generated a URL that said `www.domainname.com//fields` instead of `www.domainname.com/address/fields`. Also a notice came : `Notice: Undefined index: address in _field_ui_bundle_admin_path() (line 325 of C:\xampp\htdocs\hosting\sites\drupal7\modules\field_ui\field_ui.module).`

Note that I'm using the module Automatic nodetitles

# Answer
The problem you're facing is producing symptoms very similar to the ones in this bug. Especially because one of the symptoms you mentioned is that after you create any new content type with the same machine name that had a problem ('address' in your case) you get the message:

> *The content type XXX has been updated*

This issue is because one of the content types that you previously created originally had a machine name of 'address' but was renamed to something else. This is because Drupal actually preserves the original machine name of any content type in the DB Table named "Node\_Type" in the column "Orig\_Type".

Firstly, I suggest that you open the "Node\_Type" table and try to investigate. You will most likely find that one of the listed Content Types has 'address' in its "Orig\_Type" column.

The bug I've linked above contains patches in order to prevent this kind of issue from happening in the future. Unfortunately, in your case, the issue had already happened and you must now clean-up.

**I'm not an expert in this field** as I've only been involved with drupal for 6 months. However, I'll try my best to list the steps you need to do to remedy the issue. Note that there may be better/cleaner methods than the ones I've listed below so please be cautious:

**Step 1 -** Please carefully investigate the "Node\_Type" table in your Database as I've mentioned above before proceeding. You may be facing a different issue and this solution may or may not work in that case.

**Step 2 -** Backup your Database before proceeding

**Step 3 -** Please try to perform **one** of the following procedures, preferably in order until one of them works for you:

A. Try the Deletion URL

* Try to go to the URL YOUR\_SITE/admin/structure/types/manage/MACHINE\_NAME/delete and delete the content type
* Check the "Node\_Type" table to see if the problematic content type was deleted.

B. Programatic Deletion

* Try to programatically delete the unwanted content type by running node\_type\_delete($type) and then optionally node\_types\_rebuild(). In order to use these 2 functions in a module you must use the hook\_node\_info(). Something similar to this code may work in your module's ".module" file:

> ```
> <?php
> function MYMODULENAME_node_info()
> {
>   node_type_delete("address");
> }
>
> ```

* Check the "Node\_Type" table to see if the problematic content type was deleted.

C. Manually Replicate node\_type\_delete($type)

* Visit the node\_type\_delete($type) hyperlink, and carefully read all the functions that it invokes. They are all clickable hyperlinks too.
* Either write code to use each of its functions individually.
* Or, replicate the actions that all the functions perform exactly and manually in your Database.

@Mods. The site restricts me from posting more than 2 hyperlinks because of my reputation, so apologies for lack of links.
> 2 votes

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


title: Validation programmatically in Drupal

text:
# Question
Title: Validation programmatically in Drupal
I am creating a user programatically.

I have following files

```
$fields = array(

    'name' => $name,
    'mail' => $mail,
    'pass' => $password,
    'status' => 1,
    'init' => $mail,
    'field_first_name' =>array('und'=>array(0=>array('value'=>$first_name))),
    'field_last_name' => array('und'=>array(0=>array('value'=>$last_name))),
    'field_company_name'=>array('und'=>array(0=>array('value'=>$company_name))),
    'field_company_number'=>array('und'=>array(0=>array('value'=>$company_number))),
    'field_mobile_number'=>array('und'=>array(0=>array('value'=>$mobile_number))),
    'field_secondary_number'=>array('und'=>array(0=>array('value'=>$secondary_number))),
    'field_mobile_or_landline'=>array('und'=>array(0=>array('value'=>$landlinemobile))),
    'field_promo_emails_notifications'=>array('und'=>array(0=>array('value'=>$email_notification))),

```

);

Now i am using `user_save(NULL,$fields);`

Which is working fine. Now field\_first\_name, and some other fields are required which i have set under account mangefields. How to check validations of these fields. Does anybody tell me

Thanks

# Answer
Validation is pretty much depends on what kind of fields are they! Still I can show validation for the common fields as on user registration process.

You must be hooking into the user registration form somewhere, unless form is custom form.Assuming you are implementing hook\_form\_alter() to hook into user registration form.

```
> Step 1: Add validation handler to the user registration form.

    // Implementing hook_form_alter() to add validation handler to user registration form.
    function mymodulename_form_alter($form,$form_state,$form_id) {

    // Not sure you have to check form id of the user registration form.
      if($form_id == "user_registration") {
        $form['#validate'] = array(
          '#validate' => array('_mymodulename_registration_validate'),
        );
      }
    }

    // Write validation callback.
    function _mymodulename_registration_validate(&$form,&$form_state) {
       // Validate last name.
      if (trim($form_state['values']['last_name']) == '') {
        form_set_error('last_name', 'Last Name field is required field');
      }

      // Validate company name.
      if (trim($form_state['values']['company_name']) == '') {
        form_set_error('company_name', 'Company Name field is required field');
      }

      // Validate the e-mail address.
      if (!valid_email_address(trim($form_state['values']['email']))) {
        form_set_error('email', 'Please enter valid email address');
      }
      if (_mymodulename_registration_user_validate_mail(trim($form_state['values']['email'])) == 1) {
        form_set_error('email', 'Email address already registered');
      }
        // Validate password.
      if (trim($form_state['values']['password']) == '') {
        form_set_error('password', 'Password field is required');
      }
      if (trim($form_state['values']['password_confirm']) == '') {
        form_set_error('password_confirm', 'Repeat password field is required');
      }
      if (trim($form_state['values']['password_confirm']) != trim($form_state['values']['password'])) {
        form_set_error('password_confirm', 'Passwords do not match');
      }
    }

/**
 * Helper function to validate email adress already exists or not.
 *
 */
function _mymodulename_registration_user_validate_mail($email) {

  // used db_query_range() to check if email exists or not.
  if ((bool) db_query_range("SELECT mail FROM {users} WHERE mail = :name", 0, 1, array(':name' => $email))->fetchField()) {
    return 1;
  } return 2;
}

```
> 1 votes

---
Tags: 7
---