# Question
Title: Render content from page.tpl.php in ajax callback, without the html.tpl.php
I am attempting to render an entire page through an ajax callback using either custom javascript or drupals `ajax_deliver`. The issue is that it is trying to render the entire page and I simply want it to render what is in a custom `page.tpl.php` file created. I have found a solution around this using a `$_GET` in the `html.tpl.php` but it seems hacky to me.

Basically I am rendering only the `$page` variable if a `$_GET` is set, if not render it as normal. Is there any functions or way to simply render all the regions in a page, minus what is in the `html.tpl.php`

# Answer
There is AJAXify Pages (dev version only)

> Module to ajaxify site browsing and navigation. For instance, it allows for continuous audio playback via Background Audio module while changing the content of the pages.

or AJAXify module (D5 only)

> You can always create links that load other pages via AJAX but you will still load a full page HTML while you may only need a single HTML element from the loaded page and this is what AJAXify focuses on.

If youre not planning to use any of these module take a look at THIS function to get some idea.
> 0 votes

---
Tags: theming, ajax
---


# Question
Title: Views display of every user's flagged nodes grouped by flag type
I am using views and the flags module to create a site where users can flag node items with multiple flags/flag types. For my example, a user can flag nodes (content) items with one of three flags: fruits, veggies, or other.

User 1, name and profile picture

---

```
flag-fruits     flag-veggies     flag-other
------          ------           ------
apple           carrots          pork
orange          celery           ham
cherry                           soda

```

User 2, name and profile picture

---

```
flag-fruits     flag-veggies     flag-other
------          ------           ------
lime            artichoke        trout
banana          lettuce          barley
cherry          ginger           soda

```

User 3, name and profile picture

---

etc…

I have tried setting up the relationships in Views using content (node) item listings and Users' Flagged Content relationships. With Grouping Fields I can manage to relate a single flag type to each user, so…

User 1

---

```
flag-fruits
------
apple
orange
cherry

```

But I really need the view to show each flag under each user in a list. I have been attempting this with the \[ViewField\]\[1\] module and also regular Views Attachments, but so far with no luck. Is this even possible? Panels maybe?

```
[1]: http://drupal.org/project/viewfield

```

# Answer
> 0 votes
For grouping, I have used Views Grouped Table to good effect. You might also look at Views Complex Grouping, a more recent module.

---
Tags: views, flags
---


# Question
Title: Is it possible to change the _alt_ text wording for images in one place?
Is it possible to change the *alt* text wording for images in one place, as the wording used does not pass validation?
The website contains a vast amount of pages, most of which with images having poorly worded *alt* text. Most of the images are inline, but some have been uploaded with the image field.

The site is running Drupal 7, if this makes any difference.

# Answer
> 0 votes
If the images are all inline (i.e. part of the body content of the node) then there is no easy way to change the alt text in one place because these images have not been abstracted into the Drupal system. If these were fields or part of the files table, it might be possible to quickly update these using PhpMyAdmin or some other database solution but at this point your best options are

