# Question
Title: When and where does Panels get the title out of a View?
Two part question about Drupal 7, Panels 3, and Views 3.

I have a view that I have added to a content area in a panels page. Right now, the title from the display is being used as the pane title. I need to dynamically set the title of this from a module.

1. When does Panels pull out the display title from the view?
2. Where exactly does it pull it out from?

I cannot seem to override this from any view hook. For example,

```
function foo_views_pre_view (&$view, &$display_id, &$args)
{
    $view->display[$view->current_display]->display_options["title"] = "Foo";
}

```

doesn't seem to affect the pane title, though the value does propagate through all of the other view hooks.

I suspect I can create a workaround and use a custom block instead of the view directly, but I would rather not do that in this case.

Thanks.

# Answer
> 5 votes
I was hoping that someone would answer this, so I wouldn't have to answer my own question when I found the solution.

Credit goes to a co-worker (who doesn't really post here) who reminded me that you also need to update the handler:

```
function foo_views_pre_view (&$view, &$display_id, &$args)
{
  $view->display[$view->current_display]->display_options["title"] =
  $view->display[$view->current_display]->handler->options["title"] = "Foo";
}

```

When you do this, the title does propagate properly to the pane title.

# Answer
> 2 votes
Drupal grabs the view title from the view itself when the view is rendered.

You can over ride this in the panels settings area, by manually setting it.

Revision:

Have you tried doing this with a preprocess function something like

```
function MYTHEME_preprocess_panels_pane(&$vars) {
 if ($vars['pane']->type == 'node_title') {
  $vars['template_files'][] = 'panels-pane-node-title';
 }
}

```

---
Tags: 7, views, panels
---


# Question
Title: How to replace a string in a URL field when outputting it in a template file
I created a new field for URL. What would the best way to replace certain strings in the URL when outputting the field into the field--field\_url.tpl.php file be?

For example, in http://example.com/master/m/ I need to remove the "http://" part, and replace *master* with *slave*.

It is a single field; there will be no `foreach()` loops.

==== edit after using preprocess === i got a undefined index: field\_url

with the devel i get this

```
field_url
   und
     0
       value

```

i put in the preprocess

```
$link = $variables['field_url'][LANGUAGE_NONE][0]['value'];

$link = str_replace('http://', "", $link);

$link = str_replace('master', 'slave', $link);

$variables['link'] = $link;

```

is this right?

====== entire hook =======

```
function lessxless_preprocess_field(&$variables)
{
    $link = $variables['field_url'][LANGUAGE_NONE][0]['value']; // grab value

    $link = str_replace('https://', "", $link); // trim http://

    $link = str_replace('master', 'slave', $link);

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

sites/all/themes/lessxless/template.php

```

# Answer
> 3 votes
You probably want a preprocess function in your template.php for this. In your case, hook\_preprocess\_field() will be easiest to work with - for an example of how this is implemented, check out the API documentation for template\_preprocess\_field().

Remember, $variables is passed into preprocess hooks by reference. From within your hook\_preprocess\_field(), instead of modifying the field data directly (in case you need it elsewhere), you could do something like this after checking that you're operating on the right field:

```
/* devel's dpr() is handy for seeing where in the $variables array it lives if you
   don't have a debugger handy. If you see 'und', that's the value for the LANGUAGE_NONE
   constant. It's considered best practice to use the constant instead. */
$slave_link = $variables['field_url'][LANGUAGE_NONE][0]['value'];
$slave_link = str_replace("http://", '', $slave_link); // Trim http://
$slave_link = str_replace("master", "slave", $slave_link); // s/master/slave
$variables['slave_link'] = $slave_link;  /* You can now access this variable from your
                                            field--field_url.tpl.php as $slave_link */

```

You may also need to clear your cache after making these changes.

---
Tags: 7, entities
---


# Question
Title: Create relation N:N and specify properties for each relation
I have two content types: "Car" and "Options". My cars can have different options, so I could associate options to a car with References Module. But my problem is I'd like to specify the price of the option for each car/each relation.

Example:

```
Seat    - Airbag - 100 €
Citroen - Airbag - 88 €

```

The relation is not only a node reference, it has "metadatas".

For the moment, I plan to develop my own module, maybe "Relations" module will be the solution, but I tried it with no success.

How can I solve this problem?

# Answer
If there is an existing contrib module for that, that would be Relation. It works at the level of Entities. It should provide a generic API/framework that can be used for what you describe.

If Relation doesn't fit your needs or is not ready for you, then writing a custom module would be the only option. For a custom module, I would work at the Entities level (with the help of the Entity API module), not directly in SQL. While Drupal doesn't provides scaffolding for Entities, it provide helper functions such as field\_attach\_form() or field\_attach\_insert() to deal with fields on entities. Unfortunately, the documentation on how to properly use entities is still scarce. The Model module is an attempt to help there since it aims to *provide a model entity and entity administration interface to kick-start your entity development*.
> 3 votes

# Answer
Field Collection is another option. IMO it has a better user interface than Relation out of the box, especially if the relationships can be considered directional.
> 1 votes

# Answer
A good module is the Dynamic properties module which does exactly what you want. There is a demo.

Maybe you would like to check the Entity Construction Kit (ECK), which helps you to develop entities, and maybe rules and relation integration for multiple values field collection.
> 0 votes

# Answer
As you point out, you have the option to develop your own module. In this case, that would be my advise.

Nodereference module (packaged in the CCK bundle) is **not** a generic relations-module. It can be used for what the description says it is: *Defines a field type for referencing one node from another*. With some creativity one can abuse this to create generic N:N and 1:N and even polymorphic relations, but that is never optimal; both technical/performancewise as usabilitywise.

Things you cannot do (well) with this module:

1. Associate things to things other then nodes-to-nodes.
2. Keep the SQL and tabledefinitions optimal for your specific cases, filters and searches.
3. Validate across relations: If child misses a required field, don't proceed with parent.
4. Atomic updates and inserts: If Relation X fails, don't write its parent Y (or roll it back)
5. Implement businesslogic: e.g. An order is either unshippable OR has a shipping-address associated.

However, Writing your own solution comes with a lot of downsides, most notably:

1. Drupal (6) has no ORM, Drupal 7 has one, but is underused. You will be doing all the DBA interaction "by hand". Required effort one might not expect in a "framework"
2. Drupal gives no scaffolds, APIs and such for CRUD-actions: you will be writing all the forms, pages, storage- and update- handlers by hand. Obviously using Drupal-APIs, but nonetheless, often over 2000 lines of PHP just to manage some "items" and their associations. Nodes on the other hand, *do* come with such benefits "for free".
3. Drupal has little or no validation-helpers. You will be writing all your validations in your own PHP. The FormAPI comes with basic (but solid) mass-assignment-protection, but offers little validations on things like dates, lengths\[1\], sizes, ranges etceteras.

\[1\] As such, many contributed modules (and even core) have quite often bugs where the input allows a lot longer texts or numbers then the database can store according to its schema: simply because developers did not write validators for them.
> -1 votes

---
Tags: 7
---


# Question
Title: How to associate a node with a menu without adding it to the menu
Since menus drive the breadcrumbs by default in Drupal, is there a way to associate a node with a menu without actually adding it to the menu? I am trying to maintain a concise menu that nodes can be associated with on the node edit page, without having every node that I associate with the menu then becoming yet another item in an ever growing menu tree.

# Answer
I am not exactly sure of what you are trying to accomplish here, but it sounds like you are trying to use menus to alter the breadcrumb behavior

If that's the case, you should try the menu breadcrumb module - http://drupal.org/project/menu\_breadcrumb or the custom breadcrumb module - http://drupal.org/project/custom\_breadcrumbs

Hope this helps
> 1 votes

---
Tags: routes, breadcrumbs
---


# Question
Title: How do I migrate an image field with migrate 2 module on drupal 6
I have created my .module and .info and (one) .inc file.

I also have successfully used drush mi to import the data minus the images.

The images are in a related table in the database and are not being copied over when I run the migrate class. Here is my code:

```
    abstract class RoRMigration extends Migration {
     public function __construct() {
     parent::__construct();

     }
   }

    class RoRPagesMigration extends RoRMigration {
      public function __construct() {
      parent::__construct(MigrateGroup::getInstance('pages'));
      $this->description = t('Ruby on Rails Pages');

$this->map = new MigrateSQLMap($this->machineName,
  array(
    'page_id' => array(
      'type' => 'int',
      'unsigned' => TRUE,
      'not null' => TRUE,
      'description' => 'Page ID',
      'alias' => 'pid',
    )
  ),
  MigrateDestinationNode::getKeySchema()
);

$query = db_select('migrate_ror_pages', 'pid')
         ->fields('pid', array('page_id', 'title', 'content_subtitle', 'body_html', 'page_type',
          'redirect_url', 'published', 'meta_data', 'pretty_url'));

$source_fields = array(
 // TODO: Will add these other files later
 // 'banners' => t('Banners attached to this page; populated in prepareRow()'),
 // 'files' => t('Files attached to this page; populated in prepareRow()'),
  'images' => t('Images attached to this page; populated in prepareRow()'),
);

$this->source = new MigrateSourceSQL($query, $source_fields);
$this->destination = new MigrateDestinationNode('page_data');

// Mapped fields
$this->addFieldMapping('title', 'title');
$this->addFieldMapping('field_legacy_guid', 'page_id');
$this->addFieldMapping('field_legacy_content_subtitle', 'content_subtitle');
$this->addFieldMapping('field_legacy_html_body', 'body_html');
$this->addFieldMapping('field_legacy_page_type', 'page_type');
$this->addFieldMapping('field_legacy_redirect_url', 'redirect_url');
$this->addFieldMapping('field_legacy_published', 'published');
$this->addFieldMapping('body', 'meta_data');
$this->addFieldMapping('field_pathauto', 'pretty_url');

// We will get the image data from a related table in prepareRow()
$arguments = MigrateFileFieldHandler::arguments('file_copy', FILE_EXISTS_REPLACE);
$this->addFieldMapping('field_gallery_images', 'images')
     ->arguments($arguments);

// No unmapped source fields

// Unmapped destination fields
$this->addUnmigratedDestinations(array('status', 'promote',
  'revision', 'language', 'uid', 'revision_uid', 'created', 'changed', 'teaser', 'sticky', 'field_file_attached_file', 'field_legacy_link', 'field_legacy_byline', 'field_banner_image', 'path', 'pathauto_perform_alias'));
      }

      public function prepareRow($current_row) {

        $source_id = $current_row->page_id;

// This adds the images to the image_gallery field
$result = db_select('migrate_ror_pages_images', 'pic')
          ->fields('pic', array('filename_path', 'title'))
          ->condition('page_id', $source_id)
          ->execute();
$current_row->images = array();
foreach ($result as $row) {
  $image_data = array(
    'path' => $row->filename_path,
    'alt' => $row->title,
    'title' => $row->title,
    'description' => $row->title,
  );
  $current_row->images[] = drupal_to_js($image_data);
}

return TRUE;
    }
   }

```

So to be clear. There are two data tables migrate\_ror\_pages and migrate\_ror\_pages\_images. The first table imports fine but the images do not import. The image table has a url to the image like this /sites/all/default/files/uploads/page\_assets/images/filename.jpg and it has a title column, page\_id, and image\_id. There are more than one images per page.

# Answer
> 2 votes
Okay so I figured out what was wrong. I needed to put the site url in front of the path in my db.

```
  public function prepareRow($current_row) {

    $source_id = $current_row->page_id;

    // This adds the images to the image_gallery field
    $result = db_select('migrate_ror_pages_images', 'pic')
      ->fields('pic', array('filename_path', 'title'))
      ->condition('page_id', $source_id)
      ->execute();
    $current_row->images = array();
    foreach ($result as $row) {
      $image_data = array(
       'path' => $row->$GLOBALS['base_url'] . filename_path,
       'alt' => $row->title,
       'title' => $row->title,
       'description' => $row->title,
      );
      $current_row->images[] = drupal_to_js($image_data);
     }

```

The line that needed to be changed was the one regarding the path to the image. I was using a relative path /sites/default/.../filname.jpg and I needed to use a full path:

```
           'path' => $row->$GLOBALS['base_url'] . filename_path,

```

So if you are trying to import images/files you will need a full path to the image not a relitave one!

Hopes this helps someone.

//Craig

---
Tags: 6, files, migrations
---


# Question
Title: Page not found on new server in Drupal 7 custom module
I have a custom module that uses `hook_menu()` to create new routes. It works on all my existing Windows development boxes.
I've recently set up an Ubuntu box, and installed Drupal; everything seems to work aside from the custom routes. I have a menu callback for "test" that gives me a 404 error. I have confirmed that `hook_menu()` is called in the code. I have clean URLs enabled, and the "Add content" link goes to "node/add," so it seems that clean URLs/URL rewriting works.

I should add that visiting "?q=node/add" works fine, but "?=test" does not. It seems like on this machine something weird is happening with the menu system.

# Answer
Turns out the module requires curl which the server didn't have. The module didn't bring down the whole site but just didn't work itself. No way anybody could have diagnosed that!
> 1 votes

# Answer
The menu cache needs to be rebuilt; log in as administrator, and visit the modules page.
> 0 votes

---
Tags: routes, hooks
---


# Question
Title: How can I link a text field to a user profile such that I can display nodes on the user profile based on that text field
I'm trying to create a relationship from thin air, at least that's how it feels.

I have two account roles. Producers and Instructors. I want to be able to reference nodes (events) created by Producers on the related instructors profile page and vice versa. The caveat is that the 'referenced' accounts may not yet exist.

For example:

* Producer A creates an event and lists Instructor B (who has an acct and profile) and C (who does not have an account) as the instructors via a multivalue text field (reference field is not possible here).
* Once the node is saved, the system checks for a relationship between the text field data and user profiles. A relationship exists for Instructor B, so the nodes are displayed on her profile. No relationship exists for instructor C yet, so nothing happens.
* instructor C comes a long and makes an account, when the account is saved the system checks for relationship again and finds a relatioship between previous nodes and this new account, the nodes are displayed on the profile.

I am thinking this field could be an email address or something. Is this possible and does anyone have advice on where to get started?

# Answer
> 1 votes
I can see how you'd want the Producer to be able to create an event and assign instructors to it before the instructor has an account. So in that case, have a node type which represents the instructor. This would be like a bio page or CV or some-such.

Then use nodereference and/or entityreference fields, Views, and viewreferences to connect the dots. The Event type would have Instructor fields which would refer to the bio pages for the instructors. As the instructors created accounts, a viewfield on the user profiles would show the bio page, keyed by an email acct field which you'd be sure and add.

Complex but not hard. :-)

