title: Travel listings module for Drupal

text:
# Question
Title: Travel listings module for Drupal
I'm using Drupal 7 and can't find a suitable module to add travel listings content type. It would be great if that module would just work by having specific fields, like location and address, as well as enable the possibility to have a main index page that lists all the listings in a category.

I found Listings module, but that's only for Drupal 6.

Thank you!

# Answer
> 2 votes
Since we have the flexibility of the content type and field creation systems you don't really need someone else to post a module creating the exact content type you need (it is unlikely your requirements are exactly the same as the author of such a module).

So instead you can yourself:

1. Create your own custom content type
2. Add the fields you require to the content type
3. Create a listing of your content using the views module \- If you install the advanced help module you will get lots of help documentation on creating views by clicking the little question mark links scattered around the views user interface.

---
Tags: 7, theming
---


# Question
Title: Send email after term is selected in checkbox in a node form with rules
I have created a node form which has taxonomy vocabulary Application Status with three terms represented as check boxes

Approve Masters Approve Honours Rejected

What I am trying to achieve is when you select one of the terms a unique rule for each term sends an email for the term that has been selected in the check box. I have tried numerous setups but cannot get it to work properly. My current approach is

Event:

After updating existing content of type Online Application Form

After saving a new field collection item

Conditions :

Entity is new

Actions:

Send HTML e-mail

If anybody can give me some good advice on how to achieve this I would be most grateful.

# Answer
> 6 votes
You need:

* An "Entity has field" condition to check for the existence of the taxonomy field, and then
* A "Data comparison" condition to match the value of the taxonomy field to the one of the three terms on which you want the rule to operate.

You have two Events in your rule. It seems if you put the Field Collection condition first, then the node fields aren't available in Rules, and vice-versa. So list the "After updating existing content of type Online Application Form" event first so that you can access the taxonomy field in the conditions.

---
Tags: taxonomy-terms, rules, emails, nodes
---


# Question
Title: Non-static method view::load_views() should not be called statically with VIEWS
When I copied my Drupal 6 web site to another server with a higher version ofPHP, I get this problem on all pages that have views:

```
strict warning: Non-static method view::load_views() should not be called statically in C:\xampp\htdocs\sites\all\modules\views\views.module on line 864.
strict warning: Non-static method view::db_objects() should not be called statically in C:\xampp\htdocs\sites\all\modules\views\includes\view.inc on line 1417.
strict warning: Declaration of calendar_plugin_display_page::options_submit() should be compatible with views_plugin::options_submit(&$form, &$form_state) in C:\xampp\htdocs\sites\all\modules\calendar\includes\calendar_plugin_display_page.inc on line 297.
strict warning: Declaration of calendar_plugin_display_page::options() should be compatible with views_object::options() in C:\xampp\htdocs\sites\all\modules\calendar\includes\calendar_plugin_display_page.inc on line 297.
strict warning: Declaration of calendar_plugin_display_block::options() should be compatible with views_object::options() in C:\xampp\htdocs\sites\all\modules\calendar\includes\calendar_plugin_display_block.inc on line 78.
strict warning: Declaration of calendar_plugin_display_attachment::options_submit() should be compatible with views_plugin::options_submit(&$form, &$form_state) in C:\xampp\htdocs\sites\all\modules\calendar\includes\calendar_plugin_display_attachment.inc on line 242.
strict warning: Declaration of calendar_plugin_display_attachment::options() should be compatible with views_object::options() in C:\xampp\htdocs\sites\all\modules\calendar\includes\calendar_plugin_display_attachment.inc on line 242.
strict warning: Declaration of calendar_plugin_display_ical::options_submit() should be compatible with views_plugin::options_submit(&$form, &$form_state) in C:\xampp\htdocs\sites\all\modules\calendar\calendar_ical\calendar_plugin_display_ical.inc on line 217.
strict warning: Declaration of views_content_plugin_display_panel_pane::options_submit() should be compatible with views_plugin::options_submit(&$form, &$form_state) in C:\xampp\htdocs\sites\all\modules\ctools\views_content\plugins\views\views_content_plugin_display_panel_pane.inc on line 40

```

# Answer
> 4 votes
These errors, at least those coming from Views, does not really have a proper solution, because the versions of Views and Calendar that cause them, are no longer being updated.

Views 2 is officially not being updated anymore, and I doubt anything but serious security problems is going to change that. Calendar could potentially have the problem fixed, but this is also a module with a great deal of issues, and for an old version, I simply wouldn't expect these problems to be prioritized enough to get fixed.

Your basic options:

1. Upgrade to Views 3, and the corresponding Calendar version.
2. Disable E\_STRICT error reporting.
3. Simply accept that the errors are there.

A more sophisticated and perhaps better solution would be to locate the relevant patches in the issue queues, and apply them in your drush make file.

# Answer
> 0 votes
This is issue 465332 on d.o, part of the Views issue queue. There's a patch attached that's supposed to work but the patch is actually patching core.

For me personally I'm just disabling error reporting to the screen at `admin/settings/error-reporting`. This is a good enough solution since I'm not doing any serious work on my D6 sites anymore.

# Answer
> -3 votes
goto

administer -\> settings -\> error handling

set: Error reporting: to write errors to the log

---
Tags: views, 6
---


# Question
Title: Is it possible to do a drush sql-sync of only certain tables?
I have 4 environments between my local, dev, staging, and production.

A large amount of content is published to the staging environment on a daily basis, so that is the center of my workflow. Once content is QA'ed in staging it is then sql-sync'ed to production. This works fine at the moment. However, we're now going to allow for user registration/user generated content. Is there a way to push these content updates with sql-sync and never overwrite certain tables? Even more specifically, is there something I can place in drushrc.php that will always skip a list of tables across all environments?

# Answer
# YES

## If you know which tables you want to transfer

> `--tables-list`
>
> A comma-separated list of tables to transfer. Optional.

## If you know which tables you want to skip

> `--skip-tables-list`
>
> A comma-separated list of tables to exclude completely. Optional.

---

And here is how I know this:

```

$ drush help sql-sync
Copy and import source database to target database. Transfers via rsync.

Examples:
 drush sql-sync @prod @dev                 Copy the DB defined in sites/prod to the DB in sites/dev.

Arguments:
 from                                      Name of subdirectory within /sites or a site-alias.
 to                                        Name of subdirectory within /sites or a site-alias.

Options:
 --cache                                   Skip dump if result file exists and is less than "cache" hours old. Optional; default is 24 hours.
 --create-db                               Create a new database before importing the database dump on the target machine.
 --db-su=                            Account to use when creating a new database. Optional.
 --db-su-pw=                         Password for the "db-su" account. Optional.
 --dump-dir                                Directory to store sql dump files in when --source-dump or --target-dump are not used.  Takes precedence over --temp.
 --no-cache                                Do not cache the sql-dump file.
 --no-dump                                 Do not dump the sql database; always use an existing dump file.
 --no-ordered-dump                         Do not pass --ordered-dump to sql-dump.  sql-sync orders the dumpfile by default in order to increase the efficiency of rsync.
 --sanitize                                Obscure email addresses and reset passwords in the user table post-sync. Optional.
   --sanitize-password                     The password to assign to all accounts in the sanitization operation, or "no" to keep passwords unchanged.  Default is "password".
   --sanitize-email                        The pattern for test email addresses in the sanitization operation, or "no" to keep email addresses unchanged.  May contain replacement patterns %uid,
                                           %mail or %name.  Default is "user+%uid@localhost".
   --confirm-sanitizations                 Prompt yes/no after importing the database, but before running the sanitizations
 --skip-tables-key                         A key in the $skip_tables array. @see example.drushrc.php. Optional.
 --skip-tables-list                        A comma-separated list of tables to exclude completely. Optional.
 --source-database                         A key in the $db_url (D6) or $databases (D7+) array which provides the data.
 --source-db-url                           Database specification for source system to dump from.
 --source-dump                             Path to dump file. Optional; default is to create a temporary file.
 --source-remote-host                      Remote machine to run sql-dump file on. Optional; default is local machine.
 --source-remote-port                      Override sql database port number in source-db-url. Optional.
 --structure-tables-key                    A key in the $structure_tables array. @see example.drushrc.php. Optional.
 --structure-tables-list                   A comma-separated list of tables to include for structure, but not data. Optional.
 --tables-key                              A key in the $tables array. Optional.
 --tables-list                             A comma-separated list of tables to transfer. Optional.
 --target-database                         A key in the $db_url (D6) or $databases (D7+) array which shall receive the data.
 --target-db-url
 --target-dump
 --target-remote-host
 --target-remote-port
 --temp                                    Use a temporary file to hold dump files.  Implies --no-cache.

```
> 9 votes