1. brute force (just what it sounds like, a painful node-by-node fixin' of the alt text).
2. try a search and replace option of the body text. I've used the scanner module for this kind of operation and recommend it as it has robust regex support and (most importantly) a rollback option.

Neither of these are great options but they're the best you can do given the circumstances. Which to choose depends on a). how many nodes you have to deal with, and what kind of alt text you have to add. If you're adding the same alt text to every image, scanner is your answer but if you have to evaluate and update each image with appropriate alt text (ex for 508 compliance), brute force is the way to go.

---
Tags: media, views
---


# Question
Title: How to change MENU_LOCAL_TASK title for the View and Edit tabs according to content type?
I am trying to change the title ( tab text ) of the standard Drupal menu local task tabs 'View' and 'Edit'. I want them to reflect the content type of the current node. So on the page node/1234 ( which is a blog node, say ) I want the View tab to say 'View blog' etc.

I can change the text using :

```
$items['node/%node/view']['title'] = 'View blog';

```

in a hook\_menu\_alter() function, but I can't seem to get hold of the node itself to test what content type it is to vary the text. The arg() function doesn't return anything within the hook\_menu\_alter() function for some reason ?

How do I do this ?

Thanks

# Answer
> 0 votes
`hook_menu()` implementations are cached so aren't executed for every page (can you imagine how bad that would be for performance?)

You can use the `title callback` property from `hook_menu()` to evaluate a title on each page load, e.g.

```
$items['node/%node/view']['title callback'] = 'MYMODULE_title_callback';
$items['node/%node/view']['title arguments'] = array(1);

...

function MYMODULE_title_callback($node) {
  if ($node->type == 'foo') {
    return 'bar';
  }
  else {
    return 'baz';
  }
}

```

# Answer
> -1 votes
You can try Tabname Tweaker module.

This module allows admins to override the name of the 'View' tab on node pages. Useful for Organic Groups, where the normal 'View' tab serves as an overview or landing page rather than a specific piece of content.

This module allow to change and override the **View** and **Edit** tabs

---
Tags: routes
---


# Question
Title: Drush finding 3rd party module but can't install
Have moneyscripts modules installed and drush does not update these 3rd party scripts but still I get a notification via drupal that update is required.

So I used drush up command but failed to update saying could not find download. Then I manually wget install the update but now if I drush up after manual install it won't stop trying to update the core.

How can I make drush IGNORE moneyscripts considering it can't install them anyway?

Or do I just have to select no everytime it asks?

# Answer
> 2 votes
Please see --lock, described in drush help pm-update:

```
--lock

     Add a persistent lock to remove the
     specified projects from
     consideration during updates.  Locks
     may be removed with the --unlock
     parameter, or overridden by
     specifically naming the project as a
     parameter to pm-update or
     pm-updatecode.  The lock does not
     affect pm-download.  See also the
     update-advanced project for similar
     and improved functionality.

```

---
Tags: drush
---


# Question
Title: drupal 7 programatically close comments in custom node type
I have created a content type programmatically. Also looked at http://drupal.org/node/1169864 but comments are not being close. Although I solve it by `variable_set('comment_mynodetype', '1')`. Any other help. My code is below:

```
$t = get_t();

  $node = array(
    'type' => NODE_NAME,
    'name' => $t('My Node Type'),
    'base' => 'node_content',
    'locked' => TRUE,
    'node-preview' => 0,
    'node-options' => array('status'),
    'comment' => array('status' => 1),
    'description' => $t('A content type.'),
    'title_label' => $t('Title'),
    'custom' => FALSE
  );
  $content_type = node_type_set_defaults($node);
  //add body field using drupal function
  node_add_body_field($content_type, $t('Description'));
  node_type_save($content_type);

```

Any help ..

\[UPDATED\]

```
 $node = array(
        'type' => NODE_NAME,
        'name' => $t('My Node Type'),
        'base' => 'node_content',
        'locked' => TRUE,
        'node-preview' => 0,
        'node-options' => array('status'),
        'description' => $t('A content type.'),
        'title_label' => $t('Title'),
        'custom' => FALSE
      );
   //close comments
   variable_set('comment_mediasite', '1');

```

# Answer
`$node->comment` should be an integer (not an array). Acceptable values are:
> 6 votes

---
Tags: nodes
---


# Question
Title: using entity reference fetch different fields automatically
using entity reference, i am able to relate to nodes with one another. Thats great. The user while entering their blog has an option to relate it to nodes of my custom content type. This works great. Now i want that once the user has selected the node to be related to, the blog should not only show the title of the n node but also other fields from that referenced node. How can i achieve this?

Regards

# Answer
On the content type that has the reference-field, on the "Manage Display" section, you can choose if you want "Label" or "Rendered entity", which will output the full node.
> 1 votes

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


# Question
Title: How to display node teaser in Display Suite custom field?
I am trying to create custom Display Suite code field.

I would like to show truncated text of node body or teaser if exists (+ other stuff, like: (...) and link to current node)

I tried to use \[node:teaser\] but nothing was showed. I tried to use \[node:body:?\] token too, but all options I have tried failed for me.

Field code:

```
[node:teaser] (...) <a class="read-more" href="[node:url]"><?php print t('read more'); ?></a>

```

Any suggestions?

It so basic thing but I have no idea what I am doing wrong here...

# Answer
I did this by adding a preprocess field which then becomes available in DS.

```
<?php
      function MYTHEME_preprocess_node(&$variables) {
        // Get the summary as a discrete field.
        $body = array_pop(field_get_items('node', $variables['node'], 'body'));
        $variables['node_summary'] = $body['safe_summary'];
      }

```

Then in display suite add a preprocess field named node\_summary.
> 3 votes

---
Tags: 7, display-suite, entities
---


# Question
Title: Overriding default hashing mechanism: cannot redeclare user_hash_password()
I have a project that requires a change in the default password encryption mechanism.

The documentation of password.inc states that this can be overridden using the `password_inc` variable. I followed the instructions as stated in the documentation but when trying to change a password on the website following error is generated:

> Cannot redeclare user\_hash\_password() (previously declared in /.../drupal7/includes/password.inc:207) in /.../drupal7/sites/foo/modules/custom/foo\_custom/includes/foo\_custom.password.inc ...

I have searched the code for a hardcoded include on includes/password.inc but can't find anything.

Any ideas?

# Answer
> 0 votes
Everything in core uses

```
require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');

```

so I would guess at the cause being a contrib module.

Also just check that the password\_inc variable has been updated correctly and not deleted somehow.

---
Tags: 7, security, users
---


# Question
Title: What is best method to use for multiple databases on one server?
Do you create an extra database for each site running on same drupal core or use replication, what is the best practice at the outset for setting up multisite databases on a vps centos server?

# Answer
This question is dangerously off-topic, but as far as Drupal is concerned there are two primary things to consider.

True multisite (multiple independent sites running our of the same DOCROOT) versus multiple sites on the same server don't really come into play. In fact, you could also apply this to multiple sites using the same database server instance.

Running multiple sites out of the same database catalog is used when

1. You only have one catalog to use and need to share it (eg, shared hosting).
2. You want to share some tables between instances.

However, as those state, this isn't a good idea. Apart from the stability issues with sharing tables, you also have the security issue of an exploit in one site potentially getting at the data from another site.

Ideally, each site should have its own catalog in your database server, and each of these should have a unique user associated with it that has full access (minus `GRANT`) with connections limited to where the site is running from (either localhost or the IP address of the webserver). This is the username/password that you should use in your settings.php

Database replication doesn't really factor into the decision here. It is use for performance and/or redundancy reasons. Drupal has some support for master/slave arrangements, but it is not really transparent.
> 1 votes

---
Tags: multi-sites
---


title: Where do I find the Statistics module?

text:
# Question
Title: Where do I find the Statistics module?
I must use Drupal 5.10 for one project. It's already done, but I am doing some changes, so I must add this line to each node:

> Viewed: 3 | Total views: 30

I know I must use the Statistics module, but I cannot find one for Drupal 5. Can anyone help me please?

# Answer
> 4 votes
A quick search turned up this video from DrupalDude: Statistics module in Drupal 5

There's also the documentation for the module for the D5 version on Drupal.org that suggests you should be able to use `statistics_get()` to get the views for a certain node.

*Something* like the following would do it:

```
$stats = statistics_get($nid);

// Total view count
print $stats['totalcount'];
// Current day view count
print $stats['daycount'];
// Timestamp of last view
print $stats['timestamp'];

```

---
Tags: nodes, 5
---


# Question
Title: How to invite Facebook, twitter, gmail friends into organic groups
How can i invite Facebook, twitter,Gmail friends in to my Organic Groups in Drupal 6. Is there any possibility about this. Let me know. Thanks, Thiru

# Answer
> 2 votes
You can make use of Contact Importer module.

> Contact Importer provides a form for your users to enter their email address and password. The contacts from their address book are then retrieved.

Of course you need to alter the module to send invites.

Or

Try using Rules Module with this, to make it a chained process.

# Answer
> 0 votes
One thing to keep in mind when using this module, your host may think you are transmitting spam and suspend your account. I found it better to create a Facebook App and a Twitter app and go that route. Very easy to do.

---
Tags: organic-groups, social-network
---


title: Auto-remove unused tags

text:
# Question
Title: Auto-remove unused tags
Drupal 7.

We want to remove tags (of Tags vocabulary) automatically when all pages referring to this tag are removed.

Is there a module for this?

# Answer
> 7 votes
There are a couple of modules that might help:

* Taxonomy Orphanage (specifically the cron interface)

> This module provides interfaces (drush, cron, admin form) for removing orphaned taxonomy term references from entities.
* Field reference delete (sandbox only)

> This module removes references to a deleted entity from fields stored in an SQL database. It exists to prevent stale references to non-existent content from causing unexpected problems (for example, when the referencing content is being displayed).

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


# Question
Title: Is it good practice for a module to add fields to a certain content type?
I have a content type of "album" that is used for displaying reviews of music albums. It has fields like "artist", "genre", "publication\_date", etc.

I also have a supporting module that displays relevant albums (that can be purchased elsewhere) for this content type using a 3rd party web service. This module requires a few extra values, like the limit of the relevant albums to be displayed, or a unique id for the artist for the web service.

Is it a good idea to have the module add these extra fields at installation time?

# Answer
Not only is it a good idea, it is the result of the generally recommended workflow when working with custom content types. If you have other business logic that depends on those fields, I would definitely make them available at install time to make deployment painless.

The Features module can be used to export fields, content types and other configuration into a separate module for you to download, so you do not have to write this yourself. By exporting your configuration to code, it becomes possible to check it into revision control, providing the basis of more complex Drupal modules and distributions.

The KIT specification referred to by Letharion provides a standard for how feature modules (those exported by Features) should be structured for maximum interoperability and portability, but it is the Features module that does the heavy lifting (note, however, that modules created by Features do not name Features as a dependency). Obviously, not every feature you create has to be KIT-compliant, though it does provide a good starting point with a series of sane best practices.

Whether it makes more sense to simply modify the feature module (it is a module like any other, after all!) or make it a submodule of another project depends on the specific use case. If I understand yours correctly, both your supporting module and your content type are used in conjunction to satisfy the same single use case, so I would consider merging them together. Generally, you would make the feature module stand-alone if it could be used independently and satisfies some use case on its own, which does not appear to be the case.

If you have any questions, I would be happy to clarify my answer.
> 2 votes

# Answer
Sounds like the sort of requirement that KIT was created for.

Basically, you

1. Read the KIT spec.
2. Create the fields you need, keeping what you learning from 1 in mind.
3. Export them in a Feature
4. Extract the feature as a module inside the supporting module. You should now have a "sub-module".
5. Add relevant dependencies to the three modules.
> 1 votes

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


# Question
Title: Possible to show 'Request new password' tab with LoginToboggan 403 login page?
I'm using the LoginToboggan module to password protect a page. A login area successfully shows on the page in question, but there are no tabs, only a username and password box.

Here is what it looks like:

This is what the I want it to look like (screenshot taken from /user on same site):

I can't see any option for it in the configuration (here is what I have currently as config under the login section):

I can't find anything relating to this in the LoginToboggan issue queue or via google. Has anyone experienced this? Is there any way I can make the tabs display?

P.s. I was going to log a support request on the issue queue of LoginToboggan but I saw the following statement:

```
Support requests will only be responded to if they deal with the development of the
module, or possibly its use with another module. End users should consult the forums or
IRC chat rooms or hire a consultant for support.

```

# Answer
> 2 votes
When a page is forbidden, logintoboggan pulls the login form via the following code:

```
drupal_get_form('user_login');

```

For some reason, which I haven't figured out, calling `user_login` doesn't include the links to 'reset password' and 'create new account'. I've submitted a patch to the module, which adds an option in the configuration to include the 'forgot password' and 'create account' links. It uses `user_login_block` instead of 'user\_login' to render the form with the 'forgot password' and 'create account' links.

Here is a screenshot of the admin area:

Here is a link to the issue that contains the patch: Add lost password link to 403 login form

Edit: I think the reason that the tabs for 'Request new password' and 'Create new account' aren't displayed, is that they are MENU\_LOCAL\_TASK's on the 'user' page. Logintoboggan redirects to 'toboggan/denied', so the tabs aren't being pulled in.

# Answer
> 1 votes
That page is controlled by a theme function theme\_lt\_unified\_login\_page() and theme functions can be overridden. That's probably how I would do it.

---
Tags: 7
---


title: Empty a field when it is disabled

text:
# Question
Title: Empty a field when it is disabled
I am using `#state` values in a `hook_form_alter()` to disable field\_2 if field\_1 (a checkbox) is checked. It works and all is good.

Now I want to empty field\_2 as well. I cannot see a way to do that with the `#state`.

How can I make sure that values don't get saved for fields that are conditionally disabled, even if the user enters a value first?

# Answer
> 0 votes
After a little digging, it seems there is no way to empty a field (except for a checkbox --- 'check' and 'uncheck' are supported by `#states`, but no other value changes) that is disabled. What I ended up doing was hiding the fields when other fields had value. That way, when the user removes the value and then enters a value in another field, the first field is saved as empty (instead of with its previous value) and the second field's value is saved normally.

# Answer
> 0 votes
Interesting question. Since the `$form_state` variable is passed by reference to all form validation & submit handlers, you can modify it prior to it reaching the submit handler that saves it. What about adding a new validation handler that will empty the `$form_state['values']['field_2']` value if the field is disabled in `$form`? That should ensure that the field is empty by the time anything tries to save it.

---
Tags: forms
---


title: using drupal_process_states()

text:
# Question
Title: using drupal_process_states()
I'm trying to add dependencies to a set of fields, such that only one of the set can ever contain a value at any given time.

I see that `drupal_process_states()` does pretty much what I want, but I'd have to define it separately for each element. It looks like I'd be using it with `hook_field_widget_WIDGET_TYPE_form_alter()`, since that takes `$elements` as an argument?

Is there anything that might simplify this? Specifically, is there a function that can apply rules per fieldset rather than per widget?

# Answer
I think I was confused about what `drupal_process_states()` does. It does not have to be declared like a hook or even invoked in my custom module. It is simply the machinery behind `#states` in the FormAPI. Simply using a `hook_form_alter()` and adding a `#states` array to the relevant fields is enough.
> 1 votes

---
Tags: javascript
---


# Question
Title: Are there any alternate module for qq_import module (Quiz Questions Import Module)?
Are there any alternate module for qq\_import module (Quiz Questions Import Module) ? It seems it has no Drupal 7 version for it.

# Answer
> 0 votes
It turns our that there are some similar existing modules on D7 but not as close as qq\_import module. Instead, I just created my own custom D7 quiz question importer. It only imports multiple choice type of questions though

# Answer
> 0 votes
I have the same problem too.

I want to import my multiple choice questions from one D7 to another D7 website but there is no easy way of doing it. I have tried the Node Export module but it does not import the Multiple Choice questions with the answer choices, only the question stem is imported.

It seems like you have written your own custom module. Do you think it would help to try your module on my D7 site as well? If so, could you share some more information.

Thanks

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


title: Featurizing a role, losing permissions

text:
# Question
Title: Featurizing a role, losing permissions
I have created a role, Admin. Admin has permissions: "Assign roles" (via RoleAssign), "Access administration pages", "View admin theme", and "Administer users".

I export the role with Features (including the permissions one by one, as well as the role itself).

I delete the role in config and clear cache before enabling the feature. I enable the feature. I `drush fr adminrole` and I get `Current state already matches defaults, aborting.`

But my new Admin role doesn't have the expected permissions. Sometimes it has "Access administration pages" and "view admin theme" but it does not have "assign roles" or "administer users".

Is this a case where Features requires Strongarm? Or do I have to use Secure Permissions (which would be less than ideal because other administrators would not be able to change permissions in config anymore.)

# Answer
> 2 votes
I was confusing two different things. Because of the way Features handles permissions and roles, there are three pieces, not just two.

What I thought was happening:

1. I add Myrole to the Feature.
2. I add mypermission1, mypermission2, mypermission3, etc. to my Feature.
3. I save my Feature and user with Myrole will have mypermissions 1, 2, 3, etc.

What actually needs to happen:

1. I add Myrole to the Feature
2. I add mypermission1, mypermission2, mypermission3, etc. to my Feature.
3. I make sure that Myrole's permissions in my current config actually include mypermissions 1, 2, 3, etc.
4. I save my Feature and user with Myrole will have mypermissions 1, 2, 3, etc.

The first one exports whatever the state of mypermissions 1, 2, 3, etc. is *at the moment of the export* which means that if the role in your config does not actually have those permissions, your Feature will specify that your role **does not** have those permissions, explicitly. Backwards from what I was trying to do.

# Answer
> 1 votes
one common problem with featurizing permissions is that the roles in the source and target installs have to be identical not just in name but in ID as well. If not you may be applying permissions to the wrong roles, or to role IDs that don't exist. So the first thing is to check that both sites line up as regards the role table.

---
Tags: features, users
---


title: Alternative to Galleria module?

text:
# Question
Title: Alternative to Galleria module?
I'm trying to use the http://drupal.org/project/galleria module in conjunction with its fullscreen theme, but I get the error I pasted below, I tried many fixes but not working.

**Is there another module to show a gallery similar to this one: http://galleria.io/themes/fullscreen/**

```
Could not extract width/height from image: http://localhost/mysite.com/sites/default/files/styles/thumbnail/public/images-fullscreen/slide-1.jpg. Traced measures: width:0px, height: 0px.

```

# Answer
When this happened to one of my sites, I corrected it by upgrading to the latest version of the galleria library. There also might be an issue with your css. Several hints to track the problem down can be found here.
> 1 votes

---
Tags: media
---


# Question
Title: Filter taxonomy terms in autocomplete list by boolean field on vocabulary's terms?
I need to implement a boolean field for a vocabulary that determines whether terms within a vocabulary appear in autocomplete results for a taxonomy term reference field's autocomplete widget. The function taxonomy\_autocomplete(...) has the query that I want to modify. But how can I modify the query or override the results of the autocomplete json callback?

I know how to add the boolean field to the vocabulary but not how to filter autocomplete results. The idea is to let users enter new terms but not have their new terms appear in autocomplete results unless approved by an admin.

# Answer
The solution was to create a module that adds an 'enabled' property to term entities and implements a version of the 'autocomplete' widget with a custom callback to filter the results.

hook\_schema\_alter() tells Drupal that the entity has the new property but we have to manually add the database column in hook\_install() and remove it in hook\_uninstall().

```
/*
 * Implements hook_schema_alter() - adds boolean field to disable terms by default
 */
function term_disabler_schema_alter(&$schema) {
  $schema['taxonomy_term_data']['fields']['enabled'] = array(
    'type' => 'int',
    'unsigned' => TRUE,
    'not null' => TRUE,
    'default' => 0,
    'description' => 'Does this term appear in the enabled-only autocomplete widget?',
  );
}

/*
 * Implements hook_install()
 */
function term_disabler_install() {
  db_add_field('taxonomy_term_data', 'enabled', array(
      'type' => 'int',
      'unsigned' => TRUE,
      'not null' => TRUE,
      'default' => 0,
      'description' => 'Does this term appear in the enabled-only autocomplete widget?',
    )
  );
}

/*
 * Implements hook_uninstall()
 */
function term_disabler_uninstall() {
  db_drop_field('taxonomy_term_data', 'enabled');
}

```

The form 'taxonomy\_form\_term' is altered by the hook term\_disabler\_form\_taxonomy\_form\_term\_alter() which adds a checkboxs and a submit callback to save the value.

```
/*
 * Implements hook_form_FORM_ID_alter()
 */
function term_disabler_form_taxonomy_form_term_alter(&$form, &$form_state, $form_id) {

  $form['term-enabled'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enabled'),
    '#weight' => -1,
    '#default_value' => $form['#term']['enabled'],
  );

  $form['#submit'][] = '_term_disabler_taxonomy_form_term_submit';

}

/*
 * Submit handler saves the checkbox state with the term entity
 */
function _term_disabler_taxonomy_form_term_submit(&$form, &$form_state) {

  $tid = $form['#term']['tid'];
  $enabled = $form_state['values']['term-enabled'];

  $query = db_update('taxonomy_term_data')
    ->condition('tid', $tid)
    ->fields(array('enabled' => $enabled))
    ->execute();

  drupal_set_message($query . ' rows updated');
}

```

A custom widget with the same form and validate callbacks as taxonomy autocomplete has a different 'autocomplete\_path' pointing to a new URL. The page callback at the new URL is identical to taxonomy/autocomplete with the addition of one line when the query is being built:

```
$query->condition('t.enabled', 1);

```
> 0 votes

# Answer
Here is how I've added a new term custom widget:

```
/**
 * Implements hook_field_widget_info().
 */
function deepestlevel_taxonomy_widget_field_widget_info() {

  return array(
    'textfield' => array(
      'label' => t('deepestlevel_taxonomy_widget - Only deepest level'),
      'field types' => array('taxonomy_term_reference'),
      'settings' => array(
        'size' => 60,
        'autocomplete_path' => 'deepestlevel_taxonomy_widget/autocomplete',
      ),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_CUSTOM,
      ),
    ),
  );
}

/**
 * Implements hook_field_widget_form().
 */
function deepestlevel_taxonomy_widget_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

  $tags = array();
  foreach ($items as $item) {
    $tags[$item['tid']] = isset($item['taxonomy_term']) ? $item['taxonomy_term'] : taxonomy_term_load($item['tid']);
  }

  $element += array(
    '#type' => 'textfield',
    '#default_value' => taxonomy_implode_tags($tags),
    '#autocomplete_path' => 'deepestlevel_taxonomy_widget/autocomplete'. '/' . $field['field_name'],
    // '#autocomplete_path' => $instance['widget']['settings']['autocomplete_path'] . '/' . $field['field_name'],
    '#size' => $instance['widget']['settings']['size'],
    '#maxlength' => 1024,
    '#element_validate' => array('taxonomy_autocomplete_validate'),
  );

  return $element;
}

/**
 * Implements hook_menu().
 */
function deepestlevel_taxonomy_widget_menu() {
  $items['deepestlevel_taxonomy_widget/autocomplete'] = array(
    'title' => 'Autocomplete taxonomy deepest level',
    'page callback' => 'deepestlevel_taxonomy_widget',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

// THIS IS THE OVERRIDE CALLBACK copied from core taxonomy.pages.inc
// function taxonomy_autocomplete($field_name, $tags_typed = '') {
function deepestlevel_taxonomy_widget($field_name, $tags_typed = '') {

// NEW CODE HERE

}

```
> 1 votes

---
Tags: 7, taxonomy-terms, ajax
---


# Question
Title: Views Slideshow Contextual Filter, Show Images From Same Node
In a Content Type A I have added a image field with a value to add unlimited images.

Created nodes of Content Type A and adding multiple images to the field in all nodes of that content type.

Through Views Slideshow I have created a slideshow which is displaying all images added through that field.

Created a block display and configure that block to appear on nodes of the Content Type A.

Slide show is displaying all images added in different nodes of that content type.

I want views slideshow to display the images in context to the node it is appearing on. Means only display the images which are added on that particular node.

I think this could be achieved through contextual filters, but not sure how to do this.

# Answer
To add a contextual filter for Content:Node:Nid, configure the 'When the filter value is NOT available' by selecting 'Provide default value, and under 'Type' select 'Content ID from URL'.

Save your view and you are done.

In your case, check for the nid or entity id associated with the attached (associated) images, and relate this to the node id in the URL. If your base table is node, the Content:node:nid will work. If your base table is files, you will need to use File Usage:Entity ID.
> 1 votes

---
Tags: views
---


# Question
Title: How do I add a menu router that works even in the maintenance mode?
when a Drupal site is in maintenance mode (not due to a technical fault), users without permission cannot access any page other than `/user`.

Is there any special hook to define a specific menu router should be allowed in maintenance mode ?

I checked `user_menu` but there does not seem to be any clue about this.

# Answer
> 6 votes
You can use `hook_menu_site_status_alter()` to change the site status for a specific path.

> Control site status before menu dispatching.
>
> The hook is called after checking whether the site is offline but before the current router item is retrieved and executed by menu\_execute\_active\_handler(). If the site is in offline mode, $menu\_site\_status is set to MENU\_SITE\_OFFLINE.

The user module implements that hook (`user_menu_site_status_alter()`) to make sure the site is always online for the user, user/login, user/password and user/reset/\* paths. It should be simple enough to use the logic from that function to implement it for your custom path, e.g.

```
function MYMODULE_menu_site_status_alter(&$menu_site_status, $path) {
  if ($menu_site_status == MENU_SITE_OFFLINE && $path == 'my-path') {
    $menu_site_status = MENU_SITE_ONLINE;
  }
}

```

---
Tags: 7, maintenance-mode, routes
---


title: Views content panes link to view

text:
# Question
Title: Views content panes link to view
I have a view with multiple content panes and multiple pages. With the content pane, I have used the feature "Link to view" before to get the title of the pane to link to the page view. When using this before, there has only been one pane and one view, which has worked well.

Now I would like to link multiple panes up to different pages within the same view. When selecting "yes" in "Link to view", it always links to the first page. Is there a way to specify which page I would like to link my panes to?

# Answer
> 1 votes
Ok, I figured out you can directly insert html into view titles and it will work. Wrapping the different view panes in an `<a>` tag solved the issue.

---
Tags: views, panels
---


# Question
Title: Finding out if panelizer displays are in use
Does Drupal keep track of exactly *where* panelizer display(s) are in use? Basically, I would like to identify all pages across content types that use a particular display.

Is this information stored? Is there a way to get it programmatically or via the UI?

# Answer
This info is not saved in the theme registry, and it's not really available per page or per node. However, it is stored per configured Panels display. Many don't have a title but since I'm using Panelizer, they do have a Panels display ID. Here's a query that returns those:

```
select did, title from panels_display where layout = 'mytemplate';

```

Entity IDs correspond to DIDs in the panelizer\_entity table. Once you have queried for the DID you can query for the entity ID using the DID, like so:

```
select entity_id from panelizer_entity where did = 1234;

```

Where you replace '1234' with the DID you got from the previous query.

I have to do that second one for each DID that the first one returns in order to find all entities using mytemplate.
> 2 votes

---
Tags: theming, panels
---


# Question
Title: How to switch from using a theme function into using a template?
there's a part of a page that I want to theme, and it's currently themed by a theme function (theme\_hook). How do I change it to use a template instead? Does it have something to do with hook\_theme\_registry\_alter?

If it is that hook, I checked the variable passed in hook\_theme\_registry\_alter and I'm not sure what exactly to alter. Do I just add a 'template' key? Or do I have to also unset something? How does it know whether to use a template or theme function anyway?

I'm in Drupal 7 by the way.

# Answer
> 1 votes
As described in the documentation for hook\_theme(), the property that you need to provide in order to use a template file instead of calling the theme function is *template*.

> **template**: If specified, this theme implementation is a template, and this is the template file without an extension. Do not put .tpl.php on this file; that extension will be added automatically by the default rendering engine (which is PHPTemplate). If 'path', above, is specified, the template should also be in this path.

As you are altering the theme function implemented from another module, you are probably interested in setting also the *path* property.

> **path**: Override the path of the file to be used. Ordinarily the module or theme path will be used, but if the file will not be in the default path, include it here. This path should be relative to the Drupal root directory.

---
Tags: 7, theming
---


# Question
Title: Sanitizing strings before adding as taxonomy term
I am programatically creating taxonomy terms from a JSON object. I have a simple script that iterates over the converted JSON, and creates a taxonomy hierarchy. Since these terms come from a client-generated CSV they have random spaces and characters in them I want to sanitize/normalize them before I add them using `taxonomy_vocabulary_save()`

I've looked at the list of drupal Sanitization Functions, but those all seem to deal with HTML/JS strings. Is there a drupal way for me to format these strings, or should I just use a PHP regex to do it?

# Answer
Running the text through `check_plain()` will sanitize anything dangerous, giving you the same result you'd get if you were to input the same title as part of the normal 'create term' process via Drupal's UI. I'd also run it through `trim()` to get rid of preceding/trailing whitespace. Beyond that, yes, you might need to do some custom regex to clean up things in your data, but that's impossible to say without seeing your data.
> 6 votes

# Answer
You should use PHP regular expressions along with Drupal sanitization functions.
> 0 votes

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


# Question
Title: How can I print Views language-specific $field variable values inside a views template?
I am using Views with "Format Show:Content" instead of "... fields."

I have a multilingual website. In the filters section of Views I have Content: language = user's default language. However, Views refuses to honor this filter selection.

I am also using views-view-fields.tpl.php file to output the fields. currently it is calling, for example, $fields-\>content to output content.

How can I get Views in Show Content format to honor the language filter? I am familiar with needing to add the 'und' key to certain fields at times, but do I need to do that here? Should adding the filter in the view not be enough? If I do need to add the key where does it go?

If you want, you can see the error in the slideshow at http://goniseko.com

# Answer
Use dpm() to output $field in your template.

To make PHP not die with an out of memory error, use a static flag to ensure it only prints once.

```
static $_foo;
if (!$_foo) {
  dpm($field);
  $_foo = TRUE;
}

```
> 1 votes

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


# Question
Title: How do I show or hide a Views block based on a boolean field in the displayed node?
I have searched and searched for an answer to this, so hopefully I'm not asking something that is answered elsewhere.

I have a content type with a boolean field that show or hide a form. On each of that content type node pages, I want to show a block if the boolean field is set to true.

So, in essence, the boolean on the content type tells whether or not to show the block.

Right now I have the form (via the Webform Module) displaying as a block using Views. I think I can set a contextual filter to determine if the block is shown or not, but I am having a ton of trouble getting it to do that.

So, how do I set up contextual filters to show the block if a boolean field is set in the content type to true and not if it's false?

# Answer
> 1 votes
Forget views.

Go to the visibility settings for the block (under /admin/structure/block) and set the Page Visibility to only show on "Pages on which this PHP code returns TRUE".

Then check your boolean field with the following code:

```
$node  = menu_get_object();

return (isset($node->field_boolean[LANGUAGE_NONE][0]['value'])) ? $node->field_boolean[LANGUAGE_NONE][0]['value'] : FALSE;

```

Then place the block on the page where you want it.

# Answer
> 0 votes
This over kill for your particular use case, but the Panels module offers one way to do this.

With Panels, you can override the display of all nodes. On this overridden display, you can then add the block with a **visibility condition**. You can set the **visibility condition** to only show if a block has a certain content type. In this case, you don't need the boolean field on the content type (although if you really wanted to use that for some reason, you could instead set the visibility rule to work based on that field instead of based on the content type).

---
Tags: blocks, views
---


# Question
Title: Use custom HTML file for page created by Views?
I use Views to create new content and a new page for the content, but how am I supposed to customize the HTML layout of the page? I can style elements of the page via CSS, but what if I wanted to have my own CSS3 (animated sprite) elements? For example, most CSS3 sprites require you to have divs contained in a specific manner, but those divs are not present in a Views created page and I see no viable way to manually add them? How would I go about doing this?

# Answer
When you edit the View, under the Advanced settings on the right-hand side you should see "Theme information". If you click that it will give you the content of the theme templates for the View, which you can then override by copying into your theme, in a file with a corresponding name.
> 2 votes

---
Tags: views, theming
---


title: Proper javascript notation

text:
# Question
Title: Proper javascript notation
The following code creates navigation links for a Twitter Bootstrap carousel. The script runs perfectly when saved on my local machine as well as hosted as its own document. When placed into a Drupal page, however, the javascript is modified. I understand that Drupal requires a special Javascript structure. Is that the case with my code below? Any suggestions would be helpful. Thanks!

--- You can see how Drupal closes tags on Line 10

Original Code - working:

```
$(document).ready(function() {
    $('#headerCarousel.carousel[id]').each(function() {
        var html = '<div class="nav-collapse collapse" data-target="' + $(this).attr('id') + '"><ul class="nav">';
        for(var i = 0; i != $(this).find('.item').size(); i ++) {
            html += '<li';
                if(i == 0) {
                    html += ' class="active"';
                }
            var item = $(this).find('.item').get(i);
            html += '><a href="#" data-toggle="collapse" data-target=".nav-collapse.in">'  + $(item).attr('data-title') + '</a></li>';
        }
        html += '</ul></li>';
        $('.btn-navbar').after(html);
        $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').hide();

    }).bind('slid', function(e) {
        var nav = $('.nav-collapse[data-target="' + $(this).attr('id') + '"] ul');
        var index = $(this).find('.item.active').index();
        var item = nav.find('li').get(index);
        nav.find('li.active').removeClass('active');
        $(item).addClass('active');

        if(index == 0) {
           $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').fadeOut();
        } else {
           $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').fadeIn();
        }
        if(index == nav.find('li').size() - 1) {
           $('.carousel-control.right[href="#' + $(this).attr('id') + '"]').fadeOut();
        } else {
           $('.carousel-control.right[href="#' + $(this).attr('id') + '"]').fadeIn();
        }
    });

   $('.bootstrap .nav a').bind('click', function(e) {
       var index = $(this).parent().index();
       var carousel = $('#' + $(this).closest('.nav-collapse').attr('data-target'));
       carousel.carousel(index);
       e.preventDefault();
   });
});

```

Generated code after placing in Drupal - broken:

```
$(document).ready(function() {
    $('#headerCarousel.carousel[id]').each(function() {
        var html = '<div class="nav-collapse collapse" data-target="' + $(this).attr('id') + '"><ul class="nav">';
        for(var i = 0; i != $(this).find('.item').size(); i ++) {
            var item = $(this).find('.item').get(i);
            html += '<li><a href="#" data-toggle="collapse" data-target=".nav-collapse.in">'  + $(item).attr('data-title') + '</a></li></ul>';
        }
        $('.btn-navbar').after(html);
        $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').hide();

    }).bind('slid', function(e) {
        var nav = $('.nav-collapse[data-target="' + $(this).attr('id') + '"] ul');
        var index = $(this).find('.item.active').index();
        var item = nav.find('li').get(index);
        nav.find('li.active').removeClass('active');
        $(item).addClass('active');

        if(index == 0) {
           $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').fadeOut();
        } else {
           $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').fadeIn();
        }
        if(index == nav.find('li').size() - 1) {
           $('.carousel-control.right[href="#' + $(this).attr('id') + '"]').fadeOut();
        } else {
           $('.carousel-control.right[href="#' + $(this).attr('id') + '"]').fadeIn();
        }
    });

   $('.bootstrap .nav a').bind('click', function(e) {
       var index = $(this).parent().index();
       var carousel = $('#' + $(this).closest('.nav-collapse').attr('data-target'));
       carousel.carousel(index);
       e.preventDefault();
   });
});

```

# Answer
> 1 votes
Behavior handling has changed again in Drupal 7, with modules now required to explicitly define their attach handler, and optionally specify a detach handler. add code like this way.

```
(function ($) {

  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
    $('#headerCarousel.carousel[id]').each(function() {
        var html = '<div class="nav-collapse collapse" data-target="' + $(this).attr('id') + '"><ul class="nav">';
        for(var i = 0; i != $(this).find('.item').size(); i ++) {
            var item = $(this).find('.item').get(i);
            html += '<li><a href="#" data-toggle="collapse" data-target=".nav-collapse.in">'  + $(item).attr('data-title') + '</a></li></ul>';
        }
        $('.btn-navbar').after(html);
        $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').hide();

    }).bind('slid', function(e) {
        var nav = $('.nav-collapse[data-target="' + $(this).attr('id') + '"] ul');
        var index = $(this).find('.item.active').index();
        var item = nav.find('li').get(index);
        nav.find('li.active').removeClass('active');
        $(item).addClass('active');

        if(index == 0) {
           $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').fadeOut();
        } else {
           $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').fadeIn();
        }
        if(index == nav.find('li').size() - 1) {
           $('.carousel-control.right[href="#' + $(this).attr('id') + '"]').fadeOut();
        } else {
           $('.carousel-control.right[href="#' + $(this).attr('id') + '"]').fadeIn();
        }
    });

   $('.bootstrap .nav a').bind('click', function(e) {
       var index = $(this).parent().index();
       var carousel = $('#' + $(this).closest('.nav-collapse').attr('data-target'));
       carousel.carousel(index);
       e.preventDefault();
   });

    }
  };

})(jQuery);

```

---
Tags: javascript
---


# Question
Title: Inserting images and preventing the layout from breaking
The client has asked for an auto resize of images (when inserting via the ckeditor) so to avoid the breaking of the layout, and including images that are just too big. Is there a way to automate this process? Do you normally offer this? Or do you just make the client aware of the width and height settings in the image properties window?

# Answer
There are several ways of handling images inserted in a WYSIWYG editor. Which approach you take is depending on needs and how technical the client is.

If you let users set a size in the editor either by manually specifying a size or by using the mouse, then I would recommend the Image resize filter module which automatically resize images to the width and height set in the editor. This reduces load times by not loading the original image.

You can use the IMCE module for both manual and automatic resize. You can resize using width/height value, or using predefined image dimensions.

You could also simply set a `max-width` value in CSS for the images, but this might have an impact on loading times if the images are big, so I would not recommend it.

If you do some research I am sure you can come up with more options, but these would be the first that comes to mind.
> 0 votes

# Answer
Image styles are built into Drupal 7. You can define image styles to have a particular size, by either cropping, scaling, or some combination of the two. Drupal 7 also supports scaling only down but not up.

If you want to do this in Drupal 6, you do it by installing the Imagecache module and configuring your styles with that.
> 0 votes

---
Tags: media
---


title: How to make passwords case insensitive?

text:
# Question
Title: How to make passwords case insensitive?
it appears as passwords in Drupal 7 are case sensitive. Is there a way to make them case insensitive?

# Answer
The password is stored as a hash, upper/lowercase differences result in a different hash.

The only possible way I can think of is if you always convert the password to upper/lowercase before it is used, both when registering and when logging in. But that sounds error prone to me.

Also, if the passwords are already stored in the database, then there is no way to do it.
> 6 votes

# Answer
Since doing this severly limits the number of possible passwords, it would also make your passwords much easier to hack. There's a reason all password prompts elsewhere (both in operating systems and webapps) are case sensitive.
> 5 votes

# Answer
The password is stored as a hash, upper/lowercase differences result in a different hash.

There is nearly no other ways to make it work except making it in either lower or upper case before we save it.

You can use javascript or add another **form submit handler** to convert the pass to either lower or upper case before it gets saved to database.
> 0 votes

---
Tags: 7, users
---


# Question
Title: Taxonomy Filter with parents and child of select parent dropdown`s
On my website i have pet type (dog, cat, rabbit...) those are taxonomies, and every pet type has its own child taxonomies called pet breed. So lets say we selected in first dropdown dog, in second dropdown i want to list dog breeds.

I have tried with http://drupal.org/project/hierarchical\_select but i cant make it work.

I tried with Views but still my exposed filters doesnt show at all on Preview or in Block...

Any help would be nice. I tried searching but no luck...

http://www.pets4homes.co.uk/ this is what i want to acomplish same thing as that filter they have but just without taht location field.

# Answer
> 0 votes
You would like to check Simple hierarchical select module, which looks promising to work views exposed filter, if you use the same for the content type. Though I have used hierarchical select for what you are trying to do & by playing sometime you would also be able to achieve what you are looking for. Views has many things & it takes times sometimes to get what we want... You would like to check Views Hack module for the custom arrangement of block of yours..

# Answer
> 0 votes
the hierarchical select module is the correct solution for this purpose, why it does not work with you?

Setup steps:
1- add the module folder to sites/all/module
2- go to modules page and enable hierarchical select
3- add new field (Term reference) into your content type with (Hierarchical Select) widget type.

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


title: Making a new field via module

text:
# Question
Title: Making a new field via module
I've been following the Drupal example on how to create a new field. I can get their example to work fine, but when I try my own it does not seem to store any data, i.e. the field is always blank when I load the node back. I am ultimately attempting to create a field which can hold multiple pieces of information, a bit like the example three field color code. Although I would want a better storage then expanding a value into an array (I have an idea on this, but until I have the basic data storage working I cannot comment on this).

The example is here.

This is my code from the module; I have stripped the example down to the bare minimum, and I have checked it works on the color wheel code.

```
 function prodlist_field_schema($field) {
  if ($field['type'] == 'prodlist_code') {
      $columns = array(
        'prodcode' => array(
          'type' => 'varchar',
          'length' => 7,
          'not null' => FALSE,
        ),
      );
  }
  return array('columns' => $columns);
}

function prodlist_field_info() {
  return array(
    'prodlist_code' => array(
      'label' => t('Product Code'),
      'description' => t('Used to assign product codes'),
      'default_widget' => 'prodlist_text',
      'default_formatter' => 'field_example_simple_text',
    ),
  );
}

function prodlist_field_widget_info() {
  return array(
     'prodlist_text' => array(
      'label' => t('Prodcode entry fields'),
      'field types' => array('prodlist_code'),
    ),

  );
}

function prodlist_field_is_empty($item, $field) {
  return empty($item['prodlist_code']);
}

function prodlist_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $value = isset($items[$delta]['prodlist_code']) ? $items[$delta]['prodlist_code'] : 'emptyonload';

  $widget = $element;
  $widget['#delta'] = $delta;

    $widget += array(
          '#type' => 'textfield',
          '#title' => 'prodcode',
          '#size' => 23,
          '#default_value' => $value,
        );

  $element['prodcode'] = $widget;
  return $element;
}