---
Tags: nodes, users
---


# Question
Title: Displaying an image in a programmatically created block (Drupal 7)
I have created a custom block module that will display the children of a taxonomy term and if a term has no children it will display the nodes of that taxonomy in a table. The node type that they are showing were created using CCK and contain an image field and I would like to display the contents of the image field in this table.

So far I have only figured out how to be able to display the name of the node with a link and the time/date the node was last updated, but have not been able to figure out how an image might also be displayed. Could anyone offer advice about how to do this or point me to some documentation on the topic? Everything I found suggested that I should use CCK but for this particular problem I think I need to create my block programmatically.

**EDIT:**

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

  $block = array();
  switch ($delta) {
    case 'children':
      $path = explode('/', drupal_get_path_alias($_GET['q']));

      $tid = array_pop($path);

      $term = taxonomy_term_load($tid);

      // Set up the table rows and headers array
      $rows = array();

      $children = taxonomy_get_children($term->tid, $term->vid);

      $title = "Child Name";

      $header = array($title, 'Updated');
      // Add a new row for each child term
      foreach ($children as $child) {
        $rows[] = array(
          l($child->name, "taxonomy/term/$child->tid"),
          $child->vid
        );
      }

      // Set up the params for the theme_table call
      $table = array('rows' => $rows, 'header' => $header, 'empty' => 'No terms found');

      //$block['subject'] = t('');
      $block['content'] = theme('table', $table);

    break;
  }

  return $block;
}

```

# Answer
Some code could help us help you. But as it is, why not creating the `<img>` tag yourself based on the file path found in the `$node`variable ?
> 1 votes

---
Tags: 7, blocks, media
---


# Question
Title: display views3 output at page--mypage.tpl.php
Using drupal7 views3 i created views(products) to display an image and relevant title of my content. I selected in products to display content as block not page. I created an overriding page template page--mypage.tpl.php, where i impose my own html-css layout. My question is, that i want to display the content of newproducts block at page--mypage.tpl.php:

\[title\] \[image\], \[title2\]\[image2\], \[title3\]\[image3\]

I have created the html/css in page--mypage.tpl.php for the above layout. Now, i don't know how to retrieve the produts output to populate the above layout. For example, I used , or content);?\>, but i couldn't accomplish my objectives. Someone who knows this theming could let me figure out this issue please!\[my html/css layout\]\[1\]!

# Answer
views\_embed\_view should help you.
> 1 votes

---
Tags: theming
---


# Question
Title: Stop displaying errors in production server in Drupal 7
How to stop Drupal from showing unnecessary errors?

I'm deploying my Drupal 7 site to production server, and I want to stop displaying general purpose errors.

EDIT:

I found something about *showing* errors in this link:

```
<?php
    error_reporting(-1);
    $conf['error_level'] = 2;
    ini_set('display_errors', TRUE);
    ini_set('display_startup_errors', TRUE);
?>

```

Can someone explain what will be the appropriate value for `$conf['error_level']` to **stop** displaying errors?

# Answer
> 5 votes
Did you try this way : admin/config/development/logging ?

(Where you can choose to display every messages, or just errors, or no message at all)

---
Tags: 7
---


title: Remove all js from template

text:
# Question
Title: Remove all js from template
I'm trying to remove all javascript for anonymous users but I've hit a roadblock.

This is the php I'm using in template.php (phptemplate\_preprocess\_page function):

```
$js = drupal_add_js();
unset($js['core']);
unset($js['module']);
unset($js['setting']);

$vars['scripts'] = $js;

print_r($vars['scripts']); // prints what it should
print_r(drupal_add_js('header', $js));  // prints everything like nothing happened!

```

# Answer
> 0 votes
I've found the problem. It seems that the JQuery Update module is the culprit, more specifically the jquery\_update\_theme\_registry\_alter function:

* Make jQuery Update's page preprocess function run *after* everything else's,
* so that a theme can't call drupal\_get\_js() and mess everything up. \*/

I will discuss this with the Jquery update module makers.

# Answer
> 0 votes
You can do it in function phptemplate\_preprocess\_page exists in template.php

The below is code to remove unwanted js

```
function phptemplate_preprocess_page(&$vars) {

  $scripts = drupal_add_js();
  //PRINT THIS ARRAY AND UNSET THE UNWANTED ARRAY
  // unset($scripts['module']['sites/default/files/js/jquery-min.js']);
  unset($scripts['module']['YOUR_PATH_TO_JS']);
  $vars['scripts'] = drupal_get_js('header', $scripts);

}

```

---
Tags: 6, javascript, theming
---


# Question
Title: drupal_add_js causes blocks to be executed twice
I added this code to template.php (in Zen subtheme):

```
function mytheme_preprocess_page(&$vars) {
  if ($vars['is_front']) {
    drupal_add_js (libraries_get_path('jquery.cycle') . '/jquery.cycle.all.js', 'file');
  }
}

```

Just after adding it, each block (e.g. drupal search block, my custom blocks etc) and also this preprocess function are executed twice. I checked it using a debugger. The output on pages is OK, but executing blocks twice has performance implications.

By the way, the same happens if the JavaScript file is added in `mytheme_preprocess_html()` instead of `mytheme_preprocess_page`.

Is `hook_preprocess_page()` the right place to add JavaScript code? (I guess not.) Is there another way of adding JavaScript to a specific page other than the above? (I know I can add in mytheme.info, but it will add to each page, whereas it's needed only on front page.)

# Answer
> 3 votes
I finally discovered two circumstances when blocks are executed twice:

First is adding a missing javascript file, either in theme.info file or in theme\_preprocess\_page() function using drupal\_add\_js.

Second is by adding a broken url(..) image reference in a css file which is actually used on the page.

Here are the steps to recreate the problem with css, for javascript it's analogously:

* install Drupal (it has Bartik theme as default) and log in, to see the search box
* in a debugger, set a breakpoint inside function search\_block\_view()
* refresh the page and check that the breakpoint is reached once
* go to /themes/bartik/css/styles.css line 1467 and change the line containing:

`background: url(../images/search-button.png)`

into something that does not exist:

`background: url(../images/search-button1.png)`

* refresh the page with shift and check that the breakpoint is reached twice

Maybe such behavior is obvious for someone more advanced and has rational explanation, but for me it is not obvious and took me a while to discover. Anyway the conclusion is just to make sure that all loaded css and javascript resources are available and nothing is missing, otherwise blocks will be silently executed twice and depending what they contain, the page may load longer.

# Answer
> 1 votes
As far as I know drupal\_add\_js should be used in a module. What you can do is to implement hook\_init and check $\_GET\['q'\] for the path of your frontpage.

```
function hook_init() {
  if ($_GET['q']=='path/to/your/frontpage') {
    drupal_add_js( ... );
  }
}