# Answer
Perhaps `--skip-tables-list` is of interest to you. `drush help COMMAND` is your friend. You can set a global option in a `drush.rc` file to make this option hardcoded for every `sql-sync` for certain Site Aliases if you want. Because heaven forbid you sql-sync and forget to skip tables on some Friday at 5pm :(.

```
drush help sql-sync
Copy and import source database to target database. Transfers via rsync.

Examples:
 drush sql-sync @prod @dev                 Copy the DB defined in sites/prod to the DB in sites/dev.

Arguments:
 from                                      Name of subdirectory within /sites or a site-alias.
 to                                        Name of subdirectory within /sites or a site-alias.

Options:
 --cache                                   Skip dump if result file exists and is less than "cache" hours old. Optional; default is 24 hours.
 --create-db                               Create a new database before importing the database dump on the target machine.
 --db-su=                            Account to use when creating a new database. Optional.
 --db-su-pw=                         Password for the "db-su" account. Optional.
 --dump-dir                                Directory to store sql dump files in when --source-dump or --target-dump are not used.
 --no-cache                                Do not cache the sql-dump file.
 --no-dump                                 Do not dump the sql database; always use an existing dump file.
 --no-ordered-dump                         Do not pass --ordered-dump to sql-dump.  sql-sync orders the dumpfile by default in order to increase the efficiency of
                                           rsync.
 --sanitize                                Obscure email addresses and reset passwords in the user table post-sync. Optional.
   --sanitize-password                     The password to assign to all accounts in the sanitization operation, or "no" to keep passwords unchanged.  Default is
                                           "password".
   --sanitize-email                        The pattern for test email addresses in the sanitization operation, or "no" to keep email addresses unchanged.  May contain
                                           replacement patterns %uid, %mail or %name.  Default is "user+%uid@localhost".
   --confirm-sanitizations                 Prompt yes/no after importing the database, but before running the sanitizations
 --skip-tables-key                         A key in the $skip_tables array. @see example.drushrc.php. Optional.
 --skip-tables-list                        A comma-separated list of tables to exclude completely. Optional.
 --source-database                         A key in the $db_url (D6) or $databases (D7+) array which provides the data.
 --source-db-url                           Database specification for source system to dump from.
 --source-dump                             Path to dump file. Optional; default is to create a temporary file.
 --source-remote-host                      Remote machine to run sql-dump file on. Optional; default is local machine.
 --source-remote-port                      Override sql database port number in source-db-url. Optional.
 --structure-tables-key                    A key in the $structure_tables array. @see example.drushrc.php. Optional.
 --structure-tables-list                   A comma-separated list of tables to include for structure, but not data. Optional.
 --tables-key                              A key in the $tables array. Optional.
 --tables-list                             A comma-separated list of tables to transfer. Optional.
 --target-database                         A key in the $db_url (D6) or $databases (D7+) array which shall receive the data.
 --target-db-url
 --target-dump
 --target-remote-host
 --target-remote-port
 --temp                                    Use a temporary file to hold dump files.  Implies --no-cache.

```
> 4 votes

# Answer
If you check out the Drush Commands page for sql-sync (or `drush sql-sync --help`) then you'll notice there is a parameter called `--skip-tables-list`.

> --skip-tables-list : A comma-separated list of tables to exclude completely. Optional.

To answer the second part of your question, you can also add an array to `drushrc.php` (source):

```
/**
 * List of tables to be omitted entirely from SQL dumps made by the 'sql-dump'
 * and 'sql-sync' commands when the "--skip-tables-key=common" option is
 * provided on the command line.  This is useful if your database contains
 * non-Drupal tables used by some other application or during a migration for
 * example.  You may add new tables to the existing array or add a new element.
 */

```

In this instance you then pass the array key with `--skip-tables-key`:

> --skip-tables-key : A key in the $skip\_tables array. @see example.drushrc.php. Optional.
> 2 votes

---
Tags: drush
---


# Question
Title: Redirect comment permalink to their corresponding node paths
Is there any way in drupal to redirect comment permalink to their corresponding node paths or url alias?

I want to redirect all comment/x paths to their corresponding node-path. And it should handle pagers as well. If your comment is in the second page (when you have set a comments-per-page value in node type settings), it should be like

http://example.com/comment/111 to http://example.com/node/123?page=1#comment-111

```
http://example.com/comment/111 to http://example.com/node/123#comment-111
http://example.com/comment/112 to http://example.com/node/123#comment-112

```

Thanks in Advance!

# Answer
> 0 votes
I managed to acheive it through hook\_menu\_alter. It just works great for me

```
<?php
/**
* Implements hook_menu_alter.
* @author Md Eqbal Ahmad <*****@******.com>
*/
function MODULE_menu_alter(&$items) {
  $items['comment/%']['page callback'] = 'MODULE_commentpermalink';
}

/**
 * Redirect comment permalink to their corresponding node paths
 * @author Md Eqbal Ahmad <*****@*****.com>
*/
function MODULE_commentpermalink($cid) {
  if (($comment = comment_load($cid)) && ($node = node_load($comment->nid))) {
    // Find the current display page for this comment.
    $page = comment_get_display_page($comment->cid, $node->type);
    // Now, rather than setting menu_executive_active_handler and changin $_GET valies, we redirect them to the actual node URL with fragments and pager set.
    if ($page > 0) {
      drupal_goto("node/$comment->nid", array('fragment'=>"comment-$comment->cid",'query'=>array('page'=>$page)), 301);
    }
    else{
      drupal_goto("node/$comment->nid", array('fragment'=>"comment-$comment->cid"), 301);
    }
  }
  drupal_not_found();
}

?>

```

# Answer
> 0 votes
Try it using `hook_preprocess_page` :

```
function MODULE_preprocess_page(&$vars) {
      if (arg(0) == 'comment') {
        $cid = arg(1);
        if (($comment = comment_load($cid)) && ($node = node_load($comment->nid))) {
          // Find the current display page for this comment.
          $page = comment_get_display_page($comment->cid, $node->type);
          // Now, rather than setting menu_executive_active_handler and changin $_GET valies, we redirect them to the actual node URL with fragments and pager set.
          if ($page > 0) {
            drupal_goto("node/$comment->nid", array('fragment'=>"comment-$comment->cid",'query'=>array('page'=>$page)), 301);
          }
          else{
            drupal_goto("node/$comment->nid", array('fragment'=>"comment-$comment->cid"), 301);
          }
        }
        drupal_not_found();
      }
    }

```

---
Tags: 7, redirection
---


# Question
Title: Domain Access with URL Alias - same content, but with different automated aliases
I have a site running Domain Access with two domains - the primary domain and the sub-domain. Both domains share the same content in the database, but I would like the automated URL aliases for the sub-domain to be different from that of the primary domain's.

There are two tables in the database right now - the `url_alias` table and the `domain_2_url_alias` table (of which the latter is a copy of the original `url_alias` table).

I tried modifying the settings under `/admin/build/path/pathauto` and selected the sub-domain under the "Save settings for:" option, but that didn't seem to have any effect at all.

I can change the values in domain\_2\_url\_alias manually for each node (which worked), but the site generates new content very often, that this wouldn't be a viable solution.

I appreciate any help I can get! Thanks in advance.

# Answer
> 6 votes
I believe this is exactly what the Domain Path module is for.

According to the module page:

> The Domain Path module allows the creation of separate path aliases per domain for nodes created using the Domain Access module.

However, it looks like this module provides the option per node, rather than offering different pathauto patterns which I think is what you want. There's a postponed request in the issue queue for pathauto integration that offers a partial patch, but it's offered as an anti-proof-of-concept, it seems.

---
Tags: 6, domain-access, path-aliases
---


title: add_relationship and views_join

text:
# Question
Title: add_relationship and views_join
In `hook_views_query_alter()`, I am trying to add a join to the user role of the author of the node and filter basing on the role.

```
        $query->add_relationship('user_role_join', new views_join('users_roles', 'uid', 'users', 'uid','INNER'), 'node');
        $query->add_where(1,'user_role_join.rid','4' ,'=');

```

It is something like this, but I am missing something. When I run this query the result is always empty. If I create the condition using Views UI, I do get the correct and expected result. So the data is okay, but my code is the problem.

How do I setup this join correctly in `hook_views_query_alter()`?

Also the following code doesn't work.

```
$join = new views_join();
$join->table = 'node';
$join->field = 'uid';
$join->left_table = 'users_roles';
$join->left_field = 'uid';
$join->type = 'INNER';
$join->extra = array(
            array(
                'field' => 'bundle',
                'value' => 'node',
            )
        );
$query->add_relationship('user_node_role', $join, 'node');

$query->add_where(1,'user_node_role.rid','4' ,'=');

```

# Answer
> 9 votes
I found the solution

```
        $join = new views_join();
        $join->table = 'users_roles';
        $join->field = 'uid';
        $join->left_table = 'node';
        $join->left_field = 'uid';
        $join->type = 'left';

        $query->add_relationship('users_roles', $join, 'node');
        $query->add_where(1,'users_roles.rid','4' ,'=');

```

This works

# Answer
> 3 votes
It is better to use hook\_query\_alter() than hook\_views\_query\_alter() because it uses Drupal database abstraction layer and it's by far more easy to implement.

You can add a tag to the view's display you want to modify, *roles* for example, and check for it at the beginning of the hook:

```
function MODULE_query_alter(QueryAlterableInterface $query) {
  if ($query->hasAllTags('views', 'roles')) {
    $query->leftJoin('users_roles', 'ur', 'node.uid = ur.uid');
    $query->condition('ur.rid', 4);
  }
}

```

IMHO this way is more standard.

# Answer
> 0 votes
I think you need to build the new join outside of the $query-\>add\_relationship.

See: https://api.drupal.org/comment/54213#comment-54213

---
Tags: 7, views
---


title: Drupal 7 - load view programmatically

text:
# Question
Title: Drupal 7 - load view programmatically
How do I load a view programmatically passing a language attribute? Tried with module\_invoke and views\_embed\_view but none of them worked; Data is returned but not filtered by language;

Please advise. Thank you!

# Answer
If your view is set up with a Contextual Filter for language, this should work:

```
print views_embed_view($viewname, $display_id, $languagecode);

```
> 0 votes

# Answer
I think you should add "Filter criteria-- Content:Language(current User's language.)". This will solve our problem.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How do I find out what controls access to a page?
I'm surprised by finding that I can't access `[some-path]` on my site, and I don't know what to do?

Where do I begin searching? What is the fundamental most level to start from?

# Answer
For Drupal 6 and 7, the basic access check details are stored in the table `menu_router`.

To find out the relevant details, try a query like

`SELECT path, access_callback, page_callback FROM menu_router WHERE path LIKE '%user%';`

Lets look at three examples returned by that query on a local site of mine:

```
| path                | access_callback  | access_arguments   | page_callback
| user                | 1                | a:0:{}             | user_page
| user/%/edit/account | user_edit_access | a:1:{i:0;i:1;}     | drupal_get_form
| user/%/display      | user_access      | "administer users" | ds_contextual_page_tab

```

The data above has been manipulated slight for brevity.

First: `user`. `user`has an access callback of `1`, which means it will *always* pass. This is not, as one might think, to allow everyone access, but usually rather because the access decisions for this particular path are complicated enough to require more than a regular permission. Because of that, we need to look at the next column, which is `page_callback`. This tells us which function is called to actually handle the page, and `page_arguments`, in this case empty, could contain any arguments passed to the same function. In this case, there are no arguments, so we can't learn any more here. One needs to start reading the code of `user_page()` to figure out more.

Second: `user/%/edit/account`. This path has a standard `access_callback`, which means that `user_edit_access` is called, and if it returns `TRUE`, we'll be given access. One needs to read that function to find more details.

Third: `user/%/display`. This one is the easiest. `user_access` simply checks if the user has been assigned the permission that is passed in from `access_arguments`, so in this case `administer users`. If that permission has been checked for the users role, access will be granted. User 1 automatically gets to bypass such checks.
> 4 votes

---
Tags: users
---


# Question
Title: Enabling a module leads to memory exhaution. Where to look for?
I have developed my little module for Drupal 7 and it has been working fine. But suddenly it started to cause a memory crush. Now I can't even enable it (drush en ModuleName) with the error message of:

> Error: Allowed memory size of 536870912 bytes exhausted \[...\] in /MY/DRUPAL/ROOT/includes/module.inc, line 596

The line number, where it fails, varies sometimes. I clear the cache (`drush cc all`) frequently or practically at every step, so I don't think it is cache-related. The allowed memory for PHP and SQL are both 512MB, and the website is mini-scale with no load-hungry module. The memory should be a way more than enough.

The module is just a little language switcher with only a \*.module file (and \*.info), and has no major loop — One time loop for an enabled couple of languages is all it has. No recursive call whatsoever. So, I have no idea where to look for to pin down the problem… Only the potential thing I could think of is I had deleted a (unnecessary) path-alias directly via SQL (a row in Table url\_alias), immediately before this trouble started. It being the language-switcher, it accesses to drupal\_get\_path\_alias(), but does it matter?

In case you are interested, my little module is available in GitHub:
https://github.com/masasakano/lang\_switcher\_advanced

**\[Edit\]**
It seems the problem was tracked down and I posted it as the answer. Everything one'd need is written in it, but just to note, the example codes before and after it was solved are tagged as 0.1.1 and 0.1.2 in the above GitHub repository.

# Answer
A short answer for the question is to check the function names defined in the module. If there is any conflict with the existing function names, that can give a trouble when enabling the module. Also, it may be advisable to disable and enable the module, whenever you add a function to the module, maybe, to detect a potential trouble at the earliest opportunity.
**--The following appended--**
Another preventive ways: (1) Keep only `hook_` functions in a `*.module` file, (2) for D7, name always your private functions with a little convention, for example, add the prefix of `_`: e.g., `function _myfunction_theme()`.
**--Appended up to here--**

It turned out the function name `My_Module_Name_theme()` conflicts with `hook_theme()` in Drupal. I was not using it as my intention, but the code of the function was left for the future development - that caused a trouble, as it was regarded as a valid hook by Drupal, whatever the programmer's *intention* was. The arguments given to a call of another Drupal function in that function were not compatible with the Drupal function. That may have lead to the memory exhaustion.

My guess is, since it is the name of the function (or maybe because it is a hook?), that caused a memory exhaustion while enabling the module rather than during run-time. I added the function in the module when the module had been already enabled. At that time (I mean, after I added the function), the module caused no trouble and kept functioning as I intended. It is possibly because the function names were not registered to Drupal? I don't know, but whichever, it would make (and indeed did make in my case) a programmer's job to track down the cause of the memory exhaustion difficult, as the error message might not help much to pin down which module, let alone which function, is causing a trouble.

Note even after I had added the "hook" function, I have once successfully disabled and enabled the module (after Drupal experienced a memory exhaustion), and the module worked fine for some time, before it eventually started to cause a memory exhaustion and then it became impossible to re-enable it. I do not know why it was enabled successfully once and worked OK for some time.

The moral of this case is summarised at the beginning. Added to that, to chop off all the unnecessary parts like debugging may help (as @rooby suggested in the comment of the question), because something in those unnecessary parts, or those that you think are unused, may be causing a trouble. Frequent disabling/enabling cycles, as well as clearing the cache, can also help to identify the problem at the earliest opportunity.
> 3 votes

# Answer
Tracking down memory problems is treacherous business. There are many different ways that will help you, but not one single strategy. When I got myself stuck in situations that made me suspect my code was eating up memory, the most help I got was from tools like Callgrind and Valgrind. Which one to use depends on the platform you are running on. They will collect a full record of your call stack along with execution times and memory usage. Then you can use a visualization tool to go through the output file (don't try manually). I've used MacCallGrind, but there are plenty others.
> 1 votes

---
Tags: 7
---


# Question
Title: How does CSS and JS aggregration work in Drupal?
When Drupal is set to optimize JS and CSS, it creates the 'js' and 'css' folders in your public file system root. Aggregated JS and CSS get stored in these directories. I've tried to figure out how Drupal keeps track of these files, and how Drupal matches consequent page request against applicable aggregated files in these directories. Is the filename a hash based on, say, the request URL?

Right now, I'm working on a site which has 4 web servers. All web servers have the same storage mounted as their public and private file systems. When one server generates CSS and JS files for a page, how does any of the other servers utilise these generated files for an indentical request?

# Answer
CSS/JS files get added to Drupal various ways; 5 out of the 7 ways allows for the file to be aggregated. Once they have been added to the page, drupal renders the html markup for them and creates/uses the markup inside of template\_process\_html().

Functions to look for how an aggregate is built is drupal\_build\_js\_cache() & drupal\_build\_css\_cache(). Inside of these function it gets a list of filenames and then creates a hash of them. This is a lookup, to see if the file has already been created.

```
  $map = variable_get('drupal_js_cache_files', array());
  // Create a new array so that only the file names are used to create the hash.
  // This prevents new aggregates from being created unnecessarily.
  $js_data = array();
  foreach ($files as $file) {
    $js_data[] = $file['data'];
  }
  $key = hash('sha256', serialize($js_data));
  if (isset($map[$key])) {
    $uri = $map[$key];
  }

```

If it has not been created before, because of the order and/or contents of the $file\['data'\] info then it will create a new aggregate based off of all the files contents strung together.

```
  if (empty($uri) || !file_exists($uri)) {
    // Build aggregate JS file.
    foreach ($files as $path => $info) {
      if ($info['preprocess']) {
        // Append a ';' and a newline after each JS file.
        $contents .= file_get_contents($path) . ";\n";
      }
    }
    // Prefix filename to prevent blocking by firewalls which reject files
    // starting with "ad*".
    $filename = 'js_' . drupal_hash_base64($contents) . '.js';
    // Create the js/ within the files folder.
    $jspath = 'public://js';
    $uri = $jspath . '/' . $filename;
    ...
    $map[$key] = $uri;
    variable_set('drupal_js_cache_files', $map);
  }
  return $uri;

```

The files are kept track inside of 2 variables `drupal_js_cache_files` and `drupal_css_cache_files`; Drupal will also check to make sure the file exists before it is used. The aggregates have nothing to do with the URL. Your 4 webheads will utilize these aggregates due to the variables being stored within the database.

Note: AdvAgg is sorta similar to this but it uses a couple database tables instead of 2 variables; AdvAgg does this for a couple of reasons mainly to fix issues with concurrent variable\_set's and allowing for advanced grouping logic.
> 15 votes

---
Tags: 7, css-js-aggregation
---


# Question
Title: Print full node url escaping special characters?
How can I print the full node url in a tpl file escaping special characters?

So im using this:

```
<?php print $base_url . $node_url ?>

```

Which gives me a url like http://time.com/3525666/ebola-psychology-fear-symptoms/

However I need the url to be like http%3A%2F%2Ftime.com%2F3525666%2Febola-psychology-fear-symptoms%2F

# Answer
The proper way to generate a URL is with the `url()` function, and the `absolute` option:

```
$absolute_url = url('node/123', array('absolute' => TRUE));

```

You then need to encode it:

```
$encoded_url = rawurlencode($absolute_url);

```

This work should be done in a preprocess function, and the variable added to `$variables`, and not done in the .tpl.php file directly:

```
function MYTHEME_preprocess_node(&$variables) {
  $absolute_url = url('node/123', array('absolute' => TRUE));
  $encoded_url = rawurlencode($absolute_url);

  $variables['encoded_url'] = $encoded_url;
}

```

and then printed in the template.

```
<?php print $encoded_url ?>

```

However, you more than likely want to use the `query` option or `drupal_http_build_query` for whatever you are trying to use this for. What you are describing typically isn't needed directly. Giving the proper advice, though, is a little hard without more context.
> 1 votes

---
Tags: theming
---


# Question
Title: How to display only the status message to anonymous users in page.tpl.php
I want to display the status messages to all of the users but the error and warnings to the administrator.I am using this code

```
<?php if($is_admin): ?>
      <?php print $messages; ?>
<?php endif; ?>

```

But I have no idea how to distinguish the message type.

# Answer
This seems like a similar question to yours regarding printing messages. Additionally, this indicates that the message type is stored within the message object. You should just be able to iterate through a message object to get it. Something like

```
foreach (drupal_get_messages($messagesVariable) as $type => $messages) {
    if (($status_heading[$type] != 'error') || ($status_heading[$type] != 'warning')) {
        *perform your given action here*
    }
}

```
> 2 votes

# Answer
Wouldn't the option to not display error messages in /admin/config/development/logging solve this problem?

> "It is recommended that sites running on production environments do not display any errors."

Admins can still see the notices/warnings in the watchdog (Reports \> Recent log messages). Although you should really fix those notices, since by default those messages get logged to the watchdog, which means reducing the site's performance by writing in a database table.
> 1 votes

---
Tags: status-messages
---


# Question
Title: Add a Module Form to a front page region
As the title reads, I'm attempting to add a custom made module (simple contact form) into a region on my front page (this may be used other places as well, but for not just the front page). Could some one lend me their eyes/advice on how to do this correctly. The region on my page is labeled sidebar\_first. I have attempted to add it via a hook\_block\_view() functionallity, however nothing seems to be taking.

.module

```
function honey_front_page_form_menu(){
global $user;
//Main Page Call Back
$items['front_page_form'] = array(
    'page callback' =>'_honey_front_page_init',
    'access arguments' => array('access content'),
    'title' => t('Honey Contact page Form'),
);

}

function honey_front_page_form_admin_form(){

  $form['front_form'] = array(
        '#type' => 'fieldset',
        '#title' => t('Admin Menu'),
);

  $form['front_form']['name'] = array(
    '#type' => 'textfield',
    '#attributes' => array('placeholder' => t('name')),
    '#required' => TRUE,

  );

  $form['front_form']['email'] = array(
    '#type' => 'textfield',
    '#attributes' => array('placeholder' => t('email')),
    '#required' => TRUE,

  );

  $form['front_form']['phone'] = array(
    '#type' => 'textfield',
    '#attributes' => array('placeholder' => t('phone')),
    '#required' => TRUE,
    '#maxlength' => 15

  );
    $form['front_form']['comments'] = array(
    '#type' => 'textfield',
    '#attributes' => array('placeholder' => t('comments')),
    '#required' => FALSE,

  );

  $form['front_form']['submit'] = array(
    '#type' => 'submit',
    '#value' => 'SUBMIT NOW',
    '#field_prefix' => '<h3>',
    '#field_suffix'=> '</h3>'

  );

}

function honey_front_page_form_block_view($delta = ''){
//ensures form is only called on the front page.

// if (!drupal_is_front_page()){
//     return NULL;
// }

    if($delta == '1'){
        $form = drupal_render( drupal_get_form('honey_front_page_form_admin_form'));
    $block = array(
        // 'subject' => t('Subject'),
        'content' => $form,
    );

    return $block;

}
}

```

# Answer
Take a look at the Drupal block APIs. You need to use hook\_block\_info to define a block. Then use hook\_block\_view to return the rendered content of the block. You will still need to include the block, ether programmatically, or by using admin/structure/block.
> 2 votes

---
Tags: 7, blocks
---


# Question
Title: Producing collapsible field sets with theme functions
In an older Drupal 6 instance, I'm updating a module to produce a collapsible fieldset with the following:

```
function my_module_function($table_collections) {
    // include JavaScript for collapse functionality
    drupal_add_js('misc/collapse.js');

    foreach($table_collections as $table) {
            $to_return .= '<fieldset class="collapsible collapsed">';
            $to_return .= '<legend><span><a href="#">' . $title . '</a></span></legend><div>' ;
            $to_return .= theme_table(array_keys($table[0]), $table);
            $to_return .= '</div></fieldset>';
    }

    return $to_return;

}

```

My question, is there a better way to wrap this in a complete theme function? `theme_fieldset` and `ctools_collapsible_theme(&$items)` appears to be for forms. Is there a more standard or better approach than what I have above?

# Answer
You can call theme\_fieldset() directly, even if it's not for a form, as long as you structure the $element correctly:
https://api.drupal.org/api/drupal/includes!form.inc/function/theme\_fieldset/6

You can see an exemple in core here:
https://api.drupal.org/api/drupal/modules!system!system.admin.inc/function/theme\_system\_modules/6

```
$fieldset = array(
  '#title' => t($package),
  '#collapsible' => TRUE,
  '#collapsed' => ($package == 'Core - required'),
  '#value' => theme('table', $header, $rows, array('class' => 'package')),
);
$output .= theme('fieldset', $fieldset);

```

theme\_fieldset() is also valid in Drupal 7, but it seems to have changed in Drupal 8.
> 1 votes

---
Tags: 6
---


title: matching path rewrite without htaccess

text:
# Question
Title: matching path rewrite without htaccess
I need to move a legacy Drupal 7 site to our new Aegir hosting environment. Unfortunately, the file structure is "non standard". I need to move drupal/materials to drupal/sites/default/files/materials but also need a corresponding path rewrite or redirect .htaccess or http.config is not an option, I need to do it in Drupal.

Redirect module does not do tokens or wild cards. Match\_redirect module does not rewrite, but matches on a many to one bases. A rewrite would be better than a redirect.

I cant seem to find an existing contrib - how would I do this in PHP with the Drupal APIs? Would I want to use hook\_boot or hook\_init?

# Answer
If you have some control on the Aegir instance, and 100% trust your users that have sftp/ssh access to your site, you could use the provision\_customhtaccess module:
https://github.com/mlutfy/provision\_customhtaccess

This makes it possible to have a "htaccess-custom" file in your sites/example.org/ directory that will get included in your vhost configuration. **However, it is a big security risk** if you do not trust your users. They can close a vhost declaration, open a new one, do many bad configurations, etc.

Alternatively, if you're going to write a new module, it seems pretty easy to add in the match\_redirect module. There is a feature request open, so I am sure the community would appreciate. Worst case, you can offer the maintainer to sponsor the development:
https://www.drupal.org/node/2118233

You can see how drupal\_match\_path() does a match and use that to rewrite the target redirect:
https://api.drupal.org/api/drupal/includes!path.inc/function/drupal\_match\_path/7
> 0 votes

---
Tags: redirection, uri, aegir
---


# Question
Title: What properties does a custom cck_phone form field need to work?
I am struggling to get a working custom implementation of a cck\_phone field from the cck\_phone module. I have included my partially working code at the bottom.

What seems to be not working is that the function `cck_phone_phone_number_process` expects to be able to retrieve information about the widget with

`$instance = field_widget_instance($element, $form_state);
$settings = $instance['settings'];`

However in my implementation, `field_widget_instance($element, $form_state)` returns NULL, resulting in both `$instance` and `$settings` being NULL and problems further on in the `cck_phone_phone_number_process` function.

What does work is that the code below does render a properly populated country code dropdown and phone number entry textfield.

My code to create the custom cck\_phone field:

```
$form_section['phone']['field_phone_home'] = array(
    '#type' => 'phone_number',
    '#field_parents' => array(
        'profile_personal_information'
    ),
    '#field_name' => 'field_phone_home',
    '#language' => 'und',
    '#delta' => 0,
);

```

# Answer
I was unable to find an exact answer to this question, but I was able to find a work around to get the extensions to load.

using form\_alter, after the field is partially built in a form function

```
//set value for office extension
  if(
    isset($form_state['storage']['$profiles']['personal_information']->field_phone_office[LANGUAGE_NONE])
    &&
    $form_state['storage']['$profiles']['personal_information']->field_phone_office[LANGUAGE_NONE][0]['extension'] != NULL
  ){
    $field_phone_office_ext_value = $form_state['storage']['$profiles']['personal_information']->field_phone_office[LANGUAGE_NONE][0]['extension'];
  }
  else{
    $field_phone_office_ext_value = '';
  }

  $form['user-information']['user-information-fieldset']['profile']['phone']['field_phone_office']['extension'] = array(
    '#type' => 'textfield',
    '#title' => t('Ext.'),
    '#default_value' => $field_phone_office_ext_value,
    '#value' => $field_phone_office_ext_value,
    '#size' => 10,
    '#maxlength' => 10,
    '#weight' => 2,
    '#attributes' => array(
      'class' => array(
        'phone-extension'
      )
    )
  );

```
> 0 votes

---
Tags: 7, entities
---


# Question
Title: using contextual filters to filter with relationship
I have articles and issue nodes, where every article is related to an issue. I am trying to create a Views block which shows related Articles. This block should show on on the Article node page. What I tried was this:

I created a view of Articles. I set the relationship to Entity Reference: Referenced Entity field\_article\_issue and created a contextual filter on field\_article\_issue\_number (a field in issues) using that relationship. This didn't work, and the block shows nothing. What am I doing wrong?

# Answer
> 0 votes
You can't show both. When you choose to show articles, vieuws will select articles from the database using your conditions. Since an issue is not an article, they will not show.

What you probably can do is embed another view in your views header or footer section and display the related issues in that view.

---
Tags: views
---


# Question
Title: Views: Sort items using contextual filter arguments
Im trying to create a block of "Related products", I have 3 criterias for show the related products: Color, Texture and size. These are taxonomy vocabularies.

In the view I can use contextual filters for get the matching products while viewing another product. These results are sorted alphabeticaly by default in the view.

Im trying to show first the items that match the Color of the product, then the ones that match the Texture and then those that match the size.

Can someone tell me if this is possible? and how would you do it?

This is the screenshoot of the view

# Answer
> 1 votes
Yes. I would first get my contextual filters working so that my view was returning results for matching color, texture and size. Then I would use my Sort Criteria to add sorting filters to sort first by Color, then by texture, then by size. Order is important in the Sort Criteria.

---
Tags: views
---


title: Why won't my module table populate

text:
# Question
Title: Why won't my module table populate
I have a page that is supposed to output a table of values from my database. I am logged in as an admin and another page I created works just fine, outputting a form for data to be entered into the database. I have the following lines of code pertaining to the new page..

```
function achievementList_menu() {
$items = array();
$items['achievementList/list'] = array(
    'title' => 'Achievement List',
    'description' => 'A list of all of my achievements',
    'page callback' => 'achievementList_generate_table',
    'access arguments' => array('access content'),
);
return $items;
}

```

and

EDIT:

```
function achievementList_generate_table() {
$header = array('ID', 'Name', 'Description', 'Points');
$rows = array();
$results = db_query("SELECT * FROM {achievements}");

foreach ($results as $row){
    $rows[] = $row;
}

return theme('table', array('header' => $header), array('rows' => $rows) );
}

```

The headers render fine but the $rows array does not. Any idea why?

# Answer
I can see a few problems at first glance:

`'access callback' => TRUE,` will mean everyone gets access no matter what and make 'access arguments' redundant.

The default access callback is user\_access, which would accept your access arguments of `array('access content')`. So to use that just omit the access callback line.

`$items['achievementList/list'] = array(` is a strange path. Generally best to keep it all lower case but that's not a requirement.

`'page arguments' => array(1),` will be passing in the string "list" to your achievementList\_generate\_table() function, but there is no point passing in a parameter that never changes and you arent actually using it, so just `array()` is fine for those arguments.

For more information I recommend reading all of the documentation for hook\_menu().

The real problem though would be that your callback function is not returning anything for some reason.

(as per Clive's comment) I'm going to assume you are using Drupal 7. In which case your call to the theme() function is incorrect.

In drupal 7 all variables going into the theme function should be in an array, so your line should look like this:

```
return theme('table', array('header' => $header, 'rows' => $rows));

```
> 1 votes

---
Tags: 7, database
---


# Question
Title: Taxonomy view - showing term searched for in header
I've enabled the Taxonomy View template and used the taxonomy term page module to specify this view should be used when clicking on one of the taxonomy terms.

The page itself is working & looking great, but I'm struggling to show the vocabulary and term used in the header region.

Current view setup: https://www.dropbox.com/s/j38nsznel93eoz3/Screenshot%202014-10-22%2022.56.28.png?dl=0

I'm hoping to use one view for all the different vocabularies - but wanted to show in the header e.g.

All articles tagged \[author name\] - where the vocabulary used is 'author'

or

All articles tagged \[project\] - where the vocabulary used is 'project'

Anyone give me a pointer?

# Answer
I think @Neograph734 has eluded to the answer here.

If you add a field for taxonomy term name but don't display it (exclude from display), you can add a header field of type "Global Text" and render the term name from the collection of tokens that are representing the fields.
> 3 votes

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


title: Relationships Between Content Types

text:
# Question
Title: Relationships Between Content Types
I have 3 content types that I have created: order, product and salesperson.

The fields for each are as follows: Order: Purchaser Name, Product (entity reference to Product), Quantity Product: Product Name, Salesperson (entity reference to Salesperson) Salesperson: Name, Email

The way the system works is that a salesperson creates a product and then sells that product. Each product will be tied to a salesperson (no other salesperson can sell that product). Once they receive an order, they would create "content" containing the name of the person buying the product, what product it was, and the quantity they sold.

I'm trying to figure out how to create a view that would let me allow a user to choose a product and have the view show how many of that product were sold.

Did I set this up the right way using 3 different content types with entity references or is there a better option? If so, how can I show the sum of all the orders tied to a certain product?

# Answer
What you are looking for is the equivalent of SQL aggregation. I have done this successfully in a Drupal 6 install using the Views Group By module. The process is pretty simple as long as you are reasonably familiar with views. Your setup sounds like exactly what you should have for this case.

In Drupal 7, the equivalent functionality is built into the default views module. You will need to open the "Advanced" section to see it.

An alternative approach would be to write a custom module that creates the SQL aggregation itself. But it sounds like you are already familiar with views and should stick with this approach.
> 1 votes

---
Tags: views, nodes
---


# Question
Title: How do I target different types of anonymous user after a gateway page?
So there are a whole bunch of useful tools in Drupal for changing how a website looks depending on a number of factors, including which page you're on, what roles you have, whether you're logged in or not:

But I can't seem to figure out how to make the following use case work:

---

1. Anonymous user visits site

a. If user has never been to the site before (on this browser/computer), ask whether they are A or B

b. If user has been to the site before, figure out whether they are A or B (should be easy enough with cookies/session variables)
2. Change how site looks depending on whether user is A or B

---

It's really easy once they log in, but how do I tell anonymous users apart?

I tried installing ctools cookie context and ctools session context in the hope that I could use these to provide the necessary hooks for visibility settings in page manager... but visibility settings don't seem to use contexts!

Surely somebody has tried to do this before me? Maybe I am googling the wrong words but I've been at this for several days without a clear idea yet.

# Answer
Typical, no sooner than writing up my question do I find *an* answer. Though I'd love to hear if there are better ideas.

I discovered that you can use php to check the contexts in visibility settings. I didn't want to do this because I don't want to give the site admin access to php. However, I can make a couple of ctools access rulesets and make *those* available to the site admin to control visibility.

I haven't tried it yet but I think this will work, as long as the ctools context plugins work as I think they should.

\[edit: it worked\]
> 1 votes

---
Tags: 7, chaos-tool-suite
---


title: taxonomy auto-path views path issue

text:
# Question
Title: taxonomy auto-path views path issue
I have used the taxonomy menu and auto path to create a url alias something like below. The reason is so that the taxonomy menu has the right path.

/my-alias/\[term:name\]

I then enabled the taxonomy view and modified the view page so that it is like url below.This view grabs the taxonomy term and then filters that term and displays the fields in the view this works fine when I test it in the view itself

/my-alias/%

My question is how do I get drupal 7 to look at the view url first and not send it to the taxonomy alias?

# Answer
I think your problem lies in the fact that you are using the same URL for both a view and a node - this is a really bad idea in most circumstances.

If you always want the view to show - what does it matter if the taxonomy itself is at /category/tag/\[term:name\]?

You might find Page Manager useful for what you're trying to do, there's a fantastic free tutorial and familiarisation set of videos that have helped me immensely of late.
> 0 votes

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


# Question
Title: How to add paragragh information under hovered menu item?
Hi all, I want to add descriptions under my menu items like above (Eg. Home (ADD my description) Products (etc)? Do I have to create children under these menu items and enable these???? Any advice would be appreciated.

Drupal 7

# Answer
I think you're going to need to do a little (code) preprocessing of the menu in your theme layer.

To achieve this, I would put my description text in the "Description" part of my links (which is actually the title attribute) and then add a theme\_menu\_link() function to template.php (https://api.drupal.org/api/drupal/includes%21menu.inc/function/theme\_menu\_link/7).

Most people overload this function to add attributes to the menu links (like classes or ID's) but you could also adjust it to pull out the text you have placed in the title attribute, then mark it up however you want (span, div, etc..) and then return it in the Menu Link Title.

I see that you have also tagged your question with Superfish so you may need to review the theme superfish function as well (http://api.drupalhelp.net/api/superfish/superfish.module/function/theme\_superfish/7).
> 5 votes

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


# Question
Title: How to add an image property to an entity?
I have a requirement to add a unique icon to each bundle of an entity. My entity code is very similar to the model module. I have 2 entities, one for holding the actual entity instances, another for holding the type information.

Each entity type will have a unique icon which will be shown while adding that entity in the creation form. For this, I need to add a custom property to the entity which will hold the image file data.

# Answer
> 1 votes
You need to create an integer property that references the `fid` column in the `file_managed` table.

For inspiration, check out the `user_account_form()` function (the `picture` element) and associated validate/submit handlers. They show the exact methodology you need to use.

---
Tags: entities
---


# Question
Title: Form is not submit handler is not called
I have this code for calling a form and than submit it..

```
<?php
// hook_menu
function pricepackages_menu()
{
    $items = array();
    $items['membership/packages'] = array(
        'title' => t('Manage Membership Packages'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('pricepackages_form'),
       //'access callback' => TRUE,
       'access arguments' => array('access administration pages'),
    );
    return $items;
}
// FORM SHOW HOOK
function pricepackages_form($form, &$form_state)
{
    $form = array();

    $form['packagename'] = array(
        '#type' => 'textfield',
        '#title' => 'Package Name',
        //'attribute' => array('class' => 'package'),
        '#required' => TRUE,
    );
    $form['packageDescp'] = array(
        '#type' => 'textfield',
        '#title' => 'Package Short Description',
        //'attribute' => array('class' => 'package'),
        '#required' => FALSE,
    );
    $form['price'] = array(
        '#type' => 'textfield',
        '#title' => 'Package Price',
        //'attribute' => array('class' => 'package'),
        '#required' => TRUE,
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );
    $form['submit'][] = array('package_get_form'=> array());

    return $form;
}

function package_get_form($form, &$form_state)
{
    drupal_set_message('working');
?>
    <script language="javascript">
        alert("aaa");
    </script>
<?php
return;
    }
?>

```

but this one is not wokring proerly and form is not being submitted on the specific form... neither its showing alert or message...

please help me...

# Answer
> 1 votes
Change this:

`$form['submit'][] = array('package_get_form'=> array());`

to this:

`$form['#submit'][] = 'package_get_form';`

btw.

```
function package_get_form($form, &$form_state)
{
    drupal_set_message('working');
?>
    <script language="javascript">
        alert("aaa");
    </script>
<?php
return;
}
?>

```

This looks really messy. Try that instead:

```
function package_get_form($form, &$form_state) {
  debug('test');
}

```

But the best option would be to use standard submit handler instead declaring your own name convention:

```
function pricepackages_form_submit($form, &$form_state) {
...
}

```

# Answer
> 0 votes
You are missing the pound sign where you add the submit handler:

```
  $form['#submit'][] = 'package_get_form';

```

`$form['#submit']` should be an linear array, and each value should be a valid function.

Submit handlers will get `$form` and `$form_state` as arguments in that order. If the submit handler is not included, you can run `form_load_include` to make sure the file is included before calling the submit handler.

Also, note that you can add an implicit submit handler if you define a function named `pricepackages_form_submit`.

---
Tags: 7, forms
---


title: Why is this code causing an SQL error?

text:
# Question
Title: Why is this code causing an SQL error?
I wrote code to select records from the database, but it is causing the following error:

> PDOException: SQLSTATE\[42000\]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM pricepackages pricepackages' at line 1: SELECT FROM {pricepackages} pricepackages; Array ( ) in view\_packages() (line 25 of D:\xampp\htdocs \talyllyn\sites\all\modules\pricepackages\pricepackages.module).

What is wrong with the code I am using?

```
function view_packages() {
    $list = '<table>';
    $query = db_select('pricepackages')->execute();
    $i = 0;

    while ($record = $query->fetchAssoc()) {
        $list .= '<tr><td>';
        $list .= $record['packageName']."</td>";
        $list .= '<td>'.$record['packageDescp']."</td>";
        $list .= '<td>'.$record['pPrice']."</td>";
        $list .= '</tr>';
        $i++;
    }

    $list .= '</table>';
    return $list;
}

```

# Answer
> 2 votes
This is your current query as it's executed:

```
SELECT
FROM
{pricepackages} pricepackages

```

Which is obviously wrong; an SQL `SELECT` query needs one or more fields. To `SELECT *`:

```
$query = db_select('pricepackages')->fields('pricepackages')->execute();

```

Or specific fields:

```
$fields = array('foo', 'bar');
$query = db_select('pricepackages')->fields('pricepackages', $fields)->execute();

```

---
Tags: database
---


# Question
Title: Change the value of a field depending on the selection of another
I need to change the value of a field based on the selection of another. I also don't want the user to have the ability to change this value. I tried using `#disabled = true`, but the values don't *save*, and the same with `#access`.

I'm not sure how to go about this? `#disabled` seems to stop values from being saved - what alternatives are there?

This surely can't be unique, I know often date fields do this.

# Answer
> 1 votes
Converting the element to a `value` type might be easiest:

```
// In a form alter hook.
$form['field_foo'][LANGUAGE_NONE][0]['value']['#type'] = 'value';
$form['field_foo'][LANGUAGE_NONE][0]['value']['#value'] = 'some static value';

```

# Answer
> 0 votes
disabled fields by default are not submitted with the form not only within Drupal/PHP but in general those fields are not passed to the processor method. you can read about that in more details here.

@Clive suggested right answer, but other option would be to use form validation handler to assign the value before it is submitted.

```
//in form hook alter
form['#validate'][] = 'my_validation_handler';

```

and then:

```
function my_validation_handler($form, &$form_state) {
    //could be target_id instead of 'value' depending on the field type
    $form_state['values']['my_field'][LANGUAGE_NONE][0]['value'] = 'my_value';
}

```

---
Tags: forms
---


# Question
Title: insert advertisement block within views list
I have a view that output the content nodes as grid. (instigram style). How to insert an advertisement block in a random location within the views list.

Node Node . . Advertisement . . Node Node

# Answer
> 7 votes
You can override the format specific template like `views-view-unformatted.tpl.php` (you can find the right file based on your requirement) and then use some custom code like

```
  <?php if (($id % 2) == 0): ?>
    Do what-ever you want to do here.
  <?php endif; ?>

```

This module hosted on github https://github.com/pedroposada/custom\_views\_nthrow seems to do the same more modularly.

**Instructions :** http://www.pedroposada.com/blog/insert-whatever-every-nth-row-views.html-0

# Answer
> 1 votes
If you want to have your custom code after first row then override your default *views-view-unformatted.tpl.php* with this code:

```
<?php if (!empty($title)): ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>
  </div>
  <?php if ($id == 0 || $id == 5): ?>
Your custom adsense code
  <?php endif; ?>
<?php endforeach; ?>

```

Step-by-step tutorial for newbies on how to override default *views-view-unformatted.tpl.php* and achieve custom code after for example first and sixth row is here.

---
Tags: views, advertising
---


# Question
Title: Suppressing APC cache warning messages in watchdog log
My Drupal-oriented shared webhost recently updated PHP and APC and turned on reporting APC warnings. Now my watchdog log has many, many entries of the form `Warning: include() [function.include]: Unable to allocate memory for pool`, indicating that sometimes the cache is overflowing.

I know what these warnings mean: that's not my question. The APC cache is 96MB, which is big enough most of the time. But I have 127 enabled modules and certain page loads or doing admin work will overflow the cache. This doesn't occur on every page load by any means, but the warnings are filling up the log, making it hard to find more interesting entries, and causing the log to wrap more often than I'd like. I'm trying to cut down my needed modules but nearly all are there for good reasons.

I cannot change most of the APC settings (I might wish to use `apc.filters`, for instance).

Is there any module or other method that you know of that will filter messages before they get put in the log? I could make the log bigger, but I still have the problem of finding the wheat in the chaff of warnings.

# Answer
> 2 votes
You can create a module to use the hook\_watchdog function. This hook would kick in when there is an error so you can check the type of error decide not to write it to the table. But the variable seems to be passed not as a reference and hence I dont think you would be able to change the variable it self.

The logs are written to the table by the **dblog** module. using the hook implementation of the **dblog** module. Just make sure that your function gets called after this so that the entry is already in the db. this should be the case already if not you can set the priority in the systems table to make this effect.

Now within your hook function you can decide to delete the entry that is just written.

```
function dblog_watchdog(array $log_entry) {
  Database::getConnection('default', 'default')->insert('watchdog')
    ->fields(array(
    'uid' => $log_entry['uid'],
    'type' => substr($log_entry['type'], 0, 64),
    'message' => $log_entry['message'],
    'variables' => serialize($log_entry['variables']),
    'severity' => $log_entry['severity'],
    'link' => substr($log_entry['link'], 0, 255),
    'location' => $log_entry['request_uri'],
    'referer' => $log_entry['referer'],
    'hostname' => substr($log_entry['ip'], 0, 128),
    'timestamp' => $log_entry['timestamp'],
  ))
    ->execute();
}

```

Another option would to create a hook\_cron in your module and delete the wantchdog entries you dont want during the cron run.

# Answer
> 2 votes
Better to fix the APC error than suppress the error msg..

Note, more recent versions of PHP require the unit suffix on `apc.shm_size`

You might see an server log error `PHP Warning: PHP Startup: apc.shm_size now uses M/G suffixes, please update your ini files`

* **incorrect**: `apc.shm_size 256`
* **correct**: `apc.shm_size 256M`

There's also an issue queue for the `Unable to allocate memory for pool` error, with a few suggested solutions here:

https://bugs.php.net/bug.php?id=58982

# Answer
> 0 votes
Change you apc.ini settings like below

```
apc.mmap_file_mask=/dev/zero
apc.shm_size=64M
apc.ttl=0

```

it works

Refer apc.configuration.php

---
Tags: log-messages, caching
---


title: Custom content type add form

text:
# Question
Title: Custom content type add form
I am brand new working with Drupal 7 and I am working on a professional project and I would like some help to achieve some requirements.

We have some content types like associations. Authenticated users may add new associations after administrators validation. What is the best approach to display custom forms that are able to insert data as content types? This forms must appear in a non administrative environment, so, I don't know if there is something to export Drupal add/content form and display it to the authenticated user.

I will appreciate any help. Cheers!

# Answer
> 1 votes
Any administration page such as `/node/add` will be displayed in the selected theme, as long as the user has the permission 'View the administration theme' off (and of course has the relevant permission on, such as to create nodes for the specific type).

You wouldn't really need to create a custom form for that, the standard node create form may be sufficient. Of course you could, you would have to read the documentation such as this.

As far as the first requirement about validation from administrators, the modules Workflow and/or Rules would be useful.

---
Tags: nodes, forms
---


# Question
Title: How to hook drupal commerce line item create
I want to process something when a new commerce line item create, is there any hook can do this?

Or is there another methods can do this?

Thanks at first!

# Answer
> 0 votes
Look at this (hook\_hook\_info()) hook implementation in commerce\_line\_item.module, it exposes `commerce_line_item_insert` which gives you a chance to process some operations on insert operation..

You can use it like this:

```
function MYMODULE_commerce_line_item_insert($line_tem)
{
  // dpm($line_item);
}

```

# Answer
> 0 votes
Yes, you can use

---
Tags: commerce
---


# Question
Title: How to get flag count for any time period
I have View which displays a list of nodes with counters (flags), but the counters for all the time. How to display a list of nodes with counters (flags), for example, over the last week or last month?

# Answer
> 0 votes
Did you try to use the filter criteria : Flagged Time and eventually expose it to users?

Then you can define :
\- the operator: is equal to / is less than / ...
\- a specific date or offset

Is that what you are looking for?

---
Tags: 7, views, flags
---


# Question
Title: creating multi-country website, where each country's site is multilingual
I understand that you can create translations in many language for one website. But what if I want to create one website not just simply to be multilingual but for multi-countries and each country's website can be bilingual or trilingual.

For example, let's I have website example.com and its default country is USA. It will have 2 languages: English and Spanish When I click any of them it will take me to the corresponding page:

1. For English version: example.com/us/en/
2. For Spanish version: example.com/us/es

On the top menu I will have a menu called "Countries". When I click on "Countries", it can be take me to a "Countries" page that will show all the countries and languages they have, for example:

* United States - English - Español
* Japan - English - 日本語

Or "Countries" can be a drop-down list showing above.

**Can someone please share with ideas to implement this?**

**UPDATE 1**

I feel like this is related to MultiSite feature, but was not able to see any good working example on the web.

# Answer
> 4 votes
You need a mix of (at least) 3 modules to do this:

# Answer
> 4 votes
For anyone else interested as this is still a top result in Google for this problem, the **Country Path** module https://www.drupal.org/project/country\_path was released the other day which requires the **Domain** module https://drupal.org/project/domain but is a really good solution to this problem.

# Answer
> 2 votes
You create URLs based on language then by country, this you can configure in the Pathauto module.

For example us/en or us/es.

You can create multilevel menus to show list of languages in each country.

Then you can translate nodes using i18n or Entity Translation.

# Answer
> 1 votes
You could do a multisite environment, 1 per country, and then a multilingual shape over it.

You can find some tips searching "drupal multisite countries" in google.

# Answer
> 0 votes
You could also use purl for this. A disadvantage is that you would need to create an own language negotiation plugin if you want to have the language as the second parameter. Based on the purl prefixes you can add access control etc, etc. I have some code i could push to a drupal sandbox if you are willing to test it. If you want to have a nice UI with a lot of overhead i would go for domain module :)

---
Tags: i18n-l10n, multi-sites
---


# Question
Title: Module not returning echoing or printing variable
I'm writing a module to change a user's shopping cart order ID based on a stored value from their profile, which cannot be edited from the users.

In the hook call to `commerce_cart_order_id` I tried the following code, but it doesn't change the order ID. Printing `$orderidentifier` with `krumo()` shows `1`; if I change `return $orderidentifier;` with `return 1;` my cart changes just as I'd expect it to.

```
global $user;
$user_full = user_load($user->uid);
$orderidentifier = $user_full->field_currentcartorder['und'][0]['value'];
return $orderidentifier;

```

Can anyone tell me what I'm missing?

# Answer
fixed it I had to add an `$orderidentifier = intval($orderidentifier);` to convert it to an integer so the hook I was calling could understand it
> 1 votes

---
Tags: debugging
---


title: Views query building internals

text:
# Question
Title: Views query building internals
I have looked at the source code, briefly, and the problem is that the module is a complex "beast" that relies heavily on the core's API which I am not currently familiar with.

I have a kind of pieced together on how Drupal assembles a completed node object by traversing the various tables (node, node\_type, **field\_config**, field\_config\_instance, etc).

What confuses me is the data abstraction layer. **field\_config** has a storage\_type which appears to indicate whether a field is stored in SQL or not.

From what I have read and interpreted, Drupal is flexible enough to have a system which is data store agnostic, so if I had a *products* content type and capacity out-grew what MySQL was capable of, I could (in theory) switch to MongoDB or similar DBMS which allows better scaling.

1. So, how would I attach a field to a content type, which let's say was stored in Mongo, but the remaining fields stayed in SQL?
2. More interesting, how does VIEWS deal with this disconnection in data storage? If I store some fields for a given type in MongoDB and some in SQL how does VIEWS handle the JOINS and filtering capability?

# Answer
> 0 votes
As it currently stands it is not possible for Drupal to run a pure MongoDB installation with Drupal. Drupal has made a lot of progress towards abstracting out database connectivity into a central model layer with Drupal 7 and Drupal 8 promises even more. However it is still a work in progress and while a majority of the functionality is available as MongoDB backend, as it stands today a few of the components remain dependant on SQL.

As most of the work to port Drupal to MongoDB has been towards scalability and performance, it is possible to have a site where public page views are 100% on MongoDB. Performance benchmarks on a MongoDB backed Drupal instance are quite impressive.

---
Tags: views
---


# Question
Title: Field value of a content type is not saved
I have a content type (created through a feature) which has different fields. One field is a text field. It used to save data before but now it doesn't save any value. I checked in the table, the value is not there. I checked in `hook_node_update` the field is empty. I tried to write `hook_field_is_empty` in my module and also in feature but didn't help :(. W hat can cause this? Thank you.

# Answer
> 0 votes
Be sure to check you are accessing the field properly. I'd recommend adding `<pre><?php print_r($node); ?>` in one of your theme tpl files and then accessing it manually like `$node->field_example['und'][0]['value']`. It always helps me.

---
Tags: nodes, entities
---


# Question
Title: how to specify which region of panelpage can be displayed with php
I am using a page--front.tpl for my frontpage.

It overrides a panelpage whice i use for my frontpage.

I can display the content of my panelpage with `<?php print $content; ?>`

Is it possible to specify which region of my panelpage i can print with php?

# Answer
Yes, $page\['content'\] is an associative array. You can pick, which parts of the array you'd like to display. However, I think calling print directly is not the right way. Call the render() function instead:

```
<?php print render($page['content']['your_section']); ?>

```
> 0 votes

---
Tags: panels
---


# Question
Title: How to make custom Drush commands to work on remote instance
I have developed custom Drush commands that includes some shell commands all which work locally. I would like them to work also on the remote instance with aliases that have the remote settings. Here is how the shell commands are currently executed: //executes command

```
function execute_command($command)
{
    drush_log(dt('COMMAND: @command', array('@command' => $command)), 'notice');
    //any shell command fore example 'cp some/source dest/dir','tar xvf some.tgz',etc
    drush_shell_exec($command);
    drush_log(drush_shell_exec_output(), 'debug');
}

```

So, I would like to wrap this into some Drush API so they also execute on remote instance. Is it possible? How should I make the shell commands part of my custom Drush commands to run on the remote instance when user does something like:

```
drush @remote-alias custom-command

```

Thank You

# Answer
> 2 votes
I believe the remote site also has to have the commands as well in order to execute successfully.

---
Tags: drush
---


# Question
Title: Scheduling a module to run at a specific time
Is there any way to schedule a particular sub-module to run at a specific time? I found hook\_cron but it seems to rely on a scheduled cron job in crontab to run cron.php and then cron.php calls hook\_cron. I have multiple sub-modules that I would like to schedule to run, all at different times. The scheduled times are user-inputted from the front and processed in the main module. Because of this, for hook\_cron to work, I would need to pass in parameters from the main module (based on what the user inputted)

Any help is appreciated.

I am using Drupal 6

# Answer
Depending on how detailled your specific time is, you could still use `hook_cron`. For example, let's say the normal cron runs every hour, you could check `date('H')` in your module and only if it equals a predefined value, the cron function in your submodule will be executed.

```
function MYMODULE_cron() {
  if (date('H') == 3) {
    // this code will only be executed between 3:00am and 3:59am
    // do your stuff
  }
}

```
> 2 votes

# Answer
Take a look at Ultimate Cron \- I think it does what you want.
> 0 votes

---
Tags: 6, cron
---


# Question
Title: Module that allows visitors to suggest modifications on a node
I'm looking for a module (or some other way) that allows users to send suggestions about how to edit a certain node. I'll explain:

There is a node type with the following fields: name, description and phone number. One node contains these values:
**Name:** "Lulu's Restaurant"
**Description:** "A very good restrurant"
**Phone number:** "123456790"

A visitor notices that some values are incorrect, clicks on a link "send suggestion" and he's brought to a form where the fields are filled with the node's data. The visitor edits the fields

**Body:** "A very good restaurant"
**Phone number:** "1234567890"

And clicks on "send", this will memorize the data on drupal (on a different place than the node, but this has to be linked with the node) and notifiy registered users of this new suggestion.
Registered users should be able to see a comparison view of the original node and the suggestion (possibly with highlighted text, like your typical diff checker application) and then edit the node accordingly.

Registered users should also be able to change the status of the suggestions (pending, accepted, not accepted, spam).
Another feature i need is that visitors (unregistered) should be able to subscribe to nodes and receive notifications whenever the node is edited.

I think some basic features can be done with normal drupal features (like a node that can be created by unregistered users) or the rules module for notifications, but i was wondering if there's a specialized module to do this.

# Answer
Apart from the notifications, Workbench along with Workbench Moderation seems to meet most requirements.

Drupal only has two states for nodes: unpublished and published. With Workbench Moderation, you can define your own custom states, e.g. pending, accepted, not accepted, spam. You can then authorize anonymous users to edit nodes (make suggestions). These edits will create new revisions which will NOT be published until authorized users actually publish the changes.

Workbench Moderation also works well with Diff which allows you to compare different revisions to see the actual changes per field.

Finally, following nodes and notifications can be realized with the Flag and the Rules module.
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: MedialEment.js module not seeing the installed library
I've just installed the MediaElement.js module and downloaded the corresponding library but in the modules page it won't turn on because it's not finding the library.

i have other libraries running so i know it's in the right place.

the Media Module version is 7x-1.2 and the on the webpage the version is 2.15.1

i've cleared the cache, run Cron and renamed the folder to mediaelement

how the freak do you trouble shoot something like this? this should take like 10 mins to do and now it's going on 40mins trying to troubleshoot.

# Answer
The easiest way to debug something like this is to look at the MediaElement module itself.

Its implement of `hook_library()` contains the following:

```
$libraries['mediaelement'] = array(
    'title' => 'Media Element',
    'website' => 'http://mediaelementjs.com/',
    'version' => '2.1.6',
    'js' => array(
      // The mediaelement script detects the path to itself to call other files
      // in the same location. With preprocessing this is problematic as the
      // script is no longer in the same directory as its other assets. There
      // is an option that can be passed into the script with its location.
      // @todo Update all calls to mediaelement to pass in the assets location.
      $path . '/build/mediaelement-and-player.min.js' => array('group' => JS_LIBRARY, 'preprocess' => FALSE),
    ),
    'css' => array(
      $path . '/build/mediaelementplayer.min.css' => array('group' => CSS_SYSTEM),
    ),
  );

```

So it would appear the module is looking for

* sites/all/libraries/mediaelement/build/mediaelement-and-player.js
* sites/all/libraries/mediaelement/build/mediaelementplayer.min.css

If you make sure those files are in the right place, you should have no more issues.
> 2 votes

# Answer
* check folder permissions of your `sites/all/libraries/mediaelement` folder
* use Firebug or Chrome Developer tools, or equivalent, and check the `Console` for any javascript errors.
> 1 votes

---
Tags: 7, media
---


# Question
Title: Display suite fields visibility restriction
Is there a way in DS fields visibility restriction with url pattern?

# Answer
> 2 votes
Yes. You can create a custom view mode with DS, add or remove fields as you wish, configure that view mode to use a DS layout, then access the view mode through a URL.

The structure looks like this for the "full" view mode: node/x?v=full.

You need to enable a DS Extra setting called "View mode per node" at admin/structure/ds/list/extras

---
Tags: display-suite
---


# Question
Title: How to alter tabs that have wildcard in bartik main menu
The problem is that I have some menu items with wildcard that I wanna add in main menu tabs, but can't realize how to do it. It can't be solved by `hook_menu` as I undestood. Tried use `preprocess_links__system_main_menu`, `menu_tree__main_menu` but they didn't execute. How correctly do this?

# Answer
Solve this by page preprocess function. Not sure is this correct way or not.

```
function mobitek_custom_preprocess_page(&$vars) {
  $nid = arg(1);
  $node = ($nid && arg(0) == 'community' && is_numeric($nid)) ? node_load($nid) : FALSE;
  if (!$node) {
    return;
  }
  $main_menu = &$vars['main_menu'];
  $mobitek_menu_items = array(
    'communities',
    'reports',
    'administrators',
    'users',
  );
  // Remove links by this.
  foreach ($main_menu as $key => $menu_array) {
    if (isset($menu_array['identifier']) && in_array($menu_array['href'], $mobitek_menu_items)) {
      unset($main_menu[$key]);
    }
  }

  ....

  foreach ($community_links as $title => $community_link) {
    $new_tab = array(
      'title' => $title,
      'href' => $community_link,
    );
    array_unshift($main_menu, $new_tab);
  }

  // Add link by this.
  if (arg(0) == 'community' && arg(2) == 'profiles-roles') {
    $on_roles_page = (arg(3) == 'user-roles');
    $profiles_item = menu_get_item('community/' . $nid . '/profiles-roles/user-profiles');
    $vars['tabs']['#primary'][] = array(
      '#theme' => 'menu_local_task',
      '#link' => $profiles_item,
      '#active' => !$on_roles_page,
    );
    $roles_item = menu_get_item('community/' . $nid . '/profiles-roles/user-roles');
    $vars['tabs']['#primary'][] = array(
      '#theme' => 'menu_local_task',
      '#link' => $roles_item,
      '#active' => $on_roles_page,
    );
  }
}

```
> 0 votes

---
Tags: routes
---


title: Login 403. Hit with SA-CORE-2014-005

text:
# Question
Title: Login 403. Hit with SA-CORE-2014-005
I don't know why, but I can't find a straight answer to this anywhere. I have a site that was by the vulnerability patched by SA-CORE-2014-005. I went into the database and deleted the user and applied the update via ftp, but I still can't log in. /user gives me a 403. How do I fix this?

# Answer
> 2 votes
Okay, here is how I did it. Hopefully it will help someone else. After uploading the new drupal core, I went to the settings.php and set the $update\_free\_access = TRUE;. This will allow you to apply the update without being logged in by going to site.com/update.php.

Once that was done, in the database, I truncated the cache tables and I was able to log in and fix everything.

Hope this helps.

---
Tags: users
---


# Question
Title: Commerce: save quantity button removing products
I've come across a frustrating issue after adding a cart view block on my page in the form of a "sidebar". When trying to update a quantity or just clicking the "save" button (at bottom of the view) itself will remove the first line item added to the cart. Finally, a message shows on the next page saying: "line item removed."

I have disabled all non essential and potentially problematic modules. There is no custom Javascript / AJAX written for this button. I've checked the error logs and there is nothing wrong there.

Oddly enough, the feature works fine on our live site using a different theme. I have exported the views and ensured they are both exactly the same.

Does anyone have a clue what might be causing this? Or, any debugging steps I could try out?

Note: I'm on Commerce Kickstart 2.x-2.19

# Answer
> 2 votes
The issue is that I had written some javascript to change the value attribute of the "save" input to "update". After changing it back to "save" the button works just fine and nothing is removed from the cart.

To confirm, I went to a different theme and changed the value attribute of the "save" button to "foo" and it started removing line items from the cart.

---
Tags: views, theming, commerce
---


# Question
Title: Move Multi-lingual Content with Migrate Module
I've got a single MySQL table with mixed english/french content in each row. I'm trying to figure how to migrate this into a proper i18n configured Drupal site.

I can get Migrate to import the content into one language, but I want it to import it into both languages. There are 901 rows, so it should ultimately create 1802 nodes that are linked.

I just can't figure out how to set up the Migrate module to loop through twice & link the nodes.

EDIT: I used this and was able to merge the two:

```
public function postImport() {
parent::postImport();

// $ii should really be determined by $count_query
$ii = 2000;
for ($i = 1; $i < $ii; $i++) {
  // Confirm SQL in phpMyAdmin to verify
  $query = "SELECT n.nid, tid.field_bv_transfer_id_value
    FROM {field_revision_field_bv_transfer_id} tid
    INNER JOIN node n ON tid.entity_id = n.nid
    WHERE tid.field_bv_transfer_id_value = $i;";
  $result = db_query($query);

  // Reset for each import
  $currentRowCount = $current_translateid = 0;
  foreach ($result as $record) {
    if ($currentRowCount % 2 == 0) {
      $node = node_load($record->nid);
      $node->pathauto_perform_alias = FALSE;
      $node->tnid = $record->nid;
      $current_translateid = $record->nid;
      node_save($node);
    } else {
      $node = node_load($record->nid);
      $node->pathauto_perform_alias = FALSE;
      $node->tnid = $current_translateid;
      node_save($node);
    }
    $currentRowCount++;
  }
}

```

}

# Answer
You can create two migrations, both with the same mapping (except for the nids), but one saves nodes in English and the second in French.
> 2 votes

# Answer
In prepareRow() you return either true or false. This determines whether that row is processed in that particular migration (and counted even).

This way, you can detect the language for each row, and only return TRUE for rows that contain content in the specific language for that migration.

so you could do something like:

```
public function prepareRow($row){
  $return = FALSE
  if ($row->lang == "fr"){
   $return = TRUE;
  }
  // Only rows with a source 'lang' value of 'fr' are processed
  return $return;
}

```

An even more performant way to do this, if you are going to do the dual migrations thing, would be to add a condition() to each source query (if you are using MigrateSourceSQL), such as -\>condition('lang','en','=').
> 1 votes

# Answer
(The following applies to Drupal 7 — I don't know about Drupal 6 or before.)
I presume you want to define the relation of translation between English and French nodes. To do that, first, each node should have the defined language, as defined in `prepareRow()`:

```
$this->addFieldMapping('language', 'language_code');
$row->lang_dest = 'fr'; // or "en", depending on the row.

```

Second, you need to somehow define the `tnid` of the source-node to be its own `nid` and the `tnid` of the translation node to be the `nid` of the source node. Note you can choose the random language for the source node, and so it is even acceptable to mix up the source-language between different contents. The question is how.
(Note I think that is all you need, but I might be wrong. I followed the steps in the second case below, and succeeded.)

If you explicitly specify the node-number (=`nid`) of each row in your migration, then it is easy, because you know which row corresponds to which `nid`, even before you import those nodes. So, you can just set `tnid` of each row as such. Obviously, you must be careful not to conflict the imported `nid` with any of the existing `nid`s in the Drupal contents.

If you let Drupal decide the `nid` of each imported row, then it is more tricky. I did with the 2 steps. First, I imported all the source-language rows, adding a custom field to identify it as the source node for the later use. Second, I imported the translated-language rows and set up all the `tid`s of both source and translated-language nodes. These two steps can be completely different modules, but are perhaps handier if you define those two as separate classes in the same (migration) group in the varialbe `$api` in your `Your_ModuleName.migrate.inc`.

For the second step for the translated language, I wrote as follows. In short, it finds the source-language node with the SQL query, based on the custom field `field_original_html_filename`, which was defined when it was imported.

```
// In prepareRow()
//   Set up tnid, obtaining the nid from the node already imported.
    $this->addFieldMapping('tnid', 'row_tnid');
    //
    $field_name = 'field_original_html_filename';
    $query = sprintf("SELECT n.entity_id FROM {field_data_%s} n WHERE n.%s_value = '%s'",
                     $field_name, $field_name, $fbasename_trans);     // entity_id == nid of Node
    $result = db_query($query);
    $nid_trans = $result->fetchCol()[0];
    $row->row_tnid = $nid_trans;      // In my case, it is guaranteed there is only one candidate.

// In prepare()
//   Forcibly set up (Change) tnid of the node already imported.
  public function prepare(&$node, $row) {
    if (isset($node->tnid) && ($source = node_load($node->tnid))) {
      $node->translation_source = $source;
    }
  }

```

That is all. I am not surprised if there would be an easier or better way, but it worked for me. Anyway an advantage to set up the translations during migration is you can always rollback. As a reference my entire migration code (for 2 languages, from the static HTML files) is available at GitHub:
https://github.com/masasakano/migrate\_goo
> 1 votes

---
Tags: i18n-l10n, migrations
---


# Question
Title: How to best handle "sudo: no tty present and no askpass program specified"?
I have custom Drush commands that contain shell commands with 'sudo' included. This results in an error when calling with remote alias to execute on remote instance:

```
drush @remote-alias custom-command-with-sudo

```

From research in google.com, I understand there is not tty session loaded when doing `ssh user@ssh-server` causing the error:

```
sudo: no tty present and no askpass program specified

```

Can I configure drush to include `-t` flag when its doing `ssh -t user@ssh-server`. I understand this will load tty session and solve problem, am i wrong?...in short, how do you best overcame this issue? Thank you

UPDATE: I followed instructions from similar question referred by Clive

1. Added following line in `.drush/drushrc.php`:

```
$options['ssh-options'] = '-o PasswordAuthentication=no -i $HOME/.ssh/id_rsa/lamp_vbox';

```
2. Then I run in debug mode by adding --debug and this is what it shows:

> Calling proc\_open(ssh -o PasswordAuthentication=no -i /Users/owner/.ssh/id\_rsa/lamp\_vbox margots@lamp-vbox 'COLUMNS=179 drush --debug --uri=dev-metronic --root=/home/websites/dev/metronic --verbose deploy-asset '\\''@dev-metronic'\\'' --ver=0.3 --asset=metronic --env=dev 2\>&1' 2\>&1); Starting Drush preflight. \[0.06 sec, 1.51 MB\]

From the log, I conclude that the settings are being passed, however. I still get the error, so I wonder what could be the problem and how to solve it.

I'm using: Mac 10.9, Drush Version : 7.0-dev

# Answer
> 1 votes
This may not be solution for everyone, but it worked in my situation because i could change settings at the remote instance. I followed the following instruction and turned on `NOPASSWORD`, which is adding the following line into sudoers file:

```
# Members of the admin group may gain root privileges
%admin  ALL=(ALL) ALL

```

Afterwards, my custom drush commands with sudo works on the remote instance

---
Tags: drush, ssh
---


# Question
Title: Can you modify the settings.php file using drush?
I am trying to create multisites and the first one is up fine and running. I am trying to use drush to install a 2nd site but I need the settings.php file to point to a different db. Can I modify my drush command to do that or am I going to have to modify the settings.php by hand each time?

```
sudo drush -y site-install standard --db-url=mysql://$username:$pass@127.0.0.1:3306/$dbname --site-name="$sitename" --sites-subdir="$sitename"

```

# Answer
> 1 votes
What you really need here is different `settings.php` files for your production and development environments.

There are multiple ways of achieving this, some examples:

I usually include the following lines at the end of the `settings.php` file (in all instances):

```
// Override settings in this file.
if (file_exists('./' . conf_path() . '/local_settings.php')) {
  include_once './' . conf_path() . '/local_settings.php';
}

```

And then change the `$databases` array there, and any other specific environment settings.

You may also find useful the following links:

# Answer
> 1 votes
You can try to use drupal\_rewrite\_settings() function (in install.inc) which Drupal uses to write the `$databases` variable to your settings.php, in example:

```
drush eval '
include DRUPAL_ROOT."/includes/install.inc";
include DRUPAL_ROOT."/includes/update.inc";
global $db_prefix;
$db["databases"]["value"] = update_parse_db_url("mysql://root:root@localhost/drupal7", $db_prefix);
drupal_rewrite_settings($db, $db_prefix);
'

```

This will override your `settings.php` file so use it with caution. Change db url (`mysql://root:root@localhost/drupal7`) based on your correct db credentials.

See:

---

Alternatively you can check similar approach from update.inc:

```
function update_fix_d7_requirements() {
  // Rewrite the settings.php file if necessary, see
  // update_prepare_d7_bootstrap().
  global $update_rewrite_settings, $db_url, $db_prefix;
  if (!empty($update_rewrite_settings)) {
    $databases = update_parse_db_url($db_url, $db_prefix);
    $salt = drupal_hash_base64(drupal_random_bytes(55));
    file_put_contents(conf_path() . '/settings.php', "\n" . '$databases = ' . var_export($databases, TRUE) . ";\n\$drupal_hash_salt = '$salt';", FILE_APPEND);
  }

```

---
Tags: drush
---


title: Rate widget not working in views

text:
# Question
Title: Rate widget not working in views
I have an image gallery which I've made using views and each image has a yes/no rate widget. When the image is clicked a popup box is shown with the image in it which I have made using colorbox. I have also added the yes/no rate widget in the pop up box. The problem is that the rate widget is not working in the gallery but it works inside the popup box. How can I make it work in both the places?

This is strange, but when I click on the rate widget in the popup box for a certain image, it starts working in the gallery as well but only for that image.

This is what my views looks like. Only the `(Votes)Votes:Value` appearing first is working first and then after clicking that the other one works for that particular content.

# Answer
It's because you used the "Votes: Value" twice, use it once, "Exclude it from display" and render it using tokens as many time as you want and you must be good to go.
> 1 votes

---
Tags: views, 7, rating, javascript
---


# Question
Title: Use product entity field as filter in Views
I have a product (type: "lamp") with a text field called "power". On the Product display node ("showcase") i also want to see a block made with Views. It must show three other products of the same type AND power value. So Views should get a field's value of product rendered on the same node. I've tried a lot of modules, various relationships combinations, but still can't get a product's entity field value. Please tell me, what modules do i need and where should i go step by step. (here are the modules i've installed: References, Entity Reference, Field reference, Node Reference, Field collection)

# Answer
I recently learned how to do this kind of thing.

You need Page Manager which comes as part of Chaos Tools for d7, and Panels.

1. In Page Manager, enable and edit the path /node/%node
2. Set the selection criteria to node-type = showcase
3. Create a context based on the entity reference field, or if that doesn't work you might need the Relation module.
4. Create another context based on the power field (you might like to use a taxonomy for that)
5. Make a view that uses the context to choose the products to display
6. Back in page manager, under Content, use Panels to determine where and how you want node and the view to display.

Follow the first link ("learned") for a much more thorough tutorial.
> 0 votes

---
Tags: commerce, views
---