```

# Answer
I found another great example in the book "Drupal 7 Module Development", having worked through this example I am now able to alter it to my own purposes and the data is persistent.

Below is a working 3 field example.

```
function prodlist_field_info() {
  return array(
    'productorder' => array(
      'label' => t('Product Code'),
      'description' => t('Used to assign product codes'),
      'default_widget' => 'prodlist_text',
      'default_formatter' => 'field_example_simple_text',
    ),
  );
}

function prodlist_field_schema($field) {
  if ($field['type'] =='productorder') {
      $schema['columns']['code'] = array(
        'type' => 'varchar',
        'length' => 10,
        'not null' => FALSE,
      );
      $schema['columns']['description'] = array(
        'type' => 'varchar',
        'length' => 10,
        'not null' => FALSE,
      );
      $schema['columns']['amount'] = array(
        'type' => 'int',
        'not null' => FALSE,
      );

      $schema['indexes'] = array(
        'code' => array('code'),
        'description' => array('description'),
        'amount' => array('amount'),
      );

      return $schema;
  }

}

function prodlist_field_is_empty($item, $field) {
  if ($field['type'] == 'productorder') {
    if (empty($item['code']) && empty($item['description']) && empty($item['amount']) ) {
      return TRUE;
    }
  }
  return FALSE;

}