```

---
Tags: 7, theming, javascript
---


title: how to use panels on custome front page

text:
# Question
Title: how to use panels on custome front page
I have created a custom page in Drupal 6 and named it page-node-1.tpl.php. I want to create a panel drag and drop on this page. But when I create a panel it will assign a different name to the panel page. How can I create a panel page for my page-node-1.tpl.php?

I'm new to Drupal, thanks in advance.

# Answer
The correct way to set a page using Panels (I'm assuming Panels 3) in Drupal would be to go to the Panels interface and click "Add custom page". You can give that page any path you want such as /home - the path doesn't actually matter. Then, from the admin options: Administer -\> Site Configuration -\> Site information you can change your default front page. Input the path that you used when creating your new panel.

This will give you a new custom panels page that will show up as the default front page at www.yoursite.com

This video will walk you through the process step by step.
> 3 votes

---
Tags: theming, panels
---


# Question
Title: Query to get termID, term name and number of posts that has that term
I can figure out how to construct a db query that fetches term id and term name. But how do I associate a count of nid's that has this term? I'm looking to do this programatically through the DB api.

Any help would be greatly appreciated, as I'm running low on time.

# Answer
You can write a separate query to select nodes with term id = x, then execute the rowCount method on the resultset like:

```
$results = $query->execute();
$num = $results->rowCount();

```

(Source)

But more direct approach is using addExpression, join and groupBy:

```
$query = db_select('taxonomy_term_data', 'ttd');
$query->join('taxonomy_index', 'ti', 'ttd.tid = ti.tid');
$query->fields('ttd', array('tid', 'name'));
$query->groupBy('ti.tid');
$query->addExpression('COUNT(ti.nid)', 'nid_count');

$results = $query->execute();

```

You can also use db\_query straight away:

```
$results = db_query('SELECT ttd.`tid`, ttd.`name`, COUNT(ti.`nid`) AS `nid_count` FROM `taxonomy_term_data` ttd JOIN `taxonomy_index` ti ON ttd.`tid` = ti.`tid` GROUP BY ti.`tid`');

```
> 1 votes

---
Tags: taxonomy-terms, database
---


# Question
Title: Where are logs created by drush_log() stored?
I have installed Devel module to use xhprof. In devel settings, I have enabled xhprof, but when I load a page, can't see a link to xhprof. I read the source and found this:

`drush_log('xhprof link: ' . devel_xhprof_link($devel_run_id, 'url'), 'notice');`

Where is this log stored and how can I see it?

# Answer
> 18 votes
It's not. It's printed.

However, notices are by default not visible unless you increase the verbosity of drush using the -v option.

To display internal messages you'll need to enable debug option -d. This will display even more information.

Alternatively, you can change the message type parameter from 'notice' to 'ok' to print out to the console.

```
drush_log('xhprof link: ' . devel_xhprof_link($devel_run_id, 'url'), 'ok');

```

---
Tags: drush, debugging
---


# Question
Title: Using variable_get() in multiple places, without duplicating $default
When using `variable_get()` in multiple places, how should one avoid duplicating the `$default` values?

`define()`? Or is there some built-in Drupal-specific mechanism I'm missing?

# Answer
There is no built in mechanism. In fact, there is a long standing issue to add one http://drupal.org/node/145164.

Defining constants, as you suggested, is the only method I've seen to make it a bit cleaner.
> 2 votes

# Answer
A pattern that I often use in custom code, uses OOP. I use this for variable\_get, t() and "magic" numbers such as the amount of items in a pager- or limit-query:

```
class MyModuleHelper() {
  public static $foo = "bar";

  public function v($name) {
    return variable_get("mymodule.{$name}", $$name);
  }

  public function t($identifier, $params) {
    $translated = "";
    $callback = "t_{$identifier}";
    if (function_exist($callback, $this)) {
      $untranslated = $callback();
      return t("mymodule." . $untranslated, $params);
    }
    return $translated;
  }

  private function t_thank_you() {
    return "Thank you, %username";
  }
}

```

Then, in the module:

```
  $helper = new MyModuleNameHelper();

  print "Variable foo:" . $helper->v("foo")
  print "Translate thank_you:" . $helper->t("thank_you")

```

This has several advantages:

* Your variables and translations are properly prefixed with `mymodule.`, whithout duplicating that prefix all over the place (DRY!).
* No need to duplicate your strings and variable values all over the place (DRY+)
* No need to abuse constants for variable defaults. Constants are constant and should not be abused as value in a variable.
* Translatable strings are callable with a symbol, `t("thank_you")` instead of `t("Thank you, %username")`.

And one downside:

* It is OOP and therefore "un-Drupal-ish".
> 0 votes

---
Tags: 6, configuration
---


# Question
Title: Using forms and templates and _submit callback
I'm trying to wrap my head around the process of creating a form and handling the submitted data using `x_submit()`.

I start by having a form callback:

```
function world_form(&$form_state) {

  // if ($form_state['post']) { drupal_set_message("Solved!"); }

  $forms['fieldset_options'] =
    array('#type' => 'fieldset',
          '#title' => t('Options'),
          '#collapsible' => FALSE,
          '#collapsed' => FALSE);

  $forms['fieldset_options']['tags'] =
    array('#type' => 'item', '#title' => 'Simple stuff');

  $forms['fieldset_options']['checkbox1'] =
    array('#type' => 'checkbox', '#title' => t('Solve world problems'));

  $forms['fieldset_options']['submit'] =
    array('#type' => 'button', '#button_type' => 'submit', '#value' => 'Go!');

  // $forms['submit'] = array('#type' => 'submit', '#value' => 'Go!');

  return $forms;
}

```

So I specify a theme callback, which takes me to a file `world.tpl.php` in which I do:

```
print drupal_get_form('world_form');

```

which invokes my form callback. So far so good. Now the problem I have is that I want to handle when this form is submitted (more specifically, I want the value of the checkbox when it is checked). I read a lot of documentation and most mention the `world_form_submit` function. So I create one like this:

```
function world_form_submit($form, &$form_state) {
  drupal_set_message("Posted!");
}

```

But after I've done that the function isn't called. However if I instead use the line which is commented out in my form function and comment out the `'#type' => 'button'` field it DOES get called and I can now access the checkbox state, however the problem I have now is that the form is not updated with the state of the checkbox (I.e. if I check the box and submit I get to the same page but the box is no longer checked).

So my questions are:

1. Why isn't the `_submit` callback called when I use a "regular" submit button? Do I have to use the `$forms['submit']` way?
2. If I do get the `_submit` callback called, can I still update my form to reflect what it was before I submitted, and
3. How can I get the checkbox state in my `world.tpl.php` file? Say I want to print something if it is checked.

Thank you for your time.

# Answer
Many questions here:

* Your form function function should return the form array and doesn't need an argument unless you need it for something specific.
* You should at least have an element of type 'submit' (not button) in your form.
* Chances are good your submit function will get called if you implement it this way.
* If the form fails validation, FAPI will restore it to the values submitted, keeping what was typed by the user.
* You shoudn't try to embed business logic in your template, but rather in your module and/or a preprocess function.

---
> 1 votes

---
Tags: 6, forms
---


# Question
Title: launching parser script once in 24 hours
I have a file parser.php

```
$url = 'http://site.kz';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt ($ch , CURLOPT_USERAGENT , "Mozilla/5.0 ");
curl_setopt ($ch , CURLOPT_RETURNTRANSFER , 1 );
$link = curl_exec($ch);
curl_close($ch);

```

so all contents of the site -site.kz is in $content variable. If i call this script http://site.kz/sites/all/themes/mytheme/parser.php -\> it starts to grab this page, right?

How can i make available that variable $link in a page.tpl.php? If i make `include ('parser.php')` then everytime i F5 my page → parser is going to work (creates load to the server).

# Answer
> 0 votes
If you don't want your script to execute on each page load, you have to set up a cron job, either via hook\_cron() or a separate job.

To make a variable available in a template file, you have to use a preprocess function of some sort.

With these two elements, you should be able to make your script work and be integrated with Drupal.

---
Tags: 6
---


# Question
Title: How can I override apache solr's default search result sorting?
According to this, search results are ordered by relevance score. How can I override this? I want our results sorted by created date. I'm not talking about allowing users to sort by different fields, just the default order of results returned by apache solr.

# Answer
This requires a custom modules where you implement a hook provided by apachesolr. There are several options but `hook_apachesolr_modify_query(&$query, &$params, $caller)` works as well as any.

You can modify the `$query`:

```
$query->set_solrsort($field_name, $direction);

```

Or you can modify the `$params`:

```
$params['sort'] = "$field_name $direction";

```
> 6 votes

---
Tags: 6, search
---


# Question
Title: What is the risk of using number in image style preset name
There is a message below the preset name to be written. It not suggest us to write number:

```
The name is used in URLs for generated images. Use only lowercase alphanumeric characters, underscores (_), and hyphens (-).