function prodlist_field_widget_info() {
  return array(
     'prodlist_text' => array(
      'label' => t('Prodcode entry fields'),
      'field types' => array('productorder'),

    ),

  );
}

function prodlist_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $base = $element;

  if ($instance['widget']['type'] == 'prodlist_text') {
    $element['code'] = array(
      '#type' => 'textfield',
      '#title' => t('Code'),
      '#default_value' => isset($items[$delta]['code']) ? $items[$delta]['code'] : NULL) + $base;
    $element['description'] = array(
      '#type' => 'textfield',
      '#title' => t('Description'),
      '#default_value' => isset($items[$delta]['description']) ? $items[$delta]['description'] : NULL) + $base;
    $element['amount'] = array(
      '#type' => 'textfield',
      '#title' => t('Amount'),
      '#default_value' => isset($items[$delta]['amount']) ? $items[$delta]['amount'] : NULL) + $base;

  }
  return $element;

}

```
> 1 votes

---
Tags: entities
---


title: organic groups and private files

text:
# Question
Title: organic groups and private files
Hi everyone I was wondering if it's possible to have directories of files attached to an organic group so that only group members and admins can access those files. If so whats the easiest way to accomplish this? I tried to use a htaccess file in files/private/groups (the directory I want to store these files in) but to no avail.

# Answer
> 1 votes
For anyone attempting something similar I ultimately modified the user files module and used the hook\_file\_download to only allow group members to download protected content by using the built in is\_og\_group\_member function.

---
Tags: organic-groups, files
---


title: blocks forgetting region placement

text:
# Question
Title: blocks forgetting region placement
So i've run into an issue with a block somehow losing its region placement somewhat randomly. For background the block is very simple

```
        $blocks['tx_leftcol_block'] = array(
      'info' => t('Tx leftcol block'),
    );