```

Sometime I need the name with number such as `thumb90`, `profile100x150`, etc.

I can see some developer also write number in the name field.

Even no problem so far, I need to know what actually the risk of using number together in the name.

# Answer
> 2 votes
I have never seen the term "alphanumeric" refer to anything other than a combination of letters and numbers.

Since the style name gets used in the URL, the restriction to "Use only lowercase alphanumeric characters, underscores (\_), and hyphens (-)" likely has to do with avoiding any escaping issues with URLs and for portability across filesystems that may not support the full range of characters in filepaths.

Personally, I have never (nor have my clients) run into any issues with using numbers in image sytles, though as a best practice I lean towards using descriptive names for use, rather than size, in the sytle name. So, I will try to use "thumbnail\_square" instead of "thumbnail\_90x90", in case I end up changing the size at some point.

# Answer
> 0 votes
It says lowercase "alphanumeric" characters, which includes both letters (a-z) and numbers (0-9). So it's fine to have numerals in the names. The examples you give reflect pretty common practice for imagecache settings names.

---
Tags: media, 6
---


# Question
Title: How to sort users in a view by the number of nodes authored of a specific node type?
I was happy to find that in Views 3 I can sort users in a view by the number of nodes they have authored (Using a relationship "User: Content authored" and the Aggregation / 'Group by' - Count function, see here).

How can I do the same, but counting only nodes of a certain node type? (I'm actually using this in a view of profiles (Profile2), but using the relation "Profile: User UID" the solution would probably be the same).

# Answer
Not sure if I understand you correct, but have you tried setting up a normal filter:

Content: Type (= nodetype)
> 1 votes

---
Tags: 7, views
---


# Question
Title: How to clear already rendered "drupal messages" after successful ajax submit?
> **Possible Duplicate:**
> Remove tabledrag statuses on Ajax submit and display status message after Ajax submit

I have a custom form which saves "weights" of nodes to a custom table. The form has an Ajax submit handler. The form is rendered in a table using `theme('table')` and it has draggable handles added using `drupal_add_dragtable`.

Because the form gets submitted via Ajax, the messages such as "Changes made in this table will not be saved until the form is submitted" and any other messages in the "message region" don't get cleared even if the form is submitted and the values are saved.

How do I clear this message area? Or is there a way to hook into the "success" function of the Ajax? Or is it at all possible to run a custom javascript function after the form is submitted via Ajax? Any one of these possibilities will do for me. Please advise.

---

I've partially succeeded in solving this by returning an array of ajax commands from my callback function.

In particular I return the following commands:

```
$commands = array();
$commands[] = ajax_command_html('#page-banners-status', theme('status_messages'));
$commands[] = ajax_command_remove('.tabledrag-changed');
$commands[] = ajax_command_remove('.tabledrag-changed-warning');

```

but I've run into a new problem where now, even though the "Changes made in this table will not be saved until the form is submitted" message is removed after the save, it doesn't come back if the table is further modified after the save. I've tried to grab the form again and pass it back using an ajax command:

```
// my form function receives additional parameters
$form = drupal_get_form('my_custom_form', $path, $tid);
$commands[] = ajax_command_html('.table-container', drupal_render($form));

```

But whenever I call drupal\_get\_form from the callback function, it seems to break the function.

# Answer
You can do it in two ways,

First One,

```
function hook_preprocess_page(&$vars) {
  //if(CHECK FOR THE FORM PAGE)
  $vars['show_messages'] = 0;
  $_SESSION['messages'] = '';
  // END IF
}

```

Second One is

at the end of the form submit callback write the code like below

```
unset($_SESSION['messages'])

```

or

```
$_SESSION['messages'] = '';

```
> 1 votes

---
Tags: 7, ajax, forms
---


title: Comments not displaying

text:
# Question
Title: Comments not displaying
This is very strange.

Comments are only displaying for a content type called "Issue" for roles that have the Comment permission "Administer comments and comment settings". I set the "View comments" permission for all roles. All the other content types display the comments properly to all roles. Somehow this content type is corrupted. Has anyone seen behavior like this? Any suggestions on how to fix it?

# Answer
> 2 votes
The problem was in the node\_comment\_statistics table. When I first created the content type I selected "close comments". When I changed it later to have comments, it never put an entry into node\_comment\_statistics. So we had to go in there manually and put in an entry from the node.

# Answer
> 2 votes
First verify that the Issue type isn't set to hide comments. If comments exist but are hidden, only admins will see them. A path something like this: `/admin/structure/types/manage/issue`, and go to the 'Comment settings' tab at the bottom.

Also, you might go to `/admin/reports/status/rebuild` and rebuild the permissions cache.

---
Tags: comments
---


# Question
Title: How to search for content from the Content Management admin view?
This feels like such a dumb question to ask, but I can't find a way to search for my content on the Content Management view in the Administration area!

Could somebody point me in the right direction, please?

# Answer
In drupal 7 you can use the Aministration Views.

It uses the Views module and VBO to create some views to replace all the pages in administrtion area that does some kind of listing.

After the instalation you need enable the views created by this module.

For me this was the only way to get a "Title filter" for the contents in the drupal administration area.
> 5 votes

# Answer
The core content management is quite limited. There are a few options:

1. There is a submodule in the Admin menu Module that replaces this with Views
2. There is a feature in VBO that does something similar to the above
3. Build your own view with an exposed search filter
4. There is also the CMF module that is an alternative to the Administer \>\> Content management \>\> Content tool with these additional options:

Show nodes, comments or both Filter by author (select from drop-down list) Filter by author (enter username in AJAX search field) Filter by user role (shows nodes authored by any user in the selected role) Filter by user status (active or blocked) Filter by title or body substring Filter by node created date (before/after) Filter by node language Displays a column in the content list with node creation time Sort content list by any column: Title, Type, Author, Status, Time
> 3 votes

---
Tags: 6, nodes
---


title: hook_init() is executed more than once

text:
# Question
Title: hook_init() is executed more than once
When running xdebugger in `hook_init()`, I noticed that the debugger was stopping at same break points more than once. Why is this so? Will it not affect the page load time?

# Answer
> 1 votes
If I print some text within `hook_init()`, it is being printed only one time. This will not reduce the performance. Also `hook_init()` is called only once, from Drupal core.

---
Tags: debugging
---


# Question
Title: Call Drupal PHP function from Javascript?
I'm trying to get the content of an article and display it using AJAX by replacing the content of a div with the new article's content. In order to do this I want to make an asynchronous jQuery call to a PHP page that simply outputs the article's body. However, this PHP function needs access to the Drupal PHP functions in order to operate properly. Where or how can I create a PHP file that will have access to these functions in a Drupal install?

# Answer
> 7 votes
To get data from Drupal's database and/or produced in PHP, you need a page callback (in a custom module) that output the data without the full layout rendering. This is easily doable by printing the content of the page directly in your page callback instead of returning it.

If you want to retrieve nodes in AJAX, you can also use the Services module which provides JavaScript callable endpoints (REST, JSON over HTTP) for nodes, users, taxonomy terms, etc.

If you still want to work outside Drupal, in a standalone script, you should include Drupal's `include/bootstrap.inc` and call `drupal_bootstrap()` function to initialize Drupal environment (connect to database, load modules, session, etc.). You can select the phase to bootstrap depending on what you need from Drupal.

```
chdir('path/to/drupal/root');
require_once('includes/bootstrap.inc');
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
// Drupal is fully loaded here, you can access everything.

```

# Answer
> 3 votes
If you want to get another drupal article's body text, you need not write custom php code in file.

You could do that using views may be in the following way:

1. Create a drupal views to show get articles body text as output (which can take nodeid as parameter)
2. Use View Data source module http://drupal.org/project/views\_datasource to output the view result in JSON format.

Now you can call this view(using view page URL) with required parameter to get article body in JSON format. That can be used by your javascript to place the content inside div.

---
Tags: ajax, javascript
---


title: Canonical URL Meta Tag for a View Page

text:
# Question
Title: Canonical URL Meta Tag for a View Page
I'm using the Meta Tags Module and it has been a solid way to add meta tags throughout the site - especially the increasingly important Canonical URL meta tag.

I'm having trouble adding the same tag to views connected to a static page.

How can I add a canonical URL to some views pages?

# Answer
I'm assuming you're using Drupal 7.x and the latest alpha version of the Meta Tags module, correct? They are still working out the views integration functionality for this module but there is a sandbox project for this issue called 'meta tag views'. In Drupal 6.x nodewords, this was easier to do based upon path by just adding a custom entry at: /admin/content/nodewords/meta-tags/custom/add.

In the meantime, you can try the metatags\_quick module which lets you assign meta tags to specific paths. You would need to add the 'canonical url' as a possible field but the interface is simple to use.
> 3 votes

---
Tags: views, meta-tags
---


# Question
Title: How do I translate the content of a checkbox I created?
I have a multilingual site, content translation works. Now I added a content type and used the checkboxes/dario buttons field for a new field. How can I translate the content of that field?

Let's say the checkboxes values are *male|Male* and *female|Female*. How can I use the Spanish translation for those values?

I found someone suggesting I had to use PHP fields, but I don't even see a PHP field there, although the module works in other places.

# Answer
Apart the *Content translation* module, the Entity Translation module is also required, to translate each field/entity.

Content Translation (field translation) in Drupal 7: First steps (also linked from the *Entity Translation* project page) is a good step-by-step guide on how to set this up.
> 1 votes

---
Tags: 7, i18n-l10n
---


# Question
Title: Call template file, hook_theme() thru theme( hook, $data )
I am trying to call a template file but without luck.

```
   /**
     * Implements hook_theme().
     */
    function my_module_theme($existing, $type, $theme, $path) {
      return array(
        'my_module_text' => array(
          'template' => 'my_module_text',
          'variables' => array(
               'myvar' => 'helloworld'
           ),
          'path' => drupal_get_path('module', 'my_module'),
        ),
      );
    }

    /**
     * Preprocessor for theme('my_module_text').
     */
    function my_module_preprocess_my_module_text(&$variables) {
      debug('text preprocessor called');
    }

```

I have a template file in the module directory named my\_module\_text.tpl.php.

When I call `theme('my_module_text',array('myvar' => 'helloworld'));` I get nothing. The template file is not used.

Am I missing anything?

# Answer
Your code looks fine to me; make sure you've cleared Drupal's caches since implementing `hook_theme()`, and your preprocess function, as these implementations are cached, and won't show up in the registry until you do.

FYI, the "path" property is not required if the template file resides in your module's folder: Drupal will check there first anyway (this won't be causing the problem though).
> 2 votes

# Answer
The only difference I can see with what done, for example, in taxonomy\_theme() is the name of the template file.

```
function taxonomy_theme() {
  return array(
    'taxonomy_overview_vocabularies' => array(
      'render element' => 'form',
    ),
    'taxonomy_overview_terms' => array(
      'render element' => 'form',
    ),
    'taxonomy_term' => array(
      'render element' => 'elements',
      'template' => 'taxonomy-term',
    ),
  );
}

```

For what I recall the name of the template file reported in `hook_theme()` must match the array index used in the returned array, with the only difference being using a hyphen instead of an underscore (as hyphens are not allowed in PHP function names).

I am not sure that using underscores in the template file names could cause any issue; theme() uses the template name returned from `hook_theme()`, but there could code in Drupal that changes the underscore in the template filename with hyphens.

```
// Render the output using the template file.
$template_file = $info['template'] . $extension;
if (isset($info['path'])) {
  $template_file = $info['path'] . '/' . $template_file;
}
$output = $render_function($template_file, $variables);