```

The content isn't the issue, as even with some static content this block disappears.

On the blocks overview page this is placed on a custom region called tx sidebar (its a sidebar for certain pages). The weird part is other blocks show fine in this sidebar and dont lose placement, but for some reason this block gets disabled randomly, i.e. every couple of login/logouts it hides, or after a certain amount of time.

Any ideas what could be the cause?

# Answer
> 0 votes
It turned out to be a caching issue which i resolved by suing the block\_flush\_caches method.

---
Tags: blocks
---


# Question
Title: Custom form: How to implement a module's field widget
In my custom form I have a file upload, which follows the array structure of `file_element_info()` in file.module in core. This is consistent with examples in examples module and date module has `_date_api_element_info()`.

But looking at geofield or at openlayers and other modules I can not see what array values are possible/required.

As a general rule how do I find out how to add a field of a specific type to a custom form?

---

**Edit #1:** Just read Where can I find complete documentation of hook\_field\_info? and everyone is being really helpful about Field API, but it is a steep learning curve. A specific example would really help (an not one of the simple core field types).

---

**Edit #2:** So on my particular example in `geofield.module` I got (got the same using `dpm(field_info_field_types('geofield'));`):

```
function geofield_field_info() {
  return array(
    'geofield' => array(
      'label' => 'Geofield',
      'description' => t('This field stores geo information.'),
      'default_widget' => 'geofield_wkt',
      'default_formatter' => 'geofield_wkt',
      'instance_settings' => array(
        'local_solr' => array(
          'enabled' => FALSE,
          'lat_field' => 'lat',
          'lng_field' => 'lng',
        ),
      ),
      'property_type' => 'geofield',
      'property_callbacks' => array('geofield_property_info_callback'),
    ),
  );
}

```

But how does that translate to a form field array?

```
$form['location'] = array(
    '#title' => t('Location'),
    '#type' => 'geofield',
    '#required' => TRUE,
);

```

Or do I have the wrong end of the stick here?

# Answer
In addition to the info posted by @Clive I think it's important to note that this problem can be addressed the other way round\[\*\]: create a node type (or other entity type) with the required fields, and capture the data to process it as you wish when the content is saved.

To do this you would:

1. Create a custom content type (or other entity type) with the fields you need ;
2. Implement hook\_form\_alter to modify your form if you need special features that are not provided by normal content type forms.

From there it depends what you want to do. If you want the content saved (so that it is stored), and want to process the data after it has been saved, then you could implement hook\_entity\_insert. If you also want to process the data before it is saved, you could add your own submit handler in hook\_form\_alter as such:

```
array_unshift($form['actions']['submit']['#submit'], 'my_submit_handler');