```

Even theme\_render\_template(), the function that in Drupal 7 renders a template file, doesn't change the template filename.

```
  extract($variables, EXTR_SKIP); // Extract the variables to a local namespace
  ob_start(); // Start output buffering
  include DRUPAL_ROOT . '/' . $template_file; // Include the template file
  return ob_get_clean(); // End buffering and return its contents

```

If you are altering a theme that is currently enabled, you need to clear the Drupal cache as Drupal caches information about the enabled themes, in the same way it does with the list of hooks implemented by modules.
> 1 votes

---
Tags: theming
---


# Question
Title: Organic Groups (OG): Make public group posts visible to everyone (outside the group)
I’m using the OG module for my site where users can create groups and make them either public or private. But one feature I miss from the group environment when creating a public group is, to make all the posts in that group visible to everyone – not only group members.

I’ve looked in the OG admin settings and found the setting “Visibility of posts:” with the radio button option to “Visibility chosen by author/editor using a checkbox on the posting form. Checkbox defaults to Public.” This function is exactly what I want but when choosing this option and try to create a post inside an open, public group, I don’t get any options to select it to be visible or not. The field just isn’t there.

I’ve browsed Google and Drupal.org for an answer and have discovered that I’m not the only one with this question. But unfortunately I haven’t been able to find a solution, so I will try again to post the issue and maybe there is something I’ve overlooked.

Any help would help.
Thanks

Sincere
\- Mestika

# Answer
> 2 votes
You control the visibility of a post through the Group\_Access field.

Create a content type with Group and Group\_Access fields (or add those fields to a built-in content type). Then when users create posts of this content type, they can make the content part of the group and set its Group Access to either "Public - accessible to all site users" or "Private - accessible only to group members."

Any "Public" content will be visible to anyone on the site, not just group members.

---
Tags: organic-groups
---


# Question
Title: views filter: broken filter - but what's broken about it?
I am trying to build a views filter and after a lot of digging into the views-workflow, I think I might have understood the basics. I used a lot of resources     and of course doc.logrus.com, but now Views tells me that my handler is broken.

If there is anybody outhere that can help me get my filter-handler working, I would be in a huge debt!

Right now I have the following three files:

ds\_regions.module

```
function ds_regions_views_api(){
  return array(
    'api' => 3,
    'path' => drupal_get_path('module','ds_regions')
  );
}

```

ds\_regions.views.inc

```
<?php
function ds_regions_views_handlers() {
  return array(
    'info' => array(
    'path' => drupal_get_path('module','ds_regions'),
  ),
  'handlers' => array(
    'ds_regions_handler_filter_view' => array (
      'parent' => 'views_handler_filter',
      ),
    ),
  );
}

function ds_regions_views_data(){
  $data=array();
  $data['node']['ds_regions_filter']=array(
    'title' => t('ds regions view filter'),
    'help' => t('Filters the nodes by region'),
    'filter' => array(
      'handler' => 'ds_regions_handler_filter_view',
    ),
  );
  $data['field_data_field_verein']['table']['join']['node']=array(
    'left_field' => 'nid',
    'field' => 'field_verein_tid',
  );
  $data['ds_vereine']['table']['join']['node']=array(
    'left_field' => 'field_verein_tid',
    'left_table' => 'field_data_field_verein',
    'field' => 'tid',
  );
  return $data;
}
?>

```

ds\_regions\_handler\_filter\_view.inc

```
<?php
class ds_regions_handler_filter_view extends views_handler_filter{
  function admin_summary(){}
  function option_definition(){
    $options = parent::option_definition();
    $options['misc'] = array('default' => '1');
    return $options;
  }
  function value_form(&$form, &$form_state) {
    $form['custom_filter']  = array(
      '#type' => 'textfield'
    );
  }
  function options_form(){}
  function operator_form(){}
  function query(){
  $table = $this->ensure_my_table();
  $this->query->ensure_table('ds_vereine',$this->relationship);
  $this->query->add_where($this->options['group'],"ds_vereine.plz IN (SELECT ds_plz_distance.plz_first FROM `ds_plz_distance` WHERE ds_plz_distance.distance < 20 AND ds_plz_distance.plz_first=ds_vereine.plz) OR ds_vereine.plz IN (SELECT ds_plz_distance.plz_second FROM `ds_plz_distance` WHERE ds_plz_distance.distance < 20 AND ds_plz_distance.plz_second=ds_vereine.plz) OR ds_vereine.plz IN (SELECT ds_plz_ort.plz FROM `ds_plz_ort` ort WHERE ds_plz_ort.kreis=306)");
  }
}
?>

```

# Answer
You are looking at Drupal 6 documentation.

You don't need `hook_views_handlers()` anymore in D7. Instead, you add the file(s) that contains your views handler(s) to your .info file like this:

```
files[]=ds_regions_handler_filter_view.inc

```
> 1 votes

---
Tags: 7, views
---


# Question
Title: Whats the best method for displaying different page layouts for a node based on taxonomy?
I am building a product site which should use a slightly different page layout for different types of products, depending on what product category they are.

All products are of the same node type. They are categorized based on selected taxonomy terms. The reason I did this instead of creating a different node type for each product category is because some products may exist in multiple categories.

My understanding is that panels relies on the URL structure for determining context. I'm listing all products under ../products/\[title\] so I dont think that will work. The only way to know the product category is to check the value of a CCK field on that product.

It seems there are many ways to skin a cat in Drupal but I'm unable to figure out what method will allow me to do what Im trying to do.

Any advice/help would be appreciated.

# Answer
> 3 votes
In D6, if you are displaying a full node page, you can use the preprocess\_page() hook to select a different page template based upon that CCK field. For example,

```
function mythemeormodule_preprocess_page(&$vars) {

  $node=$vars['node'];

  switch ($node->field_i_am_interested_in[0]['value']) {
    case 'something':
    case 'anotherthing':
      $vars['template_file']='page-bytax-' . $node->field_i_am_interested_in[0]['value'];
      break;
  }

}

```

and then create `page-bytax-something.tpl.php` `page-bytax-anotherthing.tpl.php` etc with whatever page layout you want.

If though, you are really talking about how the node itself is laid out in the `$content` area of the page, you could do the same thing inside `preprocess_node()` and create `node-bytax-FOO.tpl.php` templates instead.

Also, depending on what kind of cck field you are looking at, you might need to change up the `[0]['value']` part.

If D7, subtle changes apply :)

# Answer
> 2 votes
You can access this information in the definition of the panel variant. If your content has a field, you will find it listed in the Selection Rules tab for the variant. Click on the drop-down list and you will find an item `Node Content_Type_Name: your_field_name` Selecting this should restrict the content using this variant to the values you specify. Create another variant to cover another set of values.

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


title: getting autocomplete working

text:
# Question
Title: getting autocomplete working
I honestly did, what this and this tutorial told me, but somehow my autocomplete textfields still fire an ajax error. but to be more specific: the ajax error gives a 200 http response and a status OK, but **no** answer-text.

my setup is:

```
$form['field_new_verein_location_'.$i] = array(
    '#type' => 'textfield',
    '#title' => t('<a id="ds_region_new_verein_'.$field_id.'" style="color:black;text-decoration:none;">Neuer Verein Ort</a>'),
    '#default_value' => '',
    '#size' => 60,
    '#maxlength' => 128,
    '#required' => TRUE,
    '#description' => t('description'),
    '#autocomplete_path' => 'dsregion/autocomplete'
);

function ds_regions_menu(){
    $items['dsregion/autocomplete']=array(
      'title' => 'location auto complete',
      'page callback' => '_dsregion/autocomplete',
      'access arguments' => array('access region autocomplete'),
      'type' => MENU_CALLBACK
    );
    return $items;
}

function _dsregion_autocomplete($string) {
    $matches = array();
    $result = db_select('ds_plz_ort','o')
      ->fields('o',array('ort'))
      ->condition('ort','%'.db_like($string).'%','LIKE')
      ->range(0,10)
      ->execute()
      ->fetchAllKeyed();

    foreach($result as $row){
      $matches[$row->ort]=check_plain($row->ort);
    }
  drupal_json_output($matches);
}

```

# Answer
> 2 votes
You have a slight error in your `page callback` property for the menu item. You've got a string resembling a path in there instead of the name of the callback function.

Just change

```
'page callback' => '_dsregion/autocomplete'

```

to

```
'page callback' => '_dsregion_autocomplete'

```

Then clear Drupal's caches and you should be good to go.

---
Tags: 7, ajax
---


# Question
Title: Node tagged with more than one taxonomy, how to keep expanded the specific taxonomy menu the user has used to reach a node
I have nodes associated to more than one taxonomy vocabulary, so the same node can be listed/reached in different ways, for example:

Brand \> Family line \> model \> NODES

Veicles \> category \> NODES

e.g.

Ferrari \> Top-Luxury \> Testarossa \> NODES \> NODE-A

Cars \> Supercars \> NODES \> NODE-A

By Design every node can have only and only one URL: it's ok for me (and for SEO)

Now I have created different taxonomy menus (based on the above taxonomies) to retrieve nodes in different ways:

**TAXONOMY MENU A:** Ferrari \> Top-Luxury \> Testarossa \> NODE-A

**TAXONOMY MENU B:** Cars \> Supercars \> NODE-A

**The question is:** is there a way to keep expanded the specific taxonomy menu the user has used to reach the node?

So:

if user has reached NODE-A trough MENU A then MENU A is showed and expanded in the page

if user has reached NODE-A trough MENU B then MENU B is showed and expanded in the page

Is there a way to accomplish this?

May be using SESSION variables? (ref: http://drupal.org/node/1443210 )

Thank you very much for any help

# Answer
I've done this in my modules hook\_init() implementation by using sessions, menu\_get\_object and menu\_tree\_set\_path(). Here's some example code showing my general approach:

```
function mymodule_init() {
  // Save the active path for users when on taxonomy term pages.
  if (arg(0) == 'taxonomy' && arg(1) == 'term' && arg(2)) {
    $_SESSION['mymodule_path'] = $_GET['q'];
  }
  // The user is on a node page.
  if (arg(0) == 'node' && arg(1)) {
    $node = menu_get_object();
    // Assuming all the nodes in the taxonomy menu are of the same specific type.
    if ($node->type == 'mynodetype') {
      if (isset($_SESSION['mymodule_path'])) {
        menu_tree_set_path('menu-mymenu', $_SESSION['mymodule_path']);
      }
    }
  }

```
> 2 votes

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


title: Where does drupal store all its files?

text:
# Question
Title: Where does drupal store all its files?
I would like to use FTP to copy my current site to a new server. I obviously know that the bulk of my files will be stored in `/var/www/` and the folders inside. I also exported my databases from phpMyAdmin to a localhost.sql file.

Is there any other place I need to pull files from? Is that it for the database?

# Answer
> 5 votes
You should be able to transfer the site wholesale, without too much fuss. After transferring, you may need to alter some paths (eg `admin/config/media/file-system` in D7) if the `sites` directory has changed paths relative to your Drupal codebase. Odds are you won't need to, though.

For a simple site, the layout will be something like this -

```
/var/www/index.php
         modules/                  } don't install modules here
         themes/                   } nor themes here
         includes/
         [many other Drupal core files]
         sites/
               default/            } all installed code
                       files/      } lives in the
                       modules/    } site directory
                       themes/     } and its children