```

If you want the data after it is submitted, but don't want it saved, you could replace the submit handler with your own:

```
$form['actions']['submit']['#submit'] = array('my_submit_handler');

```

\[\*\] I realise I'm not answering the *question*, but I'm offering a solution to the *problem* :)
> 3 votes

# Answer
Further to Alice's answer, you could also create your own Entity type and add fields to its instances. This may seem pretty daunting but the Model Entities module does a pretty good job of providing sample implementations of all the entity hooks.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: node-edit-protection module not working in CK Editor window
I am using node-edit-protection module to alert a user if they are navigating away from a modified Node Edit form without saving. It worked fine if we edit title or any other fields. But not worked if we change the body part. I am using CKeditor in body part.

# Answer
> 2 votes
Open `node-edit-protection.js` file in module's folder, Find this code

```
window.onbeforeunload = function() {
     if (edit && !click) {
     click = false;
            return (Drupal.t("You will lose all unsaved work."));
     }
}

```

replace above code with following

```
    window.onbeforeunload = function() {
    if (typeof(Drupal.settings.ckeditor) != 'undefined' && typeof(CKEDITOR) != 'undefined' && typeof(CKEDITOR.instances) != 'undefined') {
         for (var i in CKEDITOR.instances) {
          if (CKEDITOR.instances[i].checkDirty()) {
           edit = true;
           break;
          }
         }
        }

         if (edit && !click) {
          click = false;
          return (Drupal.t("You will lose all unsaved work."));
  }
}

```

---
Tags: 7, wysiwyg
---


# Question
Title: Which table does the Phone module store data in?
I have installed the Phone module to create a field to take input data as mobile number.

I would like to fetch the mobile number back from database to be displayed in a block. I am not getting the table in which the phone number is stored. So in which table is the phone number data is stored?

# Answer
If this module defines a field, then the table is named after that field. So if your field is called field\_phone, the table is called "field\_data\_field\_phone". However, getting the value direct from the database is not the right "Drupal way" to do it.

You say you want to display the phone number in a block, but I assume this is within a specific context, such as on a page for a node or user. One way to do this would be to use the Views module to define a block with whatever fields you wish to display, using a contextual filter to get the node or user ID from the page arguments.

But more information is needed in order to say whether this is the right answer or not.
> 1 votes

---
Tags: 7, database
---


# Question
Title: Return a view's total_rows in Drupal 7 without php filter?
Is it possible to list the total number of rows in a view into the header of the view, without enabling the PHP filter? I know I can enable the PHP filter and output $view-\>total\_rows in a header, but I'd like to avoid enabling the PHP filter.

I could use the output $view-\>total\_rows in a template file but is there an existing handler or other trick I'm missing?

# Answer
> 26 votes
On my D7 site with php-filter disabled ...

From a View configuration page: HEADER section, add, Global Result Summary

pick total row count or whatever, whatever you want:

```
You may use HTML code in this field. The following tokens are supported:
@start -- the initial record number in the set
@end -- the last record number in the set
@total -- the total records in the set
@name -- the human-readable name of the view
@per_page -- the number of items per page
@current_page -- the current page number
@page_count -- the total page count

```

# Answer
> 1 votes
I found this tutorial for Drupal 7 that displays the number of items and showing x-x items in Views. This is for Drupal 7 which lets you display number of pages in Views.

---
Tags: 7, views
---


title: How to Add DOCTYPE?

text:
# Question
Title: How to Add DOCTYPE?
In Css `Child selector` is not working in `IE 7` and `IE 8`. I google this problem and found that after adding a `DOCTYPE` it will solve. I add a `DOCTYPE` in `maintance.tpl.php` but it is not showing in souce. How to add it?

# Answer
> 0 votes
It depends on the version of Drupal you are using. On Drupal 6, you include all of the html document information in your page.tpl.php file. In Drupal 7 all of the document information is inherited from html.tpl.php in the core Drupal framework unless you create your own html.tpl.php.

---
Tags: 7
---


# Question
Title: How do I change the HTML structure of the primary links in Drupal 7?
I read what reported in How do I change html structure of menu (primary links for example) to my own? but the accepted answer for that question is for Drupal 6.

How do I create a function that adds a CSS class or ID to a single "li" and "sub li"?

# Answer
> 2 votes
It's useful to refer to the API documentation when you have an idea of what to do in version 'X' of Drupal and you want to translate the method to work in version 'Y'.

In this instance, the following API page will prove useful:

http://api.drupal.org/api/drupal/includes--theme.inc/function/theme\_links/7

# Answer
> 0 votes
I found the solution here to change the primary menu links in Drupal 7

http://www.webmediahutch.com/customizing-primary-menu-links-drupal-7

---
Tags: theming, routes
---


# Question
Title: My MYMODULE_config_preprocess_node(&$variables) is not displaying my variables
I have 2 modules both implementing the same hook: hook\_preprocess\_node()

What I do is basically the same in both:

```
function MYMODULE_preprocess_node(&$variables) {
    $stuff_to_display = $variables['myfield'];
    $output = '';

$variables['my_stuff'] = $output;

}

```

When I use a debug function I can see my variable (my\_stuff) there but is not rendering on the page

While is working for the first module is not working for the other.

# Answer
> 0 votes
I think you're halfway there! The thing is that it isn't enough just to set the variable in the preprocess function, now you have to go one step further and output it in your tlp.php template file.

So, find the correct template file in your theme that you want to use (is it a general node.tpl.php one or a one for a specific content type like node--article.tpl.php), and edit it to actually output the variable you've set.

So, in the tpl.php file you're using, you should have something like:

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

```

Otherwise, you've set the variable, but never display it. Does that make sense? Is that what's going on in your case?

---
Tags: theming
---


title: Create a 'universal' reusable View?

text:
# Question
Title: Create a 'universal' reusable View?
Is it possible to create a View that essentially a skeleton, and can be reused over and over again (on different parts of the site) simply using different input i.e. something like different node ID's?

I want to be able to create a new Views Slideshow Gallery (The gallery is a jQuery slider) just by adding content to my custom content type, Photos. The way I have it set up now, I have to create a new Photos content type, keep it not published, and then plug that Node ID to a brand new View using the Views Slideshow formatting. As you can imagine this is quite a laborious task.

This question has applications outside my specific uses. The core question is, can you create a (dynamic?) view that will automatically take different inputs for use in a content type?

# Answer
What you may be looking for is "Contextual Filters"

Here's a good tutorial I have that explains how to implement them:

http://www.youtube.com/watch?v=lJFMTDuaxy8

There's also a way to call a View directly from a template, which can be pretty useful in some cases:

```
views_embed_view("slideshow_gallery", "page", array() );

```
> 3 votes

# Answer
Contextual filters is what youre looking for.

You can declare them when rendering a view programmatically (views\_embed\_view?).

However, obviously this depends by how deep and specific are your needs
> 1 votes

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