```

For more complex setups you may need to understand multisite layouts, but for now hopefully this answers your question.

# Answer
> 3 votes
Thankfully, Drupal installations are typically very self-contained. If there were any changes made to your old server's httpd.conf (or comparable server configuration file if you're not running Apache), you may want to migrate those to the new server as well, assuming you aren't on a shared host where all of that is taken care of for you. Though other than copying everything in the root of your Drupal install (the folder containing index.php and all subdirectories) to your new DocumentRoot and importing your database dump, you should be all set.

# Answer
> 1 votes
It depends on your setup really. For example if you use the private file system (properly) and use a folder outside of the web root then you'll need to copy those files too and put them in a folder in the same location on the new site.

Similarly if you use Ubercart (and perhaps Commerce, I'm not sure) and take credit card payments on the site then the encryption keys for those will also be stored outside of the site root, for security purposes; those would also need to be copied.

There are probably other modules that store files outside of the web root but I don't know any off the top of my head. In the majority of cases (except for those above) you should be ok though, just copying the entire web root across will probably work.

---
Tags: database, files, migrations
---


# Question
Title: What's the preferred method of creating different page templates
Basically, I want to give my articles and blog entries a different class on the body so I can style them independently.

I am given to understand that the best way to do this is with creating custom tpl files

I'm working in a custom built theme that is pretty much running just on a page.tpl.php and a stylesheet.

How would I do this easily in Drupal 7? I tried this method for drupal 6 but it didn't seem to work.

# Answer
> 2 votes
This should by there by default.

For example, the body classes on my test site look like this for a simplenews node:

```
<body class="html not-front logged-in one-sidebar sidebar-first page-node page-node- page-node-90 node-type-simplenews toolbar toolbar-drawer i18n-en" >

```

As you can see, there is node-type-simplenews, among many other things.

Those classes are defined in template\_preprocess\_html() and are using in html.tpl.php (not page.tpl.php, unless you've overriden that. If so, you need to duplicate the logic in that function for your page.tpl.php.

---
Tags: 7, theming
---


# Question
Title: Drupal db_or() only returning one result
Can someone please tell me why this code always returns only the last value of the query? I have tried many ways to dynamically build the condition statement for the querying of the database. I have looked at a couple examples and from everything i have seen, this is the way to do it. Any help would be greatly appreciated. Thanks!

```
function get_drupal_school_info($schoolIds) {
$or = db_or();
foreach ($schoolIds as $index => $data){
$or->condition(db_and()
    ->condition('f.field_external_id_value', $data['entity_id'],'=')
    ->condition('f.bundle', 'school')
    );
}

$query = db_select('field_data_field_external_id', 'f');
$query->leftJoin('field_data_body', 'b', 'f.entity_id = b.entity_id');
$query->leftJoin('field_data_field_partner_code', 'pc', 'b.entity_id = pc.entity_id');
$query
    ->fields('f', array('entity_id'))
    ->fields('b',array('body_value'))
    ->fields('pc',array('field_partner_code_value'))
    ->condition($or);

return $query->execute()->fetch();
}

```

# Answer
> 3 votes
It's, because you are calling fetch(). That method fetches a *single* result.

If you want all, you can simply loop over the return value of $query-\>execute() or use fetchAll() or one of the many related helper functions.

---
Tags: 7
---


# Question
Title: Use multiple choices of CSS class in Insert
If using Insert module, in the field editing, we can put Additional CSS classes to the image being inserted.

I need the images float right. So I type `floatrimg` in the field editing, and `.floatrimg {float:right;margin:0 0 10px 10px;}` in CSS. It works fine.

But if I need to have 2 images in one post: one image float right, another one float left, I need 2 image fields.

I hope I can have one image field, where multiple choices of CSS class can be selected when submitting. So that with one image field, I can insert image float right and float left.

# Answer
> 0 votes
I would suggest you to create two presets. Each preset can then be styled and positioned with CSS and the .imagepresetname class. You just have to activate the presets you like on the field in the "Insert" settings.

---
Tags: 7, entities
---


# Question
Title: How do I add block configuration information for themes using features?
Is it possible to use features to manage block configuration information (for example, the positioning of a block \[header, footer, etc.\]) using features?

# Answer
> 2 votes
Yes, but not directly you need to use the Context module to do it.

---
Tags: 7, features
---


# Question
Title: List members visable in any organic group
I am working on a Drupal 7 & OG & Views site, and I am trying to write a view that shows what users another user can 'see' through any group he's a member of.

ie: User A - Member of Group A, Group AB, Group AC User B - Member of Group B, Group AB User C - Member of Group C, Group AC

Output of View for .. User A - User A, B, C User B - User A, B User C - User A, C

Thanks..

# Answer
> 2 votes
Go to OG Members \> EDIT \> CONTEXTUAL FILTERS \> PROVIDE DEFAULT VALUES \> CURRENT OG GROUP FROM CONTEXT ....i assumed u have the OG MEMBERS which is a default view created after installation of the latest module.

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


title: How does `drush features-update` work?

text:
# Question
Title: How does `drush features-update` work?
I have made changes to a Feature on a Drupal 7 site. I want the same feature to be updated in another website. How to do it using the `drush features-update` command? When I run it, it asks to overwrite the previous Feature, but nothing new comes in the Feature.

# Answer
> 16 votes
Drush feature-update updates the feature **code** with overwritten settings. So the function is used to export changes to code.

If you want to take those changes to another site, you will have to copy the updated feature to the other site unless they share the same code (and then revert the feature and clear cache (not always needed)).

In code it could look like this

```
$ drush fu feature_module
$ cp -r feature_module ./DIR
$ cd DIR
$ drush fr feature_module

```

---
Tags: 7, drush, features
---


title: Dual operating system setup

text:
# Question
Title: Dual operating system setup
I need advice regarding my plans for a Linux/Windows web development project.

My employers have 2 windows servers - one hosts their non-drupal CMS and the other hosts the website database. My job is to transition their website to Drupal - that's the easy part. So, I will be shutting down the server hosting the current website.

The hard part is using two separate servers for the site and the database - something I've never done before.

I plan on using a Linux server for the Drupal development but I need to know how to do the following:

* use a remote database
* use SQL Server on a Windows IIS machine

# Answer
**Remote database**

To use a remote database, you just have to supply the IP/URL of your remote server instead of 'localhost' during install or in sites/default/settings.php file.

**SQL Server**

There's a module for SQL Server : Drupal 7 driver for SQL Server and SQL Azure.

And installation instructions are available on the module page.
> 3 votes

---
Tags: 7, iis, database
---


# Question
Title: How to add a RSS Feed to a solr search view in drupal 7?
I'm trying to add a rss feed to my website. It has content indexed by a a solr search and somehow when I try to add a RSS feed it says:

> Style RSS Feed requires a row style but the row plugin is invalid.

Also in the edit view the following message is shown:

> Show: Missing style plugin

using drupal 7, solr, and views

Using a 'normal' view RSS 'page' can be created

How do I add the missing style plugin and where do I find this plugin?

# Answer
> 0 votes
as a temporary solution I created a new view with the same content added a rss feed to that. now I do have a rss feed but not on the page I want it to be.

I'll accept this answer until a better one shows up.

---
Tags: 7, views, search, feeds
---


# Question
Title: Confused about choosing between line items and product attributes
I am making a website that will have image canvas size as the products. As you know the Canvas Sizes will change and also their price will also change. Let me tell you the actual steps.

1. The customer selects the Canvas Layout. These are the Products for me.
2. The customer selects the sizes for the selected canvas layouts.
3. The customer chooses the Wrap type for the Canvas.
4. The customer chooses the color of the wrap.
5. The customer chooses the Frame type of the Canvas.
6. The customer chooses the color of the Frame.
7. The customer adds the selected item to cart and go to checkout.

Please note that, once the customer starts customizing the product, the price of the product changes with each customization.

So my confusion is that, what will be the best suited practice to achieve this one. I am using Drupal Commerce. Should I go for the Product attributes or line items? Is there any way I can achieve this one by custom Module to add line items dynamically? So then I can create the prices upon each customization. I am attaching one wireframe about my idea.

# Answer
> 2 votes
If you made it all attributes (fields) on the products, created a product with each possible variation and referenced them all in a single node, it would work with the commerce add to cart form out of the box.

Commerce would create a select list for each attribute, which might not be exactly what you want, but that should be possible to handle with some form alter.

# Answer
> 0 votes
I think in this case you're inevitably going to have to do a fair amount of custom coding. I think the thing that needs thinking about is how you can best use Drupal Commerce to reduce the amount of coding you have to do.

This is by no means a definite how-to, it is however, how I'd would go about it in the first instance:

Create product types for each option that alters the price. If I understand correctly you would have four: 'Layout', 'Size', 'Wrap Type' and 'Frame Type'. The wrap type and frame type would also have a colour attribute. You can then create a product for each layout, size, wrap type and frame type.

That's all fairly easy an can be done through the UI. Obviously the default add to cart form won't be used, so the complexity comes in how you make up an order. By the looks of it there will be a 'wizard' for the user to make up their order. It would be out of the scope of this question to go into detail but it would essentially create an order with a line item referencing a product of each product type.

---
Tags: commerce
---


# Question
Title: How to add classes to every X number of node in a array
How do I write a preprocess\_node function to add a class to every second/third node it generated?

Scenario: add .last to every 2nd node, so that i can apply margin-right: 0; for the last column in the row.

# Answer
For node listings for which the node.tpl.php (or a different node template) is being used you have variables like `$zebra` and `$id` at your disposal that you can use for this kind of tasks. You can see all the available variables with descriptions in the node modules node.tpl.php file or here.

For example if you want to add the necessary class to this line:

```
<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

```

you could use code snippets like these:

* `<?php $classes .= ' '.$zebra; ?>` \- add 'odd' to every first and 'even' to every second node in the list
* `<?php if (!($id % 2)) $classes .= ' last'; ?>` \- add 'last' class to every second node.
* `<?php if (!($id % 3)) $classes .= ' last'; ?>` \- add 'last' class to every third node.
> 5 votes

# Answer
Sounds like you want to use the `:nth-child(N)` CSS selector:

```
.table-class td:nth-child(even) {
  margin-right: 0;
}

```

Or even better:

```
.table-class td:nth-child(2) {
  margin-right: 0;
}

```

The selector does this:

> This pseudo-class matches elements on the basis of their positions within a parent element’s list of child elements. The pseudo-class accepts an argument, N, which can be a keyword, a number, or a number expression of the form an+b.

The selector works on a one-based index, not zero, so "even" will work if you've only got 2 columns; you'd be better using the second example though, which specifically targets the second `<td>` of a parent `<tr>` within the given table.
> 3 votes

---
Tags: 7, nodes
---


# Question
Title: Review the css and theme also like we do for code using code review module
To check my code in custom module we use Code Review module. Is there a similar module for themes and CSS?

# Answer
> 1 votes
If by the 'Code Review module' you mean the Coder module, it already supports reviewing the code in themes.

> Beginning with the 5.x-2.x version, this module adds a new UI, core support, theme support, and a cache for faster display of unchanged files. It also supports rule #severity levels of "minor", "normal", and "critical."

---
Tags: 7
---


# Question
Title: When does hook_node_access() get invoked for $op == "create"?
When does `hook_node_access` get invoked for `$op == "create"` ? In other words, at what portion of the node creation process is this permission checked? I am not seeing anything in the API does about this.

I have a situation where I need to restrict a subset of users to only be allowed to create/edit content with a particular taxonomy term based on their user profile. I have the `$op == "update"` and node form logic all worked out, and am not sure what I need to do about `$op == "update"`

Thanks.

# Answer
It gets called from `_node_add_access()`, which is the access callback for the `node/add` path (see `node_menu()`):

```
foreach ($types as $type) {
  if (node_hook($type->type, 'form') && node_access('create', $type->type)) {
    return TRUE;
  }
}

```

`node_access()` has this line in it:

```
$access = module_invoke_all('node_access', $node, $op, $account);

```

Which is when `hook_node_access()` is actually invoked.

To answer your question, it's called before the node add form is ever displayed to a user; obviously if it returns FALSE then access is denied to the form.
> 2 votes

---
Tags: 7, users
---


# Question
Title: Menu Block: Expand all children of this tree - ignored?
Is anybody using Taxonomy Menu + Menu Block? I have a problem setting `Expand all children of this tree`, in that it seems to be completely ignored. My sidebar taxonomy menu lists all children expanded, regardless of the setting value.

Since I don't see the problem in issue queue for the project, I assume this could be only a local problem. It might be that I am overlooking some other module that could be causing that.

Open for your insights, please.

# Answer
I had the same problem... Bug was dependant of my theme which have a theme\_menu\_link preprocess function. If I delete this function and clear cache, menu block works as designed. To be quickly sure, enabled bartik and look the behavior of your menu block.

@see http://drupal.org/node/1425342#comment-5679426
> 0 votes

---
Tags: taxonomy-terms, blocks
---


# Question
Title: Make website visible only to registered users - create invitation system to allow registration
So, my problem is two-fold:

1. I want to have a beta version of my website that I'll make available only to some friends, but I also want to give those friends the option of inviting other friends through some kind of invitation system (e.g. like Gmail did it back in 2004 when it first started).
2. I need to deny access to all content of my website if someone does not have an account.

So, ideally, I want to have a front page with a simple logo and a login form along with some text that allows the guest to enter an email address and be notified about the site going live (or get in some kind of queue). Of course, I also want to keep track of these requests/subscriptions.

So, is there a solution for this kind of functionality in Drupal? I guess I could write custom code and/or use extensive theming to achieve all these goals but I was wondering if there is a ready-made combination of modules that I can use and I'm obviously missing.

# Answer
1. See, the Request Invitation module will likely do your job
2. For this one, first create a new user role @ `admin/people/permissions/roles` (something like "Premium Users" or "Special Group" or "Only Friends" or something that makes sense). Then use the Content Access module to only allow people from the above mentioned user role to see particular contents.

Then copy the contents of page.tpl.php into a new file named page--front.tpl.php and start editing. This will theme for the front page only, where you can now add a form for the requests and so on.
> 2 votes

---
Tags: 7
---


title: Override a node page using page manager

text:
# Question
Title: Override a node page using page manager
I know it is possible to override node pages using page manager, then use panels to make new layout by selecting a variant type, and creating a new variant.

Is it possible not to use the Panels mdoule? I would like to use the Context module, and the default theme regions.

# Answer
Yes it is possible to use only context module to override layout.

1. When you first add context @ `admin/structure/context/add`, you need to select `condition` as "path" and reaction can be whatever you want. For ex. choose reaction as "Regions" and then go ahead disable region for the sleected "path" (the one you chose above in condition).

Just remember context module will use your existing theme layout and regions (.tpl.php files) unlike in panels where it allows you create your own regions and layout.
> 1 votes

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


# Question
Title: Should I be concerned about enabling too many modules at the same time?
I am using features to manage deployment. I have a controller feature which lists 8 other features I have created as dependencies. These features in turn together list over 100 modules as dependencies. Is it ok to simply turn on the controller module and allow it to automatically enable all the other modules, or does Drupal have trouble doing this?

So far when I enable them all at once it seems fine, but I'm just asking to make sure I don't have problems down the line.

# Answer
> 0 votes
Well I guess it depends on max\_execution\_time in your php.ini settings. And maybe similar setting in your my.cnf file on your server(mysql configuration).

---
Tags: 7
---


title: Why do I get these errors?

text:
# Question
Title: Why do I get these errors?
I am getting a variety of errors when I try to use Drush and nothing seems to be working. I am able to run `drush` and see the help commands indicating that I have it installed; otherwise, I can't get anything to work. I get the following error when trying to update a module as an example:

> Command pm-update needs a higher bootstrap level to run - you will need invoke drush from a more functional Drupal environment to run this command.
> Command pm-update needs the following modules installed/enabled to run: update.
> The drush command 'pm-update insert' could not be executed.
> A Drupal installation directory could not be found

When I check the `drush status` output, I get the following, but it doesn't appear to have any of the other relevant site info that is shown in other examples (e.g. theme name, site name, etc.).

```
 PHP configuration     :  /etc/php.ini
 Drush version         :  4.5
 Drush configuration   :
 Drush alias files     :

```

Drush is currently installed in my home directory on a BlueHost shared account and my primary site is in the public\_html directory; I have an additional site with a separate Drupal version and separate database in a subdirectory.

# Answer
> 4 votes
You need to call drush when you are within your Drupal folder. Otherwise drush does not know where your database is and so on.

```
cd /public_html/site2

```

Alternatively, you can set up a .drush/aliases.drushrc.php (Google should be able to tell you more about it) but that's probably not worth the effort in your case.

---
Tags: drush
---


# Question
Title: Change the position of the block created from the Locale module
I am using Drupal 7, and I have enabled the Locale module. I have configured the block so that it appears on the header, but I want the block to appear near the site's name.

How can I do it? Which files need to be changed?

I am using a Zen sub-theme.

# Answer
> 2 votes
You can put your block into any region you like on the general block config page.

If this is not enough you can change everything about a region in the page.tpl.php file or the corresponding CSS files.

---
Tags: 7, theming
---


# Question
Title: "Parameter expected to be reference, value given" error in menu page callback
I have a custom module that adds a couple action links via menu items:

```
function monographs_menu() {
  $items['node/%node/clone_comment'] = array(
    'access callback' => 'clone_access_cloning',
    'access arguments' => array(1),
    'page callback' => 'monographs_node_check',
    'page arguments' => array(1, 2),
    'title' => 'Create For Comment version',
    'type' => MENU_LOCAL_ACTION,
  );

  $items['node/%node/clone_authorized'] = array(
    'access callback' => 'clone_access_cloning',
    'access arguments' => array(1),
    'page callback' => 'monographs_node_check',
    'page arguments' => array(1, 2),
    'title' => 'Create Final Authorized version',
    'type' => MENU_LOCAL_ACTION,
  );

  return $items;
}

```

and the function signature for the page callback is

```
function monographs_node_check(&$node, $type)

```

On my local machine and my dev server, this all works just peachy. However, on the client's server, with a clone of my db and the repo, whenever this link is clicked on, they get a WSOD and this error in watchdog:

> Warning: Parameter 1 to monographs\_node\_check() expected to be a reference, value given in menu\_execute\_active\_handler() (line 517 of ...\public\_html\includes\menu.inc).

Since it's on a remote server that I don't have access to, I can't debug it, but the fact that it works without error on my own local machine and dev server makes it even weirder.

What could be different in the other environment that would cause this error?

Thanks.

# Answer
I got the answer from the support list, and all I needed to do was remove the reference for the node object in my callback function signature:

```
function monographs_node_check($node, $type)

```

$node is passed as an object anyway, so I don't need to mark it as being by reference in the signature.
> 2 votes

# Answer
The problem occurs because Drupal uses `call_user_func_array()` in order to invoke the menu callback function and pass the parameters to it.

If your function signature is:

```
function monographs_node_check(&$node, $type)

```

Then a call to `call_user_func_array()` must look like this:

```
call_user_func_array('monographs_node_check', array(&$node, $type));

```

The important thing to note is that the pass-by-reference is explicitly set on the caller side by using `&$node`, as well as in the called function's declaration.

This has apparently always been true since PHP 4.

Since Drupal does not pass any of these parameters to `call_user_func_array()` be reference in this situation, you get an error.

The most likely reason you're getting the error on one server and not the other is that you have different versions of PHP on each; prior to PHP 5.3.0 this was handled silently instead of raising an error. Now the upshot of the error is that the function is never actually invoked, so your page will never display.

There's a good discussion on the matter in this PHP bug report.
> 1 votes

---
Tags: hooks, routes
---


title: 403 Forbidden Error in Ajax call

text:
# Question
Title: 403 Forbidden Error in Ajax call
Actually this is first time to implement Ajax in drupal. I would like to implement a user name validation using Ajax in user register section. When a user enter his name and filling another field, then validation is running and if the user name already existing in the system, then a error message shows, the user name is already taken. I used to call the Validation function on **"blur"** event of **Jquery**. The Jquery cod is below

```
$("#edit-name").blur(function()
{
$.post(Drupal.settings.basePath + "username_checking",{user_name:$(this).val()} ,function(data)
    {
if(data=='no') //if username not avaiable
      {
        $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
        {
          //add message and change the class of the box and start fading
           $(this).removeClass();
          $(this).addClass('messageboxerror');
          $(this).html('<img align="absmiddle" src="images/Error.png" /> Username Not Available...').show().fadeTo(1900,1);
          disable();
        });
      }
 }
    });
 }
});