# Question
Title: What's a good access module for a state-level organization?
I'm setting up a new website for the Maine Grand Chapter of the Order of the Eastern Star. My goal is to allow each chapter to access their own chapter's node (and nobody else's) and modify the content (annual updates to officers, calendars, etc.) and hopefully also to maintain a group calendar (modules for this yet to be chosen). So, my question at the moment is what the best node access module to use for this purpose is. I'm using D7.20. Flexi access looks interesting, but there are so many to choose from...

# Answer
You should look at the Organic Groups module. This will allow you to designate individual users as responsible for the each group, and will allow each chapter to post content to their own chapter (kind of a mini web page for each chapter).

You can see an example of this format here.
> 1 votes

---
Tags: users
---


title: Panels with 4 or more columns

text:
# Question
Title: Panels with 4 or more columns
Is it possible to create a panel with 4 or more columns? The sample templates in the Panel module only go as far as 3.

# Answer
> 0 votes
Yes If panel setting restrict you to go beyond 3 column you can place panels in panels.

# Answer
> 2 votes
You could also define your own 4-column panel. There are instructions here: Panels 3: Creating a custom layout in your theme, and a more specific tutorial available here: Creating a four column layout for Panels 3 in Drupal 7.

# Answer
> 0 votes
You can create as many regions as you which and use CSS/HTML to place them where you want. You have to define the regions in the planel declaration to make it work.

---
Tags: panels
---


# Question
Title: Filter the Node Locations view in the navigation menu
I'm using Gmap Views to show where each Eastern Star Chapter in Maine is, both extant and historical. The automatic Node Locations map in the Navigation menu is displaying them correctly so far. What I would like to do is filter this so only nodes of type "chapter" are displayed, and preferably only ones marked as "active", although I won't generally have an exact geocode for the inactive ones. Thanks!

(This is very similar to a question I asked before, but it didn't get much input, so I'm asking it a different way this time.)

# Answer
> 0 votes
Set up a taxonomy vocabulary (eg Status) with the terms 'active' 'closed' etc, and attach a term reference to the node.

Then filter your view on the term. Have a look at Filter map to show single taxonomy or single content type.

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


# Question
Title: How do I set the path to a custom view style template?
I have created a custom view style in a module. It shows up in the list of view styles, but when I try to output the resulting block I get the message:

> Warning: include(/var/www/core/modules/views/templates/mymodule-list.tpl.php) \[function.include\]: failed to open stream: No such file or directory in theme\_render\_template() (line 1491 of core/includes/theme.inc).
>
> Warning: include() \[function.include\]: Failed opening '/var/www/core/modules/views/templates/mymodule-list.tpl.php' for inclusion (include\_path='.:/usr/share/php:/usr/share/pear') in theme\_render\_template() (line 1491 of core/includes/theme.inc).

This obviously is trying to find my view template in the templates folder of the view module, but I want it to look in `/sites/default/modules/mymodule/templates/`.

My plugin class annotations look like this:

```
/**
 * Style plugin
 *
 * @ingroup views_style_plugins
 *
 * @Plugin(
 *   id = "mymodule",
 *   title = @Translation("My Module"),
 *   help = @Translation("Help text"),
 *   theme = "mymodule-list",
 *   path = "sites/default/modules/mymodule/templates",
 *   type = "normal",
 *   module = "mycarousel"
 * )
 */

```

I have also tried setting the path in `hook_theme`:

```
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'mymodule' => array(
      'variables' => array(),
      'path' => drupal_get_path('module', 'mymodule') . '/templates',
      'theme' => 'mymodule-list',
      'theme path' => drupal_get_path('module', 'mymodule') . '/templates',
    ),
  );
}

```

Can anyone see what I'm doing wrong?

# Answer
> 3 votes
I think instead of `path = "sites/default/modules/mymodule/templates"` you should have `theme path = "sites/default/modules/mymodule/templates"`.

---
Tags: 8, views
---


# Question
Title: Using custom CSS3/HTML on generated pages?
I created new pages on my (soon to be) photography website using Panels and Views. I want to have my own hover effects for pictures on my albums page. How am I supposed to use custom HTML and CSS3 animations like those found hereon these images which are loaded by modules such as Panels and Drupal which are basically creating their own markup on the page load i.e. not in hard coded files which I can add markup to.

# Answer
You can override the views template and create your own template/markup to achieve what you want. You can read more on how to achieve that here: http://drupal.org/node/1089656
> 0 votes

---
Tags: views, panels, theming
---


title: Views, Filter based on part of url

text:
# Question
Title: Views, Filter based on part of url
I have a content type: "artist\_news" which has an entity reference to "field\_artists". So that when you create a news story you attach it to an artist.

the url for this might look like this: /artists/picasso/news/my-news-item

I am trying to create a view block, to appear on the page "/artists/picasso/news/" that shows all news "artist\_news" items that reference any given artist (e.g. picasso)

I cannot figure out how to exactly structure it. I suspect I need to use contextual filters but the exact settings of contextual filters is escaping me.

Thank you in advance for your help.

# Answer
That is just your pretty URL. Your actual url is something like this node/52.

So in your contextual filters, choose provide default argument and then select the content id from the URL. Views will pull in the 52 number for your referenced entity and that will filter your block accordingly.

**UPDATE** Since you are manually creating your URLs, and idea here would be to grab the first and second element from your path. I do not recommend this. I would recommend you adding another field to reference the artist on the news basic page so you can use that value in your contextual filter. Anyway here is what you could do.

In the contextual filter, when providing a default value, use the PHP filter and add something like this to return the value of the NID of the artist.

```
$path = drupal_get_path_alias($_GET[‘q’]);
$path = explode(‘/’, $path);
// This path should be something like artists/picasso
// The idea here would be to get the artists node path
// and then retrieve the node id from that.
$node_artist_path = drupal_get_normal_path($path[0].'/'.$path[1]);
// ^ should return something like node/33
$nid = arg(1,$node_artist_path);
return $nid;

```

This will return the value of nid from the artists main path. **AGAIN** I do not recommend this as its very dependent on path aliases.

Also I did not test any of this code, I may have some functions wrong and if I do let me know and I will update it, this is all from memory.
> 0 votes

---
Tags: views
---


# Question
Title: how to make unique fields in profile type in drupal 7
I am using drupal 7 and want to save unique mobile number for users. I have created a profile type field of phone number type.I have installed unique field module but not getting any option to make it unique while editing the phone number type field. I want make it a unique so there will be one mobile number for only one user.So how can we make a unique field in a profile types? Or will we have to make a unique field in a database itself??

# Answer
> 2 votes
You can use the http://drupal.org/project/field\_validation for unique validation. When this module is enabled, there is a validation tab for each fields in content type. If you want to validate the unique value. Just go validation tab and click on the "Unique values", do some configuration, the unique value rule will be applied for current field.

# Answer
> 0 votes
This is by design in the unique\_fields module, they only provide this functionality for content types, not profile fields according to the maintainers: http://drupal.org/node/476064. They suggest writing your own validation hooks:

> To implement a uniqueness requirement for Drupal profile fields, you would probably use hook\_user() to add extra validation (comparing the submitted value against other existing values) for the profile fields you want to be unique.

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


# Question
Title: Can I make a Views "Rendered Node" field not be linked to the original node?
I have a view that outputs rendered nodes. Setting "Show: Rendered Entity" doesn't work, because I need to add other things like edit links and custom text. So I set "Show: Fields" and used a "Rendered Node" field to output the node contents alongside everything else I needed.

The problem is that Views brilliantly wraps the entire node contents in `<a></a>` tags and links it to the node's page! This would be fine if I were just showing the titles, but I'm showing the node's entire rendered contents, with all sorts of `<div>`s and *other links that need to work* and other things.

Is there a way to make it not do that? There's no option for it in the field settings and I can't find where in the Views module this field is implemented.

Alternately, is there another way I can show a list of rendered nodes alongside other fields without them being stupidly linked in unconfigurable ways?

# Answer
> 0 votes
Turns out there *is* an option for it in the field settings, but there's a bug in the user interface. If you have `Display` set to "Show complete entity", the only sub option that appears is `View Mode`. However, if you set `Display` to either of the other options, a new checkbox appears: `Link to entity`. **This option applies to all three `Display` options**, not just the two on which it appears. Turn off the checkbox and set `Display` back to "Show complete entity", and you're done.

# Answer
> 0 votes
This happens because whenever Drupal renders a node someplace other than the node's page (for example, /node/12345) it will include the title as a link to the node itself. This is done in modules/node/node.tpl.php:

```
<?php if (!$page): ?>
  <h2<?php print $title_attributes; ?>>
  <a href="<?php print $node_url; ?>">
  <?php print $title; ?></a></h2>
<?php endif; ?>

```

To stop this from happening in your view when using the rendered node as a field, you probably want to tweak the view field template. If you override node.tpl.php in your theme, other displays of nodes (for example, the default front page) will stop working as you expect.

I did this in views-view-field--test--rendered-entity.tpl.php using preg\_replace:

```
$output = preg_replace('@(<header class="node-header">\s+<h1 class="node-title"[^>]*>\s+)<a[^>]*>([^<>]*)</a>(\s+</h1>\s+</header>)@', '$1$2$3', $output);
print $output;

```

Note that the exact regex will depend on the theme you're using. This is for an Omega subtheme.

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


# Question
Title: Why are users seeing edit pages outside of Admin UI
I just tested the editorial process for authors on our new web site. For some reason, although admins and editors see pages in the normal Admin UI (using the *Seven* theme) when editing a page, members of the author role see it in the public UI that displays for non-logged-in users browsing the web site.

At `/admin/appearance` I have **Administration theme** set to *Seven*, and I have 'Use the administration theme when editing or creating content' checked.

Why would this setting take effect for admins and editors, but not authors?

# Answer
> 2 votes
D'oh. I somehow missed this before in the permissions:

`View the administration theme`

Admins and editors had this permission enabled, but authors did not. Enabling it for authors fixed things.

---
Tags: 7, theming
---


# Question
Title: How can I upload 1000s of nodes per hour to a live drupal 7 site and avoid deadlocks?
Not too long ago I wrote about deadlock here: PDOException: SQLSTATE\[40001\]: Serialization failure: 1213 Deadlock found when trying to get lock;

Despite everything my development team tries to do, we still get errors like this:

> PDOException: SQLSTATE\[40001\]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction: INSERT INTO {location\_instance} (nid, vid, uid, genid, lid) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4); Array ( \[:db\_insert\_placeholder\_0\] =\> 1059 \[:db\_insert\_placeholder\_1\] =\> 1059 \[:db\_insert\_placeholder\_2\] =\> 0 \[:db\_insert\_placeholder\_3\] =\> cck:field\_item\_location:1059 \[:db\_insert\_placeholder\_4\] =\> 1000 ) in location\_save\_locations() (line 974 of /var/www/website.com/sites/all/modules/location/location.module).

Despite the specific table in that example, we get this error on other tables.

Here is my situation. I have taken a large University project. At any given time there are 50,000 campus residents who use the system daily. In addition to that, I am migrating 100s of 1000s of items of content both manually and through custom module code (migration from the old university data) to this new Drupal 7 site.

This error is killing us, to the point where we are almost ready to scrap the last years worth of work and go with something else if Drupal cannot handle this type of load.

But that is more or less my question - How can Drupal handle this type of load? How can I organize my work flow to be able to handle this much activity? Is this a Drupal issue? A database issue?

Specifically, I am running Ubuntu, LAMP stack 16GB RAM. I am open to any suggestion whether it be Drupal related, database related, server config related, or a different work flow to work within Drupal's capabilities, so feel free to suggest anything if you have experience with this much activity.

# Answer
> 2 votes
The answer is: Configure your MySQL my.cnf file correctly.

After a little over a week of research, I have found that Drupal 7 can indeed handle this much concurrent input traffic.

These Deadlock PDOExceptions were related to the MySQL my.cnf file not being optimized correctly. With help from the Drupal High Performance group and other sources, our team has not had one single Deadlock happen since implementing the new configuration settings for MySQL. We tested our batch scripts to simulate up to 500 current users saving content with no problem. Check out the thread here.

http://groups.drupal.org/node/260938

Specifically, Dalin suggested using a wizard to get a base configuration file based on the server specs and table types. After using this, even without further tweaking, the deadlocks stopped. Here is a link to the wizard if you would like to try it: https://tools.percona.com/wizard

I'll be happy to post the my.cnf file if anyone would find it helpful.

Although the Deadlock problem is no longer an issue, we are now getting this error very frequently:

```
PDOException: SQLSTATE[42000]: Syntax error or access violation:
1305 SAVEPOINT savepoint_1 does not exist: ROLLBACK TO SAVEPOINT savepoint_1;
Array ( ) in file_usage_add() (line 661 of /var/www/website.com/includes/file.inc).

```

Could this be a mysql configuration issue as well?

# Answer
> 6 votes
I work for Stanford university and have been doing similar things. We constantly have to load over 100,000+ nodes on a regular basis. We have been working on our own custom loading code for 2 years now have been able to speed up the process quite a big using pcntl\_fork. The only thing you have to remember is to close all socket connection before invoking the fork. For example you have to close you mysql connection, memcache connection and even mongo connection. Drupal will automatically create new connections when one doesn't exists. As far as the deadlock problem, we were able to fix that issue by putting `innodb_locks_unsafe_for_binlog = 1`.