```

and I implemented the function in a hook menu as below,

```
    $items['username_checking'] = array(
'title' => 'username_availability',
'page callback' => 'username_availability',
'access arguments' => array('access caubo_registration content'),
'type' => MENU_CALLBACK
);

```

and function is here

```
function username_availability() {
$user_name = $_POST['user_name'];
$select = "SELECT name FROM name WHERE user_name='%s' LIMIT '%d'";
$result = db_query($select,$user_name,1);
$node = db_fetch_object($result);
if($node->name = $user_name){
  return "yes";
}
else{
  return "no";
}
}

```

It shows the error in Firebud

### POST http://localhost/WC/drupal\_website/username\_checking<br>403 Forbidden

I want to confirm is my method is right or not ? If right please solve the problem, or give the exact way to do.

# Answer
> 1 votes
if this is a registration function for anonymous users do they have the respective `access caubo_registration content` permission set in User Permissions?

# Answer
> 0 votes
you might want to take a look how username\_check implemented the ajax call or even use that module.

---
Tags: 6, forms, ajax, javascript
---


# Question
Title: Flat Shipping price per product using Drupal Commerce
I've been beating my head against a wall trying to configure shipping in Drupal Commerce for a week now and so here I am! I have a Select or Other field in the product entity with a couple of choices:

* Free Shipping
* Call for Details
* Other (and the admin enters a flat price)

Again, this is entered on a per product basis, on the Commerce Product entity (not the node). My question is how do I update the shipping price based on this value? It should work as follows:

* Item 1 (shipping: $1.00)
* Item 2 (shipping: $4.00)
* Item 3 (shipping: Free)
* Item 4 (shipping: Call for Details)
* Item 5 (shipping: $1.00)
* **Total Shipping: $6.00**

Perhaps I'm doing this wrong. Any direction would be awesome. Thanks!

---

**This is the final working code:**

```
class CustomShipping extends CommerceShippingQuote {
  public function calculate_quote($currency_code, $form_values = array(), $order = NULL, $pane_form = NULL, $pane_values = NULL) {
    $order = $order ? $order : $this->order;
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    $price = 0;
    // Loop through the products, and add costs.
    foreach ($order_wrapper->commerce_line_items as $line_item_wrapper) {
      if ($line_item_wrapper->commerce_product->field_shipping_price_other->value() > 1) {
          $price += ($line_item_wrapper->commerce_product->field_shipping_price_other->value()*100)*$line_item_wrapper->quantity->value();
      }
    }
    return array(array(
      'amount' => $price,
      'currency_code' => $currency_code,
      'label' => t('Custom Shipping label'),
      'quantity' => 1,
    ));
  }
}

```

# Answer
> 6 votes
If you are using commerce shipping 1.x, you should do something like this:

**Disclaimer, this is written by memory.**

This is based on two fields on the product,

`field_shipping_type` containing the shipping type
`field_flat_rate` containing the actual rate for the product.

1. Create a custom module and add a folder for the shipping plugin, fx `plugins/quotes/custom_shipping`
2. Create the custom\_shipping.inc with the plugin definition.

```
<?php

$plugin = array(
  'title' => t('Custom shipping'),
  'description' => t('Descriptive text.'),
  'handler' => array(
    'class' => 'CustomShipping',
    'parent' => 'quote_base'
  ),
  'price_component' => array(
   'title' => t('Shipping'),
   'display_title' => t('Shipping'),
   'weight' => -40,
  ),
);

```
3. Create the actual shipping logic in the CustomShipping.class.php file in the same dir. All you need is something like this:

```
class CustomShipping extends CommerceShippingQuote {
  public function calculate_quote($currency_code, $form_values = array(), $order = NULL, $pane_form = NULL, $pane_values = NULL) {
    $order = $order ? $order : $this->order;
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    $price = 0;
    // Loop through the products, and add costs.
    foreach ($order_wrapper->commerce_line_items as $line_item_wrapper) {
      switch ($line_item_wrapper->commerce_product->field_shipping_type->value()) {
        case 'free':
          break;
        case 'flat_rate':
          $price += $line_item_wrapper->commerce_product->field_flat_rate->amount->value();
          break;
        case 'call_for_details':
          // Call for details
          break;
      }
    }
    return array(array(
      'amount' => $price,
      'currency_code' => $currency_code,
      'label' => t('Custom shipping method line item label'),
      'quantity' => 1,
    ));
  }
}

```

---
Tags: 7, commerce
---


# Question
Title: List child terms according to parent term page
I created a view listing all parent terms and child terms in my site. Following those suggestions: Tiered HTML lists using Views and Taxonomy?

Now, I need to make the list of child terms change automatically according to the parent term page. For example: In the parent term page: Fruits, This view will show a only a list of those terms:

* Bananas Apple ….

In the parent term page: Colors, This view will show only a list of Colors child terms:

* Red Green Yellow

Any Idea how to do this?

# Answer
> 6 votes
In Drupal 7, I accomplished this by creating a view (for a block) that uses the contextual filter, "Taxonomy term: Parent term" - Under "When the Filter is Not Available" choose "Provide default value", then select "Taxonomy term ID from URL", and check "Load default filter from term page". I then displayed the block on the taxonomy pages where I want the child term lists to appear.

I'm just starting to work with Drupal and I suspect that there's a more robust solution - this works with pathauto but has trouble with terms that use a URL alias - but the instructions I've found for other approaches either don't work or require considerable coding. If you devise a better way, or somebody else has ideas, I'm all ears.

# Answer
> 0 votes
I found a solution to accomplish this, without using views.

1. I have used Taxonomy menu to display a list of all my terms.
2. Then, I used a nice module called: Menu block , to achieve exactly what I want. It can display a list of parent terms, and then display the second level of terms or deeper when you visit one of the parent terms page.

Hope this can help someone.

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


title: HTML5 custom data attributes in Drupal

text:
# Question
Title: HTML5 custom data attributes in Drupal
I want to use the "data" attribute in some of my tags, and I have been searching for a way to include it.

For Example: I am adding JavaScript code to my form. I use `hook_form_alter()` and the `#attached` property.

```
$path = drupal_get_path('module', 'mymodule');
$form['#attached']['js'][] = array('data' => $path . '/js/custom_values.js','type' => 'file');

```

How do I add a "data" attribute to the `<script>` tag generated? I want to use it for arguments to the JavaScript code.

# Answer
> 8 votes
If you mean how to add the `data-` attribute to the `<form>` tag it would be as easy as this:

```
$form['#attributes']['data-foo'] = 'bar';

```

The same goes for any element within the form:

```
$form['foo']['#attributes']['data-bar'] = 'baz';

```

For more info have a look at the documentation for `#attributes`.

---
Tags: javascript
---


# Question
Title: How to set paths for menu items in hierarchy to make it work with Superfish
I'm confused about what to do with the menu items whose sole function is 'to be parent' i.e. no content attached to them. One way I wanted to solve this is to set the path to `<front>` for those items. But then subitems just won't fly out anymore.

Similarly, if I set the path of a parent item to the node that belongs to a child item, the parent just totally disappears out of the menu, leave alone that there would be a child to pop out of.

# Answer
> 0 votes
Weirdly enough I've just stumbled across the Special menu items module, which is:

> a Drupal module that provides placeholder and separator menu items.
>
> A placeholder is a menu item which is not a link. It is useful with dynamic drop down menus where we want to have a parent menu item which is not linking to a page but just acting as a parent grouping some menu items below it.

I'm pretty sure that's just what you're looking for, and it has a stable release for Drupal 7 :)

---
Tags: 7, navigation
---


# Question
Title: how to create a link to mysite/user and how to theme mysite/user?
I have searched for this for some time and the only thing that pops up is how to create/customize your own login/register page.

I would like to add a link to the default Drupak 7 login/register pages and keep the default Drupal 7 login page (mysite/user) and registration page (myste/user/register). Furthermore, I would also like to add some fields to them.

I am currently using the LoginToboggan module and it has provided some help. Could someone please tell me how I can create a stand alone link that i can theme on the front page that will take a user to login/registration pages?

For example, I would to display something of the following on the front page:

```
login | register

```

So both 'login' and 'register' are stand alone links that appears somewhere on the front page and can be themed. but when clicked on, they will take the user to mysite/user (for login) and mysite/user/register (for register)

Thank you any help would be appreciated.

# Answer
> 2 votes
You could add a block to your site and have it show up only on the front page

1) add a block -\> /admin/structure/block/add 2) add this code in the block

```
<div id ="new-login-block">
<a href="/user/login">Login</a> | <a href="/user/register">Register</a>
</div>

```

Make sure that you select a filter that will leave the HTML intact. If you have a rich text editor, make sure that select php code. - http://drupal.org/documentation/modules/filter

3) Set the region settings to show up on top of your content

4) Under Visibility Settings Look for Pages and select only on listed pages

5) In the box, put `<front>`

6) Save Block

# Answer
> 2 votes
Like Stan Ascher posted the simplest and quickest way would probably be to create a block with the links and set it to appear where you want on the front page. With a wysiwyg editor it should be fairly easy to get the output themed to your liking as well.

If adding a block is not suitable for one reason or another there's also the option to manually add the necessary code in your theme's page--front.tpl.php file or if it doesn't exist then page.tpl.php. The code could look like this:

```
<?php if ($is_front): ?>
<div class="user_links">
  <?php print l(t('login'), 'user', array('attributes' => array('class' => array('login')))); ?>
  <span> | </span>
  <?php print l(t('register'), 'user/register', array('attributes' => array('class' => array('register')))); ?>
</div>
<?php endif; ?>

```

If the code is going into page--front.tpl.php then remove the first and last line. Basic HTML, CSS knowledge would probably be necessary with this approach though.

You can add fields for users on the 'admin/config/people/accounts/fields' page or select Configuration -\> Account settings then the manage fields tab. These can be set to appear on user registration and users can edit them later with their other profile information.

---
Tags: users, navigation
---