# Answer
> 1 votes
http://dev.mysql.com/doc/refman/5.0/en/innodb-deadlocks.html this mysql page suggests what to do when you encounter the deadlock.

By fine tuning your mysql configuration will help you to solve this issue.

---
Tags: 7, performance, database
---


title: How to add table column aliases

text:
# Question
Title: How to add table column aliases
I am trying to perform a query on a database that has the following info (in Drupal 7.21):

```
nid | sid | cid | data
----------------------
32  |  2  |  1  | date
32  |  2  |  2  | name
32  |  3  |  1  | date
32  |  3  |  2  | name
32  |  4  |  1  | date
32  |  4  |  2  | name
         etc..

```

I would like to perform a query on the database where I extract the following information in this manner:

```
nid | sid |    date    |    name
-----------------------------------
 32 |  2  | date_value | name_value
 32 |  3  | date_value | name_value
 32 |  4  | date_value | name_value

```

Where date and name are the actual values. Of course the result of this query would be an object. I am using the table display here to illustrate what I want to achieve in terms of data extraction.

My query looks like this:

```
$query = db_select('webform_submitted_data', 'sub1');
$query->innerJoin('webform_submitted_data', 'sub2', 'sub1.nid=sub2.nid and sub1.sid=sub2.sid');
$query = $query
  ->fields('sub1', array('nid', 'sid'))
  ->addField('sub1', 'data', 'date')
  ->addField('sub2', 'data', 'name')
  ->condition('sub1.nid', 32)
  ->condition('sub2.cid', 2)
  ->condition('sub1.cid', 1);

```

I thought the addField command would accomplish this but Drupal doesn't like it. What am I doing wrong?

Thanks.

# Answer
Okay, I fixed it by doing the following:

```
$query->addField('sub1', 'data', 'date');
$query->addField('sub2', 'data', 'name');
$query = $query
  ->fields('sub1', array('nid', 'sid', 'data'))
  ->fields('sub2', array('data'))
  ->condition('sub1.nid', 32)
  ->condition('sub2.cid', 2)
  ->condition('sub1.cid', 1);

```

The issue was addField does not return an object so you can't chain the commands together. Also note that even though you aliased the colums to date and name you still need to refer to them as tablename.data. The aliased names will appear in the result of the query.
> 1 votes

---
Tags: 7, database
---


# Question
Title: Filter and display all commerce product sales by date in a block?
In my Commerce Order settings I have created a custom select list field with the following Allowed values.

**Allowed values list**

> 1|01/03/2013
>
> 2|02/03/2013
>
> 3|03/03/2013
>
> 4|04/03/2013
>
> 5|05/03/2013

Currently I can choose a date from a select list and that filters all sold products and gives me the result for that date. I am able to separately filter all products sold for each date using views but is there a way I can list the results of each date separately in a block?

Is this possible or do I have to add the field for each date and set the operator Is equal to the date for each date in my select list?

I would like the output to be something like this.

## Event Date Sales

> 01/03/2013 Total: 210
>
> 02/03/2013 Total: 150
>
> 03/03/2013 Total: 621
>
> 04/03/2013 Total: 500
>
> 05/03/2013 Total: 142

# Answer
You need to do some advanced Views building to make this happen, so if you've never used Views aggregation (formerly I think it was called "group by"), then I'd recommend looking into video tutorials on the topic.

Basically, if you start with a View of Orders and turn on aggregation (under advanced settings), then you can add two fields to the View:

1. Your custom date select field using "Group results together" as the aggregation type.
2. The Order ID using "Count" as the aggregation type.

Fiddle with it from there to get it to look like you want, probably using an unsorted list display format with the fields set the show up on the same line.

Here's a quick working export of a View that groups orders by user and shows the number of orders per each user (courtesy of joshmiller): http://pastebin.com/j7NTrkp9
> 0 votes

---
Tags: views, commerce
---


title: Use url alias for page parameters

text:
# Question
Title: Use url alias for page parameters
I'm new to Drupal and created a basic page in which the clean url is

```
/todo

```

If I want the todo's for a certain month I can do

```
/todo?month=januaray

```

However what I would like to do is provide a clean url which looks like

```
/todo/januaray

```

I tried modifying my `.htaccess` file like explained here

```
RewriteCond %{REQUEST_URI} ^/todo/(.*)$
RewriteRule ^.*$ /todo?month=%1 [L]

```

But that didn't seem to work. Is there any easy way to achieve this?

# Answer
> 1 votes
This will work:

```
RewriteRule ^todo/(.*)$ todo?month=$1 [L,QSA]

```

No need for the rewrite condition.

That will internally forward, e.g. `http://example.com/todo/january` to `http://example.com/todo?month=january`.

Make sure you add that code **before** Drupal's main index.php RewriteRule

# Answer
> -3 votes
I would consider using Pathauto as it is way more flexible and easier to use.

> The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.

---
Tags: 7, uri
---


# Question
Title: Blocks created twice for a single page load
In a template file I am using this code

```
$blocks= block_get_blocks_by_region('revel_card_dashboard');

```

To grab blocks for a region to render at specific parts of the template. This is causing the regions to be created twice.

Checking stack traces the first time the blocks are created is by drupal core.

```
 2 =>
  array (
    'file' => 'C:\\xampp\\htdocs\\revel\\html\\includes\\module.inc',
    'line' => 799,
    'function' => 'call_user_func_array',
  ),
  3 =>
  array (
    'file' => 'C:\\xampp\\htdocs\\revel\\html\\modules\\block\\block.module',
    'line' => 854,
    'function' => 'module_invoke',
  ),
  4 =>
  array (
    'file' => 'C:\\xampp\\htdocs\\revel\\html\\modules\\block\\block.module',
    'line' => 674,
    'function' => '_block_render_blocks',
  ),
  5 =>
  array (
    'file' => 'C:\\xampp\\htdocs\\revel\\html\\modules\\block\\block.module',
    'line' => 318,
    'function' => 'block_list',
  ),
  6 =>
  array (
    'file' => 'C:\\xampp\\htdocs\\revel\\html\\modules\\block\\block.module',
    'line' => 268,
    'function' => 'block_get_blocks_by_region',
  ),
  7 =>
  array (
    'file' => 'C:\\xampp\\htdocs\\revel\\html\\includes\\common.inc',
    'line' => 5616,
    'function' => 'block_page_build',
  ),
  8 =>
  array (
    'file' => 'C:\\xampp\\htdocs\\revel\\html\\includes\\common.inc',
    'line' => 2583,
    'function' => 'drupal_render_page',
  ),
  9 =>
  array (
    'file' => 'C:\\xampp\\htdocs\\revel\\html\\includes\\common.inc',
    'line' => 2471,
    'function' => 'drupal_deliver_html_page',
  ),
  10 =>
  array (
    'file' => 'C:\\xampp\\htdocs\\revel\\html\\includes\\menu.inc',
    'line' => 531,
    'function' => 'drupal_deliver_page',
  ),
  11 =>
  array (
    'file' => 'C:\\xampp\\htdocs\\revel\\html\\index.php',
    'line' => 21,
    'function' => 'menu_execute_active_handler',

```

How can I grab the already created blocks instead of creating them a second time as the call up top seems to do?

Clarification: I do not want to simply cache the block because its important to update the block when the user revisits the page, but there is no point in updating it with time expensive methods twice a page view.

# Answer
```
$blocks = $page['revel_card_dashboard'];

```

This line of code grabbed the blocks that had already been created by drupal's original passthrough.
> 0 votes

---
Tags: blocks, theming
---


# Question
Title: How do I copy an already existing field in manage display?
I have a field (entity reference) that is used to provide a link to another node. I want to have it two times in my "manage display" settings page, it's for redundancy. I don't want to create a new field, i just want a duplicate in the view mode. Is that possible? Maybe it's just hidden in plain view?

# Answer
The solution to printing out a variable twice is to use a custom template. e.g. copy node.tpl.php or node--contenttype.tpl.php and put the link in there twice.

Don't forget to clear caches to see your changes.
> 1 votes

# Answer
The approach I would use would be to use a custom php snippet in a block to pull the field value out of $node and to format the field. I would then place the block in a region of the page where I needed it.

`<?php`

`if (arg(0) == 'node' && is_numeric(arg(1))) {

$node = node_load(arg(1));

if (isset($node->field_node_reference['und'])) {

```
foreach ($node->field_node_reference['und'] as $other_node) {
  $link = '/node/' . $other_node['node']->nid;
  $title = $other_node['node']->title;
  print (l( $title, $link));
}

```

}`

`} ?>`

This would be the core code for a node reference field. You should pretty it up to format your display, but this gets the information on your page a second time.
> 1 votes

# Answer
You are trying to follow the pattern that gets people to validate an email address by entering it twice? The end goal is not just to have the element twice in the administration screens?

If the goal is to get people to type out a field response twice, then it is appropriate to have the field twice as you need 2x responses for the validation - to compare then to make sure they are the same. Having 2 instances of a field without 2 corresponding values is a logical problem - which instance would you want the to be submitted back to the server?

It is possible to use javascript/jquery to clone the html form element and then check that it is the same without submitting the second value. Try http://api.jquery.com/clone/ and compare the result on submit.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: succesfully changed order regions in info file, but rendered html stays untouched
Layout-wise I want 3 columns in this order: `sidebar first - content - sidebar right`. Since the region order in d7 is `content - sidebar first - sidebar second` I wanted to change that order in html.

If I remember well, all that's needed to change the order of the regions, is to do that in the `.info` file.

So I simply just put the `content` region between `sidebar first` and `sidebar second` so the info file has the following in it:

```
regions[header] = Header
regions[highlighted] = Highlighted
regions[help] = Help
regions[sidebar_first] = Left sidebar
regions[content] = Content
regions[sidebar_second] = Right sidebar
regions[footer] = Footer

```

When I go to `structure` -\> `blocks` The result that I'm seeings is what I was aiming for; the content region is being replaced. Yet, when I go and check the HTML,The order remains `content - sidebar first - sidebar second`.

Goes without saying I cleared caches often.

# Answer
> 0 votes
the orders of your regions are probably defined in the `page.tpl.php` of your current theme. so you will have to change the order there, changing the order of your .info entries should (if any) only change the output from configuration pages.

---
Tags: 7
---