# Question
Title: Rotating image background in a div using Background Field
I have successfully added background graphics using the module BackgroundField module with the help of this previous question. We've had a feature creep in that we need to have a rotating image from a preset pool of images. Does anyone know of an module to facilitate this request?

# Answer
Turns out the module does it automatically. I also asked for this as an interface enhancement on drupal.org. The developer responded saying that that feature already exists. All you have to do is set the field to unlimited. How freaking awesome is that?!
> 0 votes

# Answer
It is not a Drupal Module but a very simply jQuery plugin to use.

http://jquery.malsup.com/cycle/

A snippet of me using it from my javascript:

```
function handle_header_carousel() {
    if ( jQuery('#header_carousel').get(0) == undefined ) {
        return;
    }
    jQuery('#header_carousel').cycle({
        fx:     'fade',
        speed:   300,
        timeout: 3000,
        next:   '#s3',
        pause:   1
    });
}

```

From my template page that houses the images:

```
<div id="header_carousel">
            <img src="/<?php echo drupal_get_path("theme", "tcth"); ?>/img/carousel_1.jpg" />
            <img src="/<?php echo drupal_get_path("theme", "tcth"); ?>/img/carousel_2.jpg" />
            <img src="/<?php echo drupal_get_path("theme", "tcth"); ?>/img/carousel_3.jpg" />
            <img src="/<?php echo drupal_get_path("theme", "tcth"); ?>/img/carousel_4.jpg" />
        </div>

```
> 2 votes

---
Tags: 7
---


# Question
Title: Custom page containing list of nodes separated by content type and date like an Archive
How can I create a custom page containing list of nodes separated by content type and date like an Archive?

I think it requires pagination too. So is there any module for this purpose (Drupal 6)?

# Answer
I did this:

1. Installed and enabled the Views module
2. Installed and enabled the Archive module
3. Enabled the *Archive* view
4. Added the following lines in the template file

```
print views_get_view(archive);
print $content;

```
> 1 votes

---
Tags: theming, nodes, 6
---


# Question
Title: How to treat users as Anonymous in Confidential Groups?
Here is my problem.

* Mark an Organic Group as Confidential Group while creating it.
* Users will be asked with a question saying would you like to be Anonymous while joining Confidential Group.
* If user opted for Anonymous then all the content and activity inside group will be shown as Anonymous user as Author in front end but who posted details will be tracked in back end with user details. So, Technically Content Author is author of the node, but Author field should be shown as anonymous in front end !

This will be useful in Sensitive Groups where user identity should be hidden.

Any hooks or out of the box modules or solutions for above three problems ?

# Answer
I would add a "anonymous" field in the user account: admin/config/people/accounts/fields

then, in node pre-processing, do a check to see if the author of the node is anonymous and re-write the author field accordingly.
> 2 votes

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


# Question
Title: archive_page() from archive module in drupal 6 shows all nodes not date specific
I installed Archive module and used following code in a custom template:

```
print archive_page('all', 2012, 10, 12);

```

but it shows every single node I posted, How can I make it load nodes according to date I specified in the code?

# Answer
> 3 votes
I just tested archive page in Drupal 6.26 and using Archive 6.x - 1.4 . It is working as expected. Maybe you are date and month in the archive\_page. Please find the detailed explanation below.

The parameters of `archive_page()` are the following ones:

* $year
Number of year.
* $month
Number of month.
* $day
Number of day.

So `print archive_page('all', 2012, 10, 12);` will return the nodes created on October 12, 2012. I just followed the below process to verify the functionality.

* I installed archive module
* I enabled the module
* I enabled content types in "admin/settings/archive"
* I created two pages using Page one, and Page two as titles
    + Page one's authored date is October 13, 2012
    + Page two's authored date is October 15, 2012
* I enabled the PHP filter module
* I created a block with the below code, and enabled it on the right side bar

```
module_load_include('inc', 'archive', 'archive.pages');
print archive_page('all', 2012, 10,  13);

```

It does display the following output where only "Page one" is the one authored on October 13, 2012.

# Answer
> 0 votes
Here is How I fix my problem:

Created a view that prints out months (link), enabled pagination and added some fields to print and now I get months list with post titles in pages.

---
Tags: 6, nodes, theming, datetime
---


# Question
Title: How to write a self join query in drupal 7 using db_select
I want to write a self join query, However I dunno how to write it in drupal 7 using `db_select()`.

The query will look like this

> SELECT * FROM msg where sender = receiver

Both sender and receiver fields are part of the `msg` table.

# Answer
Its possible with the following query,

```
db_select('msg')
  ->fields('msg')
  ->where('sender = receiver');

```
> 0 votes

# Answer
A query using `db_select` is a lot slower than a 'vanilla' `db_query` call...for a query as simple as the one you're doing just run it through db\_query:

```
$query = db_query('SELECT * FROM msg where sender = receiver');

```
> 4 votes

---
Tags: database
---


# Question
Title: How to get a themed form via Ajax in D7?
I'm trying to get a D7 form into a Bootstrap modal dialog. I had this working on D6, through a semi-straightforward process:

* The jQuery code that's building and showing the modal does an $.ajax call to a url on my site to get the form contents -- something like /get\_my\_form/123. This request is picked up by a Drupal menu entry that makes a call to drupal\_get\_form() with the appropriate form function and various parameters. The usual Drupal form-creation thing.
* There's a theme function for the form that does a couple of things and then sends the results back to jQuery by doing:

print json\_encode($the\_form\_contents);
exit;
* The ajax handler, which is expecting a json object, gets the results and sticks them into the body of the modal, and puts it up.

In moving this code to D7, I've been following the same route. It almost works, but the ajax call continually fails because the response string from the server includes the HTML from a page template, up to the point where the "exit" in the theming function kills the PHP request. That HTML is obviously not a expected part of the JSON object, but I can't figure out how to get rid of it. I've tried using drupal\_json\_encode in place of json\_encode, and replacing the "print" statement with a call to drupal\_json\_output, but the page template stuff keeps coming. I'm definitely not adding it to what's produced in the theme function, so there must be some other part of Drupal that's squirting it out in ajax's direction.

Any ideas? This has REALLY been driving me crazy this afternoon. Thanks!

# Answer
I don't know that this counts as a duplicate, but the answer by "jeroen" on https://stackoverflow.com/questions/247991/displaying-a-drupal-view-without-a-page-template-around-it got me past this. It's a greasy little hack (no offense, jeroen!), but it seems to work.
> 0 votes

---
Tags: theming, forms, ajax, javascript
---


# Question
Title: How to print taxonomy term name with published node count and with a custom link?
How can I print taxonomy name with published node count with a custom link?

eg: Taxonomy term-a (23) Taxonomy term-b (10) Taxonomy term-c (55)

I need to link each of them to a separate page.

I found this below code to print taxonomy term with count. but now how to make to print specific taxonomy term with it's node count? so that I can link it to a page later, so if I repeat the same code with different term ids to have multiple terms with its count.

```
    <?php
$vid = 23;  // Set the vid to the vocabulary id of the vocabulary you wish to list the terms from
$parent = 130;

$terms = taxonomy_get_tree($vid, $parent, -1, 1);
foreach ( $terms as $term ) {
  $count = db_result(db_query("SELECT COUNT(n.nid) FROM {node} n INNER JOIN {term_node} t ON n.nid = t.nid WHERE t.tid = %d AND n.status = %d", $term->tid, 1));
  {
    print '<div>' . l($term->name, "taxonomy/term/$term->tid") . " ($count)"  . '</div>';
  }
}
?>

```

Can someone please help me?

**\__*HAD TO ANSWER HERE AS I CAN'T AT THE BOTTOM*\__**

This is it!!!

Took a while to write this code... :(

```
<?php
$tid = 100;
$term = taxonomy_get_term($tid);
$name = $term->name;
$result = db_result(db_query("SELECT COUNT(n.nid) FROM {node} n INNER JOIN {term_node} t ON n.nid = t.nid WHERE t.tid = %d AND n.status = %d", $term->tid, 1));
print '<div><a href="http://example.com/">' . $name. " ($result)" . '</a></div>';
?>

```

Change: 100 at the second line of above code to your specific taxonomy id, that's it and repeat the same for different tid.

And make sure to change the link at the bottom from (http://example.com/) to your (custom link).

Thanks a lot to all, let me know if this code can be fine tuned further...

# Answer
Although it looks like you have come up with a solution, you might want to compare against the Taxonomy List module.
> 0 votes

---
Tags: 6, taxonomy-terms
---


title: Disable product when out of stock

text:
# Question
Title: Disable product when out of stock
I would like to disable a product as soon as it's stock drops to 0 in Drupal commerce.

I think this might be possible by using rules, but then I don't know what will happen to the product display. I figure that when there are no more active products attached to a product display, the display will still appear in my views but without any product information attached to it. In this case I would also like the product display to be "unpublished".

I can't unpublish the product display immediately after a given product is out of stock because there could be more products added to a single display...

Can some one help me to achieve this through rules or is there some other method that I could use?

I'm using Drupal Commerce and the stock module for it.

# Answer
Here's a pretty basic rule that disables the Product SKU when stock hits 0:

```
{ "rules_out_of_stock" : {
"LABEL" : "Out of Stock",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules", "entity" ],
"ON" : [ "commerce_product_presave" ],
"IF" : [
  { "entity_is_of_type" : { "entity" : [ "commerce-product" ], "type" : "commerce_product" } },
  { "data_is" : { "data" : [ "commerce-product:commerce-stock" ], "value" : "0" } }
],
"DO" : [
  { "data_set" : { "data" : [ "commerce-product:status" ], "value" : 0 } }
]}}

```
> 5 votes

# Answer
Seems really odd that the maintainer would say that this was impossible and a fringe case.

Seems to me like this is a very normal use case, in fact one that we use on every single Ubercart site we have in production. I actually thought this was a setting in the module config page and was surprised to see that it wasn't.

Anyway, here's what I did. I disabled the included rule because I despise rules and added this code to my module:

```
/**
 * Implements hook_commerce_checkout_complete().
 */
function MYMODULE_commerce_checkout_complete($order) {
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $line_items = $order_wrapper->commerce_line_items->value();
  if (is_array($line_items)) {
    foreach ($line_items as $line_item) {
      if (in_array($line_item->type, commerce_product_line_item_types())) {
        $product = commerce_product_load_by_sku($line_item->line_item_label);

        // Subtract the sold amount from the available stock level.
        $qty = (int) $line_item->quantity;
        module_load_include('inc', 'commerce_stock', 'commerce_stock.rules');
        commerce_stock_adjust($product, -$qty);

        // Disable the product if we have no stock left
        $product_wrapper = entity_metadata_wrapper('commerce_product', $product);
        if ($product_wrapper->commerce_stock->value() <= 0) {
          $product_wrapper->status->set(0);
          $result = $product_wrapper->save();

          if ($result) {
            watchdog('commerce_stock', 'Product %sku stock level reached 0, status set to 0.', array('%sku' => $product->sku));
          }
          else {
            watchdog('commerce_stock', 'Failed attempt to disable product %sku', array('%sku' => $product->sku), WATCHDOG_ERROR);
          }
        }
      }
    }
  }
}

```

It's just a copy of the default rule that ships with the module with the extra code for disabling the product added in.

I guess you could leave the default rule active and remove the 3 lines that adjust the stock level in my example, but then I'm not sure what would be called first, the rule or my hook so you would have to test that yourself.
> 4 votes

---
Tags: commerce
---


title: payment method in commerce

text:
# Question
Title: payment method in commerce
I want to make a payment method, that works with web services. I made set of rules that decrease the money from the bank. at last the bank give me a code that it notices whether the payment is successful or not.for example 1 or 0. I want that if the code is 1 for example, Drupal thinks that payment is successful, and when the code is 0, means payment failure. and affect stock to decrease or increase by the returned code. how can I do that? is there any simple sample of on-site payment method ? thanks

# Answer
> 2 votes
This page has everything you need to know, including example payment method modules you can use as reference implementations:

http://www.drupalcommerce.org/developer-guide/utilizing-core-apis/writing-payment-method-module

---
Tags: commerce
---


# Question
Title: Contextual filter has no results when using entity translation of non default language
I have a view that shows content with an entity reference field referencing the currently displayed node. This is a scenario often used, just a block (pane in my case) that shows content (child nodes) that belongs to the current node (parent node).

This uses the contextual filter (Content entity referenced from field\_section\_reference) Content: Nid with 'provide default argument': content ID from URL'

The view is filtered with 'Field Language:Current user's language'

This works fine for the default site language, showing all content of the language (url language selection) But when I use the language switcher, the view does not show anything any more. Translated content of current language is not shown.

I removed the contextual filter and added a normal filter, selecting manually a language other than the default site language. This worked, translated content shows fine.

If you are reading this and have entity translation enabled in a similar setup, please do me a favor and test if I'm right. I have spend quite some hours trying to find alternatives and workarounds, but can't display a view of translated content that is referencing the currently displayed node, when using a not-default language.

# Answer
> 2 votes
not sure if I had the exact problem, but I solved my views / ET woes by adding 'entity translation' relationship. then you can filter by 'entity translation: language' and then select to user the user's current language. hopefully this helps!

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


title: Are there general css paths for drupal

text:
# Question
Title: Are there general css paths for drupal
Is there a specific drupal way to focus on one specific part of a nodes element in the css path? For example if I change the H2 element within my theme css it changes all H2... How can I change one specific one on the page. The object is to be able to focus on particular elements to make them unique... If this is possible how do I write the style declarations?

# Answer
Drupal allows your site to have many Themes installed. Themes can define their own HTML structure to make your site look a certain way. Drupal has a few themes the ship out-of-the-box.

Depending on the theme you use it may or may not contain HTML `class`es or `id`s in the source to easily target specific items on the page. Typically, themes and Core html is fairly darn flexible.

Looking at the Zen Theme HTML and CSS markup you can see it has fairly specific rules to get at and theme alot of the content from Zen and also core drupal themes: Useful CSS selectors to add to your stylesheets
> 0 votes

---
Tags: theming
---


# Question
Title: Site's settings file return blank screen
I'm looking through a few of my drupal sites since the recent DRUPAL-SA-CORE-2012-003 security update. I noticed that on a few of them, if I navigate to the settings.php file location through the url. The browser is just a blank page. Does this mean I can access the settings.php file? Or is this the intended functionality due to proper permissions being set?

# Answer
> 6 votes
This is the intended functionality - your web/server user should be able to access the file and serve it over http but the file by itself doesn't do anything unless its included in the rest of the Drupal bootstrap.

The core concern of this security notice is that there is a vulnerability if the settings.php file is writable or owned by the webserver.

---
Tags: security
---


# Question
Title: taxonomy menu select list with redirect when a menu item is selected
I'd like to have a taxonomy drop-down list like the one in www.1mobile.com.

When I select an term, it should go to the respective page, showing products concerning with selected term. I tried Custom Search module. But as far as I concern, it is not meet my requirement.

What is the best way to fulfill this requirement?

# Answer
> 0 votes
I've chosen "custom module".

```
function my_module_block_info() {
    $blocks['quicklinks'] = array(
    'info' => t('Quick Links'),
    'cache' => DRUPAL_NO_CACHE
    );
    return $blocks;
}

function my_module_block_view($delta = '') {
$block = array(); # Declare array

switch ($delta) {
case 'quicklinks' :
    $options = array(); // Options for category combo

    // Getting terms from vocabulary "Category"
    $terms = my_module_taxonomy_get(4, 0); //echo '<pre>';print_r($terms);echo '</pre>';
    $options['c-all'] = t('Choose a Category');
    foreach ($terms as $term) {
        $options[$term->tid] = $term->name;
    }

    // Block View
    $block['subject'] = 'Quick Links';
    $block['content'] = array(
        'combo' => array(
            '#type'          => 'select',
            '#default_value' => 'c-all',
            '#options'       => $options,
            '#attributes'    => array(
                'id' => 'quick_links_select',
                'class' => array('quick_links', 'select'),
                'onchange' => 'my_module_browse_by_category()'
            ),
        ),
        'links1' => array(
            '#type' => 'markup',
            '#prefix' => '<div class="quick_links top link">',
            '#markup' => l('Future icons Apps', base_path() . 'ours'),
            '#suffix' => '</div>',
        ),
        'links2' => array(
            '#type' => 'markup',
            '#prefix' => '<div class="quick_links second link">',
            '#markup' => l("Editor's Choice", base_path() . 'editor'),
            '#suffix' => '</div>',
        ),
        'links3' => array(
            '#type' => 'markup',
            '#prefix' => '<div class="quick_links third link">',
            '#markup' => l('Apps Starter Kit', base_path() . 'appstarter'),
            '#suffix' => '</div>',
        ),
        'links4' => array(
            '#type' => 'markup',
            '#prefix' => '<div class="quick_links forth link">',
            '#markup' => l('Games Starter Kit', base_path() . 'gamestarter'),
            '#suffix' => '</div>',
        ),
    );
 }
 return $block;
}

function my_module_taxonomy_get($vid, $get_base_term = FALSE) {
  // Getteing Terms
  $query = db_select('taxonomy_term_data', 't');
  $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
   $result = $query
    ->fields('t')
    ->condition('t.vid', $vid)
->condition('h.parent', 0, '!=')
    ->orderBy('t.name')
    ->execute();

  foreach ($result as $term) {
    $terms[] = $term;
  }

  return $terms;
}

```

With above code, I got what I want. But I don't understand much about $block\['content'\] thing and how \['content'\] is rendered.

Is there any sources which fully explain how it works ?

Thanks

# Answer
> 1 votes
Try Autocomplete Deluxe, it has a taxonomy widget available for use, and I used it just the other day and I believe that it does what you need it to do.

# Answer
> 1 votes
Try Better Jump Menus. It does not have specific support for taxonomy but it has an api to do it via custom module. If you do not want to go the custom module way then have a look at Taxonomy menu can be used along to get the desired effect.

Other option would be Jump

---
Tags: routes, search, navigation, taxonomy-terms
---


title: What is "Advanced Mode" in Views 3?

text:
# Question
Title: What is "Advanced Mode" in Views 3?
In this article the first instruction is

> On every site, run `drush vd` to turn the Views settings to the advanced mode.

What does this mean? A Google search for "Views advanced mode" yields mostly just links back to this article. What is "advanced mode"?

# Answer
> 14 votes
Advanced mode means

> Set the Views settings to more developer-oriented values.

You can check the definition of this in views module Drush folder views.drush.inc file.

```
  $items['views-dev'] = array(
    'callback' => 'views_development_settings',
    'drupal dependencies' => array('views'),
    'description' => 'Set the Views settings to more developer-oriented values.',
    'bootstrap' => DRUSH_BOOTSTRAP_DRUPAL_FULL,
    'aliases' => array('vd'),
  );

```

Once drush vd command is executed following variables are set.

```
  variable_set('views_ui_show_listing_filters', TRUE);
  variable_set('views_ui_show_master_display', TRUE);
  variable_set('views_ui_show_advanced_column', TRUE);
  variable_set('views_ui_always_live_preview', FALSE);
  variable_set('views_ui_always_live_preview_button', TRUE);
  variable_set('views_ui_show_preview_information', TRUE);
  variable_set('views_ui_show_sql_query', TRUE);
  variable_set('views_ui_show_performance_statistics', TRUE);
  variable_set('views_show_additional_queries', TRUE);
  variable_set('views_devel_output', TRUE);
  variable_set('views_devel_region', 'message');
  variable_set('views_ui_display_embed', TRUE);
  $message = dt("Setup the new views settings.");
  drush_log($message, 'success');

```

You can do it with out using drush command too by navigating to "admin/structure/views/settings"

---
Tags: views
---


# Question
Title: using EntityFieldQuery, how to order results based on a node reference field title and/or field collection item field, says name
I have a node which references another, I want to order the results based on the title of the referenced field title.

I'm using

```
function listAll(){
  $query = new EntityFieldQuery();
  $entities = $query->entityCondition('entity_type', 'node')
                    ->entityCondition('bundle', 'building')
                    ->fieldOrderBy('field_reference_area', 'title', 'ASC')
                    ->execute();

  $nodes = entity_load('node', array_keys($entities['node']));

  foreach($nodes as $key => $fac){
      dsm($fac);
  }
}

```

# Answer
> 1 votes
I'm afraid this won't be possible using EntityFieldQuery. You could build your own query using `db_select()` and have full control over it.

You can refer to this post and try to adapt it to fit your needs.

# Answer
> 0 votes
You can use join using something like

`$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'building')
->fieldOrderBy('field_reference_area', 'title', 'ASC')
->addTag('JOINTABLE');
->execute();`
And now use this tag to join another table
`function MYDMOULE_query_JOINTABLE_alter(QueryAlterableInterface $query) {
$query->join('reference_table', 'r', 'r.nid = node.field_referencefield_value');
}`

This is just a sample example. Try to modified it with your need. :)

---
Tags: database
---


# Question
Title: How to get nodes by custom field value using EntityFieldQuery?
I am trying many options, e.g:

```
$entities = $nodeQuery->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'article')
    ->fieldCondition('field_archived','field_archived_value', '1', '=')
    ->pager(10)
    ->execute();

```

`field_archived` is the machine name of my custom field added to `article`. `field_archived_value` is a column inside `field_data_field_archived` table.

In this case I am getting error:

```
PDOException: SQLSTATE[42S22]: [Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid column name 'field_archived_field_archived_value

```

What I am doing wrong here?

# Answer
The correct code is the following one.

```
$entities = $nodeQuery->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->fieldCondition('field_archived','value', '1', '=')
  ->pager(10)
  ->execute();

```

Instead of `'field_archived_value'` you need to use `'value'`.
> 11 votes

# Answer
In entity query, you need to write the machine name of the field, not the table name.
> 0 votes

---
Tags: 7, database
---


# Question
Title: Is it possible that search could index token content?
Using the Token module with the Token Filter module, one can put a token in the body of a node.

When visitors search for a content they would like to find whatever is show in page, no matter how is it placed there. However, tokens are only replaced before node renders. Is it possible that the search mechanism could index the token content?

# Answer
The search index includes the content of the nodes after they are rendered.

node\_update\_index() is an implementation of hook\_update\_index(), the hook that is invoked when the search index needs to be updated; it calls \_node\_index\_node() which contains the following code.

```
  $node = node_load($node->nid);

  // ...

  // Render the node.
  $build = node_view($node, 'search_index');
  unset($build['#theme']);
  $node->rendered = drupal_render($build);

  $text = '<h1>' . check_plain($node->title) . '</h1>' . $node->rendered;

  // ...

  // Update index
  search_index($node->nid, 'node', $text);

```

Similar code is present in `_node_index_node()` for Drupal 6.

```
  $node = node_load($node->nid);

  // ...

  // Build the node body.
  $node->build_mode = NODE_BUILD_SEARCH_INDEX;
  $node = node_build_content($node, FALSE, FALSE);
  $node->body = drupal_render($node->content);

  $text = '<h1>' . check_plain($node->title) . '</h1>' . $node->body;

  // ...

  // Update index
  search_index($node->nid, 'node', $text);

```

In your case, if the node body contains a token such as \[global:test\], whose content is test, the search index will contain test, not \[global:test\].
> 2 votes

---
Tags: search, tokens
---


# Question
Title: Migrating D5 users to D6 using MigrateDestinationUser
I'm using the migrate module to migrate users from a Drupal 5 site to a Drupal 6 site.

MigrateDestinationUser assumes that the source passwords will be plaintext which isn't the case in Drupal 5. Is there any way around this assumption?

# Answer
As per http://drupal.org/node/1349758, you need to add a complete function:

```
$this->addFieldMapping('pass', 'source_password');
...
public function complete($account, $row) {
  db_update('users')
    ->fields(array('pass' => $row->source_password))
    ->condition('uid', $account->uid)
    ->execute();
}

```
> 1 votes

---
Tags: migrations
---


title: Jquery not working on node edit page

text:
# Question
Title: Jquery not working on node edit page
Added jquery library, it works fine, but when i click on node edit, jquery does not work for this page. I need to style some inputs inside this edit page. I am using theme zen. For example i want to change color of edit-title

```
(function($) {
$(document).ready(function(){

    $('#edit-title').css('color', 'red');

  });
})(jQuery);

```

not working. Its loaded i see in firebug. But any code does not work(only inside edit or admin menus).

# Answer
In the firebug(any) console, try `jQuery('#edit-title').css('color', 'red');` it should work or something with the css is wrong.

For Drupal you're really supposed to use something like this to do on document load:

```
(function ($) {
  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
      $('.example', context).click(function () {
        $(this).next('ul').toggle('show');
      });
    }
  };
})(jQuery);

```

Check out Managing JavaScript in Drupal 7, and search for "behaviors".

@ krister.. The code is a function where the `$` variable is `jQuery`. So in most languages you create function and declare variables that you want passed into it. Well in JavaScript you can create that in one line.

```
function some_function(tmpVar){ alert(tmpVar); }
some_function("Woot!");

You can wrap the function side in ()s and it still works
( some_function )("Woot!");

Now you can put an anonymous function block instead of some_function

( function(tmpVar){ alert(tmpVar); } )("Woot!");

```

and finally the jQuery

```
(function($){... the $ = jQuery ...})(jQuery);

```
> 3 votes

---
Tags: javascript
---


# Question
Title: How do I fix my Commerce Feeds import process post updating my modules and core?
I have just upgraded to core 7.15 and updated all my modules at the same time. When I now try and run the an import using commerce feeds I receive the error below.

```
    An AJAX HTTP error occurred.
    HTTP Result Code: 200 Debugging information follows.
    Path: /batch?id=892&op=do
    StatusText: OK
    ResponseText: Fatal error:
Call to undefined function commerce_product_validate_sku() in /home/mmlcofdk/public_html/sites/all/modules/commerce_feeds/plugins/FeedsCommerceProductProcessor.inc on line 216

```

I would really appreciate some advice on how I could go about debugging this...

# Answer
> 2 votes
I have the same problem. I think that is because I am using a old version Drupal Commerce and it is incompatible the newer version of Feeds module that i am using.

but I manage to get it work by paste in this function:

```
function commerce_product_validate_sku($sku) {
  // Do not allow commas in a SKU.
  if (strpos($sku, ',')) {
    return FALSE;
  }

  return TRUE;
}

```

into the file "commerce\_prouduct.module" located in:

```
{mydrupal-installation}\profiles\commerce_kickstart\modules\commerce\modules\product

```

I found that function in:

http://drupalcontrib.org/api/drupal/contributions!commerce!modules!product!commerce\_product.module/7

Hope that help!

Apollo Tang

---
Tags: commerce, feeds
---


title: Limit results of the entity reference

text:
# Question
Title: Limit results of the entity reference
I have been trying to find the solution to this problem. I am referencing a serial of nodes with entity reference, but I just want to display the latest 3 nodes. Is there any way I can limit the results of the entity reference? I need to have unlimited Number of values but just need to display the last 3 for that case. I am not using views.

I am using Drupal 7

Thanks :)

# Answer
> 0 votes
@junedkazi your point is valid. However, a more flexible solution is to install Display Suite so you can control and limit the number of items on a multiple value field, and works also with entity reference.

There is an extra textfield on the manage display screens to limit the output per field instead of # (to show them all) you can write the number of the items that you would like to display.

I have attached a video that explains better the solution. It is necessary to active the extras that comes with Display Suite in modules administration.

Limiting the number of fields

# Answer
> 2 votes
You can always use the Views: Filter by an entity reference view option from Entity selection mode and then create a view and set the number of items to 3.

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


# Question
Title: Can I use the $user global variable for security purposes?
I am developping a module which allows users to modify information about themselves using a form. I want to make sure no user is able to modify the informations about another user. To do this, I thought I could use the uid provided in the `$user` global variable. So my question is: is this safe enough? Or is it somehow possible for `$user->uid` to return something other than the current user's uid? In other words, is it possible to *cheat* the `$user` global object?

This is not the best way to ask this question, feel free to suggest improvements.

edit: Another way of asking this is: Does $user-\>uid return something different than 0 **only** in the case where the current user has been properly authenticated?

# Answer
> 4 votes
In short, yes, what you describe is how Drupal identifies the active, logged-in user. Wherever possible, though, you should use API functions such as user\_access('module permission') to check access rights, where 'module permission' is a string defined in your module's hook\_permission function and set for each role on the admin permissions page.

**Edit:** If you want to see if the current user is authenticated, check to see if $user has the authenticated user role. See Check if a user has a role

# Answer
> 2 votes
> Or is it somehow possible for `$user->uid` to return something other than the current user's uid?

The user object is initialized in \_drupal\_session\_read() using the following code. (`_drupal_session_read()` is a session handler set by Drupal.)

```
// Secure page session.
$user = db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.ssid = :ssid", array(':ssid' => $sid))->fetchObject();

```

```
// Not secure page session.
$user = db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.ssid = :ssid", array(':ssid' => $sid))->fetchObject();

```

`$sid` is the session ID.

For authenticated users, the session ID is generated in drupal\_session\_regenerate() using the following code.

```
$session_id = drupal_hash_base64(uniqid(mt_rand(), TRUE) . drupal_random_bytes(55));

```

`$user` is initialized to currently logged-in user if:

* `$_COOKIE[session_name()]`, or `$_COOKIE[substr(session_name(), 1)]` is set
* There is a database row in the sessions tables for the current session ID

In the other cases, `$user` is initialized to the object for the anonymous user.

---
Tags: 7, users
---


# Question
Title: How to merge WYSIWYG fields from separate nodes
I would like to know if it is possible to merge the contents of two separate WYSIWYG fields from separate nodes to create a new node containg both.

Does anybody know of a module that performs this function or something similar, or would this require the writing of a new module?

The use case is for a newsletter, the WYSIWYG fields being populated by articles, and saved to separate nodes. The end result would be a node that contained all articles in a single WYSIWYG field.

# Answer
Welcome to Drupal Answers. You can use views module with simplenews to achieve above functionality.

Please find simplenews features below.

* Sending nodes as newsletters to subscribers
* Multiple newsletter categories with separate settings
* Per category and multi-signup Blocks and Pages
* Subscriber management including mass-subscription and export
* Optional E-mail confirmations for anonymous users
* Customizable newsletter templates
* Support for HTML (including text alternative) newsletter when used in combination with a supported mail system module
* **Views and Rules integration**
* Support for multi-language newsletters
> 1 votes

---
Tags: nodes, database, wysiwyg
---


# Question
Title: Is there a way to get all values for a particular node?
I would like to create a customized view and search page by writing my own module because I believe that Views is unable to do what I want. This requires me to write my own SQL queries, as well. Is there an API call I can use to get all the data and values about a specific node? For example, if I had a content type that asked for your first name and last name:

```
$values = get_node($nid)

```

and $values would end up looking something like:

```
$values['first_name'];
$values['last_name'];

```

Right now, it seems that all the fields and values are in their own tables, which makes it a nightmare in writing my SQL query to gather all data about the particular node.

# Answer
You can use node\_load() function.

eg:

```
 $node = node_load(nid); //you will get all fields values of particular node
 print_r($node);

```
> 3 votes

---
Tags: 7, database
---


# Question
Title: What are bundles? Can we create custom bundles?
Does all nodes have bundles? Also can we create custom bundles?

# Answer
> Bundles are an implementation of an entity type to which fields can be attached. You can consider bundles as subtypes of an entity. With content nodes, for example, you can generate subtypes like articles, blogs, or products. Not all entity types have bundles, however. For example, users do not have separate bundles or subtypes. With bundles, you can have as many subtypes as you want. Then, using the Field system, you can add additional fields to those bundles such as file download field for Articles and location fields for Users.

Read more here and a good article that i found. Hope it helps :-)
> 7 votes

---
Tags: entities
---


title: How to make "php if" for views block?

text:
# Question
Title: How to make "php if" for views block?
I'm generate views content with this:

```
<?php echo views_get_view('xtr')->preview('block_1', array(1)); ?>

```

But I need to add `slidewrap` class only if the content available.

Below is what I've tried which not working:

```
<?php if (views_get_view('xtr')->preview('block_1', array(1))): ?>
  <div class="slidewrap"><?php echo views_get_view('xtr')->preview('block_1', array(1)); ?></div>
<?php endif; ?>

```

# Answer
> 2 votes
To check if your views output have contents use following snippet

```
<?php
 $view = views_get_view_result($name, $display, $args);
 $result = count($view);
 if ($result) {
   //do your stuff here
 }
?>

```

---
Tags: 7, views, theming
---


# Question
Title: Display Suite - code field retrieve the first value in a multivalue field?
I've created a view mode to display a value multivalue image field. The rendered entity utilizes display suite to display the images. There are 12 images in this field for this all of the nodes of this content type.

Is it possible to just display one image instead of the 12 as a code field in display suite? If so how does one do that.

# Answer
There is an extra textfield on the manage display screens to limit the output per field where it says # change for a number so you can limit the results. You can also see this video to see how it works Limit the number of fields to display on Field UI with Display Suite

There is another video from a drupalcon that I love the way they explain how to render the content in display suite if you need more information.

take-full-control-your-site-layout-display-suite-drupal-7
> 1 votes

# Answer
When you have a multivalue field, you have also a # on the format column. It represents all images. If you want to show only one or two images, you must write 1 or 2 in the box.

Good luck
> 3 votes

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


# Question
Title: How to add exposed form block to .tpl.php
I've added this code to preprocess function but it dosen't work : in preprocess :

```
//edit_search_api_views_fulltext is the form_id of exposed form block;
$vars['custom_search'] = drupal_render(drupal_get_form("edit_search_api_views_fulltext"));

```

in tpl.php

```
print $custom_search;

```

What I'm missing ?

# Answer
You want to print an exposed block in tpl, right? I am using this in drupal 7

```
<?php
  $block = block_load('views', '-exp-VIEWNAME-DISPLAYNAME');
  $output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));
  print $output;
?>

```

for example

```
<?php
  $search_block = block_load('views', '-exp-cruise_package-page');
  $output =  drupal_render(_block_get_renderable_array(_block_render_blocks(array($search_block))));
  print $output;
?>

```
> 1 votes

---
Tags: theming
---


# Question
Title: Why file attachment has different URLs in icons links and default link on node page?
I have node with attached file. Node attachments view look:

`sample.pdf` link has url like `sites/default/files/sample.pdf`. I can download file via this link.

Links with icons has URL like `download/file/fid/[id]`

I can't download some of files via icon links (403).

How can I change this behaviour? I want those links point to \`sites/default/files/sample.pdf

# Answer
> 1 votes
I believe, there can be custom or some contributed module doing the trick. The menu - download/file/fid/\[id\] is created by some module and allowing you to download the file. Might be a case that the logic is written in the same callback.

try searching your modules with this callback and you might see some results...

---
Tags: 7, files
---


title: Why doesn't my new tab show?

text:
# Question
Title: Why doesn't my new tab show?
I just made a new tab (quicktabs) with the drupal interface, but it is not displayed like the other tabs. In fact, it doesn't show at all. How can I debug such a problem?

# Answer
> 0 votes
The problem was that the view I had assigned to that tab did not work (I don't know why). Still, I am surprised that the tab itself wouldn't show just because the view is broken.. Whatever, problem solved.

# Answer
> 1 votes
You have to assign the quicktab block to a particular region. Then you might be able to see the tabs

---
Tags: blocks
---


# Question
Title: How to get visitors count of a page created using views
I have created a page in Drupal using views. Is there any option to get the count of visitors that visit the page?

# Answer
Enable the **statistics** module that comes with core in admin/module. You can start tracking pages once you enable the log settings in admin/config/system/statistics

Once you enable the Setting Enable access log drupal will start tracking all pages. Now follow below process to create a view.

* Create a view with base type as access log
* Enable aggregation in the other settings
* Add Access Log path field and set "Group results together" in aggregation settings next to field settings.
* Add one more field access log path and select Aggregation type as count.
* Now you can see all paths and number of visits associated with them.
* Add filter access log path and provide the path for which you would like to see number of visits.

Find the exported view below.

```
$view = new view();
$view->name = 'statistics';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'accesslog';
$view->human_name = 'Statistics';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Statistics Custom';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Access log: Path */
$handler->display->display_options['fields']['path']['id'] = 'path';
$handler->display->display_options['fields']['path']['table'] = 'accesslog';
$handler->display->display_options['fields']['path']['field'] = 'path';
/* Field: COUNT(Access log: Path) */
$handler->display->display_options['fields']['path_1']['id'] = 'path_1';
$handler->display->display_options['fields']['path_1']['table'] = 'accesslog';
$handler->display->display_options['fields']['path_1']['field'] = 'path';
$handler->display->display_options['fields']['path_1']['group_type'] = 'count';
$handler->display->display_options['fields']['path_1']['label'] = 'Count';
/* Filter criterion: Access log: Path */
$handler->display->display_options['filters']['path']['id'] = 'path';
$handler->display->display_options['filters']['path']['table'] = 'accesslog';
$handler->display->display_options['filters']['path']['field'] = 'path';
$handler->display->display_options['filters']['path']['value'] = 'admin/config/system/statistics';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['path'] = 'statistics-custom';

```

That's it :-)

If you would like to display page counter contextually then below code in a custom block will help.

```
<?php
$path = $_GET['q'];
drupal_set_message($path);
$visits = db_query("SELECT count(*) FROM {accesslog} where path = :path", array(':path' => $path))->fetchField();
echo "Views: " . $visits;
?>

```
> 6 votes

---
Tags: views
---


# Question
Title: How can I make a view to show all own comments?
I'm trying to show all comments the logged user did on a forum from the module advanced forum. I've tried using views, adding a relationship with content:autor and filtering by user:current. But didn't work. Also I've tried contextual filter with the parameter comment :author id. Anyone can help?

I'm using D7.

# Answer
> 1 votes
Follow below steps to create a view.

* Login as admin
* Go to admin/structure/views/import
* Copy paste below code in "Paste view code here"

**$Below code**

```
$view = new view();
$view->name = 'user_forum_comments';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'comment';
$view->human_name = 'User Forum Comments';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE;

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'User Forum Comments';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'comment';
/* Relationship: Comment: Content */
$handler->display->display_options['relationships']['nid']['id'] = 'nid';
$handler->display->display_options['relationships']['nid']['table'] = 'comment';
$handler->display->display_options['relationships']['nid']['field'] = 'nid';
$handler->display->display_options['relationships']['nid']['required'] = TRUE;
/* Field: Comment: Title */
$handler->display->display_options['fields']['subject']['id'] = 'subject';
$handler->display->display_options['fields']['subject']['table'] = 'comment';
$handler->display->display_options['fields']['subject']['field'] = 'subject';
$handler->display->display_options['fields']['subject']['label'] = '';
$handler->display->display_options['fields']['subject']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['subject']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Comment: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'comment';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: Comment: Author uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'comment';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'current_user';
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Comment: Approved */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'comment';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status_node']['id'] = 'status_node';
$handler->display->display_options['filters']['status_node']['table'] = 'node';
$handler->display->display_options['filters']['status_node']['field'] = 'status';
$handler->display->display_options['filters']['status_node']['relationship'] = 'nid';
$handler->display->display_options['filters']['status_node']['value'] = 1;
$handler->display->display_options['filters']['status_node']['group'] = 1;
$handler->display->display_options['filters']['status_node']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['relationship'] = 'nid';
$handler->display->display_options['filters']['type']['value'] = array(
  'forum' => 'forum',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['path'] = 'user-forum-comments';

```
* Click on Import
* Go to user-forum-comments to see results
* Go to admin/structure/views/view/user\_forum\_comments/edit to see how view is constructed.

Hope it answers :-)

---
Tags: views, nodes
---


title: Form returning value issue

text:
# Question
Title: Form returning value issue
I am trying to adapt a Drupal 5 form to a Drupal 7 form, but something is not working. The form is correctly displayed, but when "Submit" button is clicked the information in the form is not correctly send to $\_GET. What am I missing??

```
<?php
 function my_menu($may_cache) {
  $items = array();
    $items['admin/reporting/report_details'] = array(
    'title' => 'Report: User details by stores',
    'access arguments' => array('access content'),
    'page callback' => 'say_report_details',
    'type' => MENU_CALLBACK,);

 return $items;
}

function say_report_details($values = array()) {
  $form = drupal_get_form("report_details_form");
  //$output = theme("report_page", $form, $output);
  return $form;
}

function report_details_form() {
 $form["search"] = array(
 '#type' => 'fieldset',
 '#title' => t('Search params'),
 '#collapsible' => FALSE,
 '#tree' => TRUE,
 );

 for ($i = 1; $i < 32; $i++) {
  $days_opt[$i] = $i;
 }
 for ($i = 1; $i < 13; $i++) {
  $month_opt[$i] = $i;
 }
 for ($i = 2008; $i < date("Y") + 3; $i++) {
  $year_opt[$i] = $i;
 }

 $form["search"]["from_day"] = array(
  '#type' => 'select',
  '#title' => 'Date from',
  '#options' => $days_opt,
  '#default_value' => (($_GET['from_day'] == "") ? date("d") : $_GET['from_day'])
 );
 $form["search"]["from_month"] = array(
  '#type' => 'select',
  '#title' => ' ',
  '#options' => $month_opt,
  '#default_value' => (($_GET['from_month'] == "") ? date("m") : $_GET['from_month'])
 );
 $form["search"]["from_year"] = array(
  '#type' => 'select',
  '#title' => ' ',
  '#options' => $year_opt,
  '#default_value' => (($_GET['from_year'] == "") ? date("Y") : $_GET['from_year'])
 );

 $form["search"]["to_day"] = array(
  '#type' => 'select',
  '#title' => 'Date to',
  '#options' => $days_opt,
  '#default_value' => (($_GET['to_day'] == "") ? date("d") : $_GET['to_day'])
 );
 $form["search"]["to_month"] = array(
  '#type' => 'select',
  '#title' => ' ',
  '#options' => $month_opt,
  '#default_value' => (($_GET['to_month'] == "") ? date("m") : $_GET['to_month'])
 );
 $form["search"]["to_year"] = array(
  '#type' => 'select',
  '#title' => ' ',
  '#options' => $year_opt,
  '#default_value' => (($_GET['to_year'] == "") ? date("Y") : $_GET['to_year'])
 );

 $result = db_query('SELECT something in the database');

 $strs = array("all" => "All");

 foreach ($result as $store) {
   $strs[$store->tid] = $store->name;
 }

 $form["search"]["store"] = array(
  '#type' => 'select',
  '#title' => 'Stores',
  '#options' => $strs,
  '#default_value' => $_GET['store']
 );

 $form["submit"] = array("#type" => "submit", "#value" => "Show report");

 return $form;
}

function report_details_form_submit($form_id, $form_values) {
  $query = "";
// This next line is the one I am having an issue with right now.$form_values is empty
  foreach ($form_values['search'] as $key => $value) {
     $query .= "&". $key ."=". $value;
  }

 return array('admin/reporting/report_details', $query);
}

```

The code throws an error at last "foreach" as $form\_values is empty for some reason.Thank you!!

# Answer
> 1 votes
By default Drupal form sends values using post method. If you are looking to recieve values in $\_GET you will have to define `#method` attribute of your form to `get`.

```
$form['#method'] = 'get';

```

# Answer
> 0 votes
Your code is not correct in many points, but the main reason you are not getting the values you are expecting is that the code to redirect the form is wrong, for Drupal 6/7.

The following code works.

```
function report_details_form_submit($form, &$form_state) {
  $form_state['redirect'] = array($_GET['q'], 'query' => $form_state['values']);
}

```

This code is similar to the one executed by search\_form\_submit(); the difference is that `search_form_submit()` add the search values to the path, separating them with a slash.

```
 $keys = $form_state['values']['processed_keys'];
  if ($keys == '') {
    form_set_error('keys', t('Please enter some keywords.'));
    // Fall through to the form redirect.
  }

  $form_state['redirect'] = $form_state['action'] . '/' . $keys;

```

There are other things that needs to be changed, such as:

* hook\_menu() doesn't get any parameter, in Drupal 7.
* There is no need to use a function that calls `drupal_get_form()` as page callback. Just use code similar to the following one.

```
function my_menu($may_cache) {
  $items = array();

  $items['admin/reporting/report_details'] = array(
    'title' => 'Report: User details by stores',
    'access arguments' => array('access content'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('report_details_form'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

```
* Functions defined from a module should be prefixed with its short name. If "my" is the short name of your module, then every function it defines it should have its name starting with `my_`, or `_my_` (if the function is private).
* You should verify the values are set, before to using them. Module code is supposed not to throw any warning. I would rather use the following code.

```
$form["search"]["from_month"] = array(
  '#type' => 'select',
  '#title' => ' ',
  '#options' => $month_opt,
  '#default_value' => empty($_GET['from_month']) ? date("m") : $_GET['from_month'])

```

);

Considering that (since Drupal 6) a form builder receives two parameters (`$form`, `&$form_state`), I would rather write the code as follows.

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

  $items['admin/reporting/report_details'] = array(
    'title' => 'Report: User details by stores',
    'access arguments' => array('access content'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('my_report_details_form'),
    'type' => MENU_CALLBACK,
  );

 return $items;
}

function my_report_details_form($form, $form_state) {
  $form["search"] = array(
    '#type' => 'fieldset',
    '#title' => t('Search parameters'),
    '#collapsible' => FALSE,
  );

  $from_date = array(
    'day' => isset($form_state['my_report']['from']) ? $form_state['my_report']['from']['day'] : date('d'),
    'month' => isset($form_state['my_report']['from']) ? $form_state['my_report']['from']['month'] : date('m'),
    'year' => isset($form_state['my_report']['from']) ? $form_state['my_report']['from']['year'] : date('Y'),
  );

  $form["search"]["from"] = array(
   '#type' => 'date',
   '#title' => t('From'),
   '#default_value' => $from_date,
  );

  $to_date = array(
    'day' => isset($form_state['my_report']['from']) ? $form_state['my_report']['to']['day'] : date('d'),
    'month' => isset($form_state['my_report']['from']) ? $form_state['my_report']['to']['month'] : date('m'),
    'year' => isset($form_state['my_report']['from']) ? $form_state['my_report']['to']['year'] : date('Y'),
  );

  $form["search"]["to_day"] = array(
    '#type' => 'date',
    '#title' => t('To'),
    '#default_value' => $to_date,
  );

  $options = array("all" => "All");
  $result = db_query(/* */);

  foreach ($result as $store) {
    $options[$store->tid] = $store->name;
  }

  $form["search"]["store"] = array(
    '#type' => 'select',
    '#title' => t('Stores'),
    '#options' => $options,
    '#default_value' => isset($form_state['my_report']['store']) ? $form_state['my_report']['store'] : 'all',
  );

  $form["submit"] = array("#type" => "submit", "#value" => "Show report");

  if (isset($form_state['my_report']['result'])) {
    $headers = array(/* The headers to use for the table */);

    $form['result'] = array(
      '#theme' => 'table',
      '#header' => $headers,
      '#rows' => $form_state['my_report']['result'],
      '#empty' => t('There are no reports found in the database'),
    );
  }

  return $form;
}

function my_report_details_form_submit($form, &$form_state) {
  $form_state['my_report']['from'] = $form_state['values']['from'];
  $form_state['my_report']['to'] = $form_state['values']['to'];
  $form_state['my_report']['store'] = $form_state['values']['store'];

  // Search the reports, and populate $form_state['my_report']['result'].

  $form_state['rebuild'] = TRUE;
}

```

In this way, there would not be any need to populate `$_GET` with the data submitted in the form.

See theme\_table() for the value to use as `#rows`.

### Reference

---
Tags: forms
---


# Question
Title: Cancel user creation from hook_user_presave
I created a module that links to Taleo (Talent Management system). When creating a Drupal user, automatically a Taleo Candidate is made.

This works like a charm. But sometimes Taleo answers with an error (example: a candidate with email address info@example.com already exists)

Is there an easy way to cancel the creation of the user from within 'hook\_user\_presave'? Now the error messages is showed, but the Drupal user is made anyway.

```
function taleo_user_presave(&$edit, $account, $category) {
    global $client_taleo;
    $session = _taleo_login();
    $error = 0;

    if(!isset($edit['field_taleo_id'][LANGUAGE_NONE][0]['value'])) {
        // NOT LINKED TO TALEO

        $params = array(
            'in0' => $session,
            'in1' => array('id' => '', 'rank' => '', 'status' => '0-Available',
            'firstName'     => @$edit['field_first_name'][LANGUAGE_NONE][0]['value'],
            'lastName'      => @$edit['field_last_name'][LANGUAGE_NONE][0]['value'],
            'phone'         => @$edit['field_phone_number'][LANGUAGE_NONE][0]['value'],
            'zipCode'       => @$edit['field_zip_code'][LANGUAGE_NONE][0]['value'],
            'country'       => @$edit['field_country'][LANGUAGE_NONE][0]['value'],
            'textResume'    => @$edit['field_text_resume'][LANGUAGE_NONE][0]['value'],
            'lastUpdated'   => date('c'),
            'email'             => @$edit['mail'])
        );

        try{
            $edit['field_taleo_id'][LANGUAGE_NONE][0]['value'] = $client_taleo->__call('createCandidate', $params);
        } catch (SoapFault $fault) {
            $error = 1;
            $error_message = check_plain("ERROR: " . $fault->faultcode . "-" . $fault->faultstring);
            drupal_set_message($error_message);
            watchdog('taleo', $error_message, array(), WATCHDOG_ERROR);
            return array();
        }

    }

```

# Answer
> 1 votes
I think `hook_validate()` will be a better place to check if taleo accepts new user data or not. If it didnt set an error using `form_set_error()` for Email Field.

I am not sure if `presave()` is the right hook to stop creation of user.

> A user account is about to be created or updated.
>
> This hook is primarily intended for modules that want to store properties in the serialized {users}.data column, which is automatically loaded whenever a user account object is loaded, modules may add to $edit\['data'\] in order to have their data serialized on save.

# Answer
> 4 votes
The equivalent of hook\_user('validate') used in Drupal 6 doesn't exist in Drupal 7. For that, you need to add a form validation handler to user\_register\_form(), and use form\_set\_error() when Taleo returns an error.

# Answer
> 0 votes
This is the working code to check if Taleo (or other sources) gave an error, if so: a form error will be shown.

```
function taleo_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'user_register_form' || $form_id == 'user_profile_form'){
        $form['#validate'][] = 'taleo_form_validate';
        return $form;
    }
}

function taleo_form_validate($form, &$form_state) {
    // If previous validation didn't pass, return
    if (form_get_errors()) return;

    global $client_taleo, $user, $taleo_id;

    $session = _taleo_login();
    $user = user_load($user->uid);

    // NOT LINKED TO TALEO
    if(strlen($user->field_taleo_id[LANGUAGE_NONE][0]['value']) == 0) {
        $params = array(
            'in0' => $session,
            'in1' => array('id' => '', 'rank' => '', 'status' => '0-Available',
            'firstName'     => @$form_state['values']['field_first_name'][LANGUAGE_NONE][0]['value'],
            'lastName'      => @$form_state['values']['field_last_name'][LANGUAGE_NONE][0]['value'],
            'phone'         => @$form_state['values']['field_phone_number'][LANGUAGE_NONE][0]['value'],
            'zipCode'       => @$form_state['values']['field_zip_code'][LANGUAGE_NONE][0]['value'],
            'country'       => @$form_state['values']['field_country'][LANGUAGE_NONE][0]['value'],
            'textResume'    => @$form_state['values']['field_text_resume'][LANGUAGE_NONE][0]['value'],
            'lastUpdated'   => date('c'),
            'email'         => @$form_state['values']['mail'])
        );

        try{
            $taleo_id = $client_taleo->__call('createCandidate', $params);
        } catch (SoapFault $fault) {
            form_set_error('', check_plain($fault->faultstring));
        }
    }
}

```

---
Tags: 7, users
---


title: Is there a module for Image Sitemaps?

text:
# Question
Title: Is there a module for Image Sitemaps?
I have been looking to expose the images hosted on my site to Google Images search. I was wondering is there is a Drupal 6 module to do that? I am on Pressflow 6.

I can see such modules available for Drupal 7 (see below). http://drupal.org/project/google\_image\_sitemap AND http://drupal.org/node/451234

# Answer
The module http://drupal.org/project/google\_image\_sitemap has a d6 version but it was released after the d7 version :)
> 0 votes

---
Tags: 6, media, xml-sitemap
---


# Question
Title: Hide some of the fields of user profile of profile2 module
I am using Drupal 7 profile2 module for creating user profile and Organic group module for group managemnet.

I have **user status** field in user profile, and there are two options(radio button) for visibility of profile field like **1.** Visible in Group **2.** Invisible.

**Visible in Group** is selected then any group member can see the **user status**

**Invisible** then no one can see the **user status** field

Now I want to know that is there any way to unset the profile field during viewing. Is any hook calling during user view event ?

I have also the code that checks whether user being viewed and logged in user are member of same group or not

# Answer
> 1 votes
`hook_entity_view` can be used all core and most contrib entities and the more specific `hook_user_view` can be used when the user account is used - this is, however, not the same as the user profile itself.

You should note that this wont effect fields and entities displayed by views.

---
Tags: users, organic-groups
---


title: Assign the node to a user

text:
# Question
Title: Assign the node to a user
I'm using Drupal 7 and **workflow** module for Article content type. There are two roles author, editor. There can be as many number of authors as how many we want, but there are only four editors. Workflow states: Review, Back to Author and Publish.

Worflow offers very good publishing process throught it's rules and actions. Authors create articles, and change the workflow state to Review and save it. Editors have two choices either to publish the content or return it back to the author of the article. Works cool!

But what I want is to make the authors to choose one of the editors(there 4 of them), that editor is going to be assigned to this article, and only he/she can edit this article while the worflow state changes into Review. Currently any user with **Editor** role can edit the articles with **Review** state.

# Answer
If the Rules module is used on your site (as you wrote in comment), then create a rule for *Node editing*.

1. Condition: Check that assigned Editor field isn't equal to current user
2. Action: Show access denied or just redirect to some page
> 2 votes

# Answer
I use workbench, which accomplishes the same thing as workflow. There is a module in the workbench collection called Workbench access that I use to send content to specific editors in the workflow. I use it for my school newspaper so that writers moderate content to the editors of their specific section (i.e. news, sports, arts, lifestyle, etc.) then the Editors send the content to me for final approval and publication on the site. Hope this helps!
> 3 votes

---
Tags: workflows
---


# Question
Title: Filtering a views result two month ago from now
I building a view with a date filter. How do I filter the nodes to the ones that have been created between the date I select and two months earlier?

I tried with a relative date value, but I do not know how I should set it correctly.

# Answer
Install and enable the *Date Views* module which is part of the Date project. In your view, expose the date field, and select the *Between* operator with two dates (*Start date* and *End date*).

>
> 1 votes

---
Tags: 7, views
---


title: Remove links in admin content list form

text:
# Question
Title: Remove links in admin content list form
In the admin content form (admin/content), I am trying to remove links to content page on some content types in a custom module with the following code but I can't get it working.

```
/**
* Implements hook_form_node_admin_content_alter()
 */
function MYMODULE_veilleur_form_node_admin_content_alter(&$form, &$form_state, $form_id) {
    foreach ($form['admin']['nodes']['#options'] as $option){
      if($option['type'] == "Document"){
        $option['title']['data']['#type'] = "text";
        unset($option['title']['data']['#href']);
      }
    }
}

```

With this code, I still have the links in the content title. Any idea?

# Answer
> 1 votes
Sorry, it is my fault, I forgot to use the "&" to pass the reference variable in the loop. Here is the final code :

```
/**
* Implements hook_form_node_admin_content_alter()
 */
function MYMODULE_veilleur_form_node_admin_content_alter(&$form, &$form_state, $form_id) {
    foreach ($form['admin']['nodes']['#options'] as &$option){
      if($option['type'] == "Document"){
        $option['title'] = $option['title']['data']['#title'];
      }
    }
}

```

# Answer
> 1 votes
Below code should work too...

```
function YOURMODULE_form_node_admin_content_alter(&$form, &$form_state, $form_id) {
  foreach ($form['admin']['nodes']['#options'] as $key => $value){
    if($form['admin']['nodes']['#options'][$key]['type'] == "Document"){
      $form['admin']['nodes']['#options'][$key]['title']['data']['#type'] = "item";
      unset($form['admin']['nodes']['#options'][$key]['title']['data']['#href']);
    }
  }
}

```

---
Tags: 7, forms
---


# Question
Title: Drupal 7 : I want "Access Denied on Node but Title listing in view"
I used content access for restricting content of particular content type.

Anonymous user can't see Node and get Access Denied But want to listing of those restricted node's title to Anonymous user. I searched and found premium content module but not found way to use it.

What I want,When Anonymous go: On node == Access Denied,
On View (listing Title) == can see Title.

kindly help me for premium content **OR any other Solution**.

# Answer
Using view you can achieve this functionality,

In you view go to Query settings in others tab, In the popup select **Disable SQL rewriting**

This is what views says about this option

```
Disabling SQL rewriting will disable node_access checks as well as other
modules that implement hook_query_alter().

```

Then Content access will not able to alter this query, so your users who don't have permission to view the particular content type also can see the views results

While When they are trying to access the node, on that time content access will not allow them to see that node.

Hope this helps.
> 1 votes

---
Tags: users
---


# Question
Title: Display custom text if there is no comments
I want to display custom text on a node if there is no comments yet. I think i should check for comments count in preprocess\_node, and somehow add the text below Comments title.

```
function MYTHEME_preprocess_node(&$variables, $hook) {
  if($variables['comment_count'] === '0') {
     //somehow i need to display text - There is not comments yet
  }
}

```

How can achieve this? here is an example of how it should looks like:

**EDIT:** Also i have found better solution, may be useful for someone. (using Zen theme - aka STARTERKIT modified) I have added `comments-wrapper.tpl.php`

And in a `template.php` added preprocess function of this wrapper

```
function MYTHEME_preprocess_comments_wrapper(&$variables) {
    $variables['MYTHEME_comment_title'] = t('Comments');
      $commented_node = $variables['node'];

      if(!empty($commented_node) && is_object($commented_node)){
        $comment_count = 0;
        if(isset($commented_node->comment_count)){
          $comment_count = $commented_node->comment_count;
        }
        $variables['MYTHEME_comment_title'] = format_plural($comment_count, '1 comment', '@count comments');
         if($comment_count == 0) {
            $variables['MYTHEME_comment_title'] = t('Comments');
            $variables['empty_comments'] = t('There is no comments yet');
     }
}

```

And in a `comments-wrapper.tpl.php` i have printed out `$empty_comments` variable

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

```

# Answer
> 4 votes
In your node.tpl.php you could check the $comment\_count variable to see if there are comments. If so, render the comments, if not display your alternet text.

Example:

```
<?php if ($comment_count > 0 ): ?>
  <?php print render($content['comments']); ?>
<?php else: ?>
        <strong> 0 comments yet</strong>
        <?php echo l('Be the first','commentpath'); ?>
<?php endif; ?>

```

---
Tags: comments, theming
---


title: Search results - Show custom fields

text:
# Question
Title: Search results - Show custom fields
Is it possible to change the output created with the Search module? I want to show custom fields, and I want to hide the description, user and date...

# Answer
> 7 votes
You have two options:

1. You can use Display Suite module. A sub-module Display Suite Search allows you to change the way nodes are displayed for search results.
2. You can use `template_preprocess_search_result()` together with a copy of `modules/search/search-result.tpl.php` in your theme. Read thoroughly the comments in the `search-result.tpl.php` as they will help you understand what is going on and what is available to you.
You can define variables this way: `$variables['your_value'] = $variables['result']['node']->field_sample[LANGUAGE_NONE][0]['value'];` and use it in the .tpl file like this: `print $your_value;`.

---
Tags: 7, search
---


# Question
Title: How can I add pager to the comments of advanced forum in drupal 7?
I use the drupal 7 core forum with advanced forum module.

This works perfectly except the forum topic page show only post comments what number is defined on the content type, and no pager on the comments, therefore the users can't jump to the next few comments.

My question: how can I add pager (first, prev, next, last, etc.) to the advanced forum post comments?

I didn't found any solution until yet.

# Answer
> -2 votes
In your style directory, you should have a \*.topic-header.tpl.php file. Make sure the following is where you want the paging to display:

```
<?php print($pager); ?>

```

Then, in \*sites/all/modules/advanced\_forum/includes/theme.inc\*

Approximately line 446:

```
  pager_default_initialize($variables['node']->comment_count, variable_get('comment_default_per_page_forum'));
  $variables['pager'] = theme('pager');

```

---
Tags: forms, comments, paging
---


# Question
Title: Submitting a form rebuilds (expensive) page upon submit
I have a simple menu callback that draws a page with a form on it. The page callback does a very expensive operation (requests a bunch of data from an external API).

```
function test_menu() {
  $items = array();
  $items['test'] = array(
    'title' => 'Test',
    'page callback' => 'test_page_handler',
    'access callback' => TRUE,
  );
  return $items;
}

function test_page_handler() {
  $data = very_expensive_data_operation();
  $output = drupal_get_form('test_simple_form', $data);
  return $output;
}

function test_simple_form(&$form_state, $data) {
  $form['create'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

function test_simple_form_submit(&$form, &$form_state) {
  // do something
}

```

The problem I am seeing is that when the form is submitted, Drupal will re-execute the page callback in the background, resulting in the very\_expensive\_data\_operation() running again.

There are probably lots of great reasons for Drupal to do this, but how can I change my app so that the very\_expensive\_data\_operation() doesn't have to run again when submitting the form (after all, that's why I'm passing $data to the form, rather than having the form run it directly.)

One workaround I can think of is to toss $data into a cache table, but it feels like I'm missing something that available to me in the Drupal+FAPI api.

# Answer
> 1 votes
You can also try using drupal\_static

> Provides central static variable storage.
>
> All functions requiring a static variable to persist or cache data within a single page request are encouraged to use this function unless it is absolutely certain that the static variable will not need to be reset during the page request. By centralizing static variable storage through this function, other functions can rely on a consistent API for resetting any other function's static variables.

```
function test_menu() {
  $items = array();
  $items['test'] = array(
    'title' => 'Test',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('test_simple_form'),
    'access callback' => TRUE,
  );
  return $items;
}

function expensive_data() {
  $data = &drupal_static(__FUNCTION__);
  if (!isset($data)) {
    $data = very_expensive_data_operation();
  }
  return $data;
}

function test_simple_form(&$form_state) {
  $data = expensive_data();
  $form['create'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

function test_simple_form_submit(&$form, &$form_state) {
  // do something
}

```

You might notice that the static variable technique only stores data for the duration of a single page load. For even better performance try this

```
function expensive_data() {
  $data = &drupal_static(__FUNCTION__);
  if (!isset($data)) {
    if ($cache = cache_get('my_module_data')) {
      $my_data = $cache->data;
    }
    else {
      $data = very_expensive_data_operation();
      cache_set('my_module_data', $my_data, 'cache');
    }

  }
  return $data;
}

```

If you want to refresh your cache from time to time you can try

```
cache_set('my_module_data', $my_data, 'cache', time() + 360);

```

OR you can manually rebuild your cache using

```
cache_clear_all('my_module', 'cache', TRUE);

```

# Answer
> 0 votes
I think the best place to run your expensive function is in the form itself, even though you've mentioned you're currently avoiding that.

As it stands, your page callback has no link to the form that's currently being submitted; there are ways you could get it from the `cache_form` table, but it's a bit messy.

Instead, I'd advise saving the data to a variable in the form, and checking to see if that variable has been submitted in the `$form_state` array. You'll also need to flag the form to rebuilt in the submit handler:

```
function test_simple_form(&$form_state) {
  // If the form has already been biult, and we already have the data, don't load it again.
  if (isset($form_state['values']['expensive_data'])) {
    $data = $form_state['values']['expensive_data'];
  }
  else {
    // Otherwise get the data from source.
    $data = my_expensive_function();
  }

  // Store the data
  $form['expensive_data'] = array(
    '#type' => 'value',
    '#value' => $data
  );

  // ...

  return $form;
}

function test_simple_form_submit(&$form, &$form_state) {
  $form_state['rebuild'] = TRUE;
}

```

In your submit handler you'll have access to `$form_state['values']['expensive_data']`, which will contain the results of the function call.

This method has the added benefit of caching the data if the form validation fails, not just when it's submitted successfully.

Judging from the function signature you're using for the form I'm guessing you have a Drupal 6 site, although the above method will work equally well for a Drupal 7 site (the function signature would just need to change).

---
Tags: forms
---


# Question
Title: How can I replace an image using a Form API?
I have a form that works great for adding fields, including and image, to a node and saving it.

I want to allow users to edit their fields and change the data, including their image. I figure there is some way to retrieve and display the current image and then allow the user to upload and save/replace the image with a new one. I can't figure out how to show a preview of the existing image on the Edit form. I assume somewhere I should use File\_Exists\_Replace, but the rest is an overwhelming mystery.

Here is the code I use for the original form:

```
  $form['logo'] = array(
  '#title' => t('Image'),
  '#type' => 'managed_file',
  '#description' => t('Only image files will be allowed.'),
  '#default_value' => variable_get('logo', ''),
  '#upload_location' => 'public://misc/media',
  '#upload_validators'  => array(
    'file_validate_extensions' => array('png gif jpg jpeg'),
    'file_validate_size' => array(2*1024*1024),
    )
  );

```

And the submit function:

```
    // Load the file via file.fid.
    $file = file_load($form_state['values']['logo']);
    // Change status to permanent.
    $file->status = FILE_STATUS_PERMANENT;
    // Save.
    file_save($file);
    // Record that the module (in this example, cformtwo module) is using the file.
    file_usage_add($file, 'cformtwo', 'node', 1);
...
    node_submit($node);
    node_save($node);

```

I have spent days trying to figure out how to do this.

# Answer
Your 'logo' variable will be a file id, referring to a row in the `file_managed` table, so you can use the `file_load()` function to load the file object, create an image with the details, and attach it to your form field.

This is a (very) basic example:

```
$logo = variable_get('logo');

$image = '';
if ($logo) {
  // Load the file object
  $file = file_load($logo);

  // Get a thumbnail of the image (just an example)
  $args = array('style_name' => 'thumbnail', 'path' => $file->uri, 'alt' => 'Alt text');
  $image = theme('image_style', $args);
}

// Prepend it to your field
$form['logo'] = array(
  '#title' => t('Image'),
  '#type' => 'managed_file',
  '#description' => t('Only image files will be allowed.'),
  '#default_value' => $logo,
  '#upload_location' => 'public://misc/media',
  '#upload_validators'  => array(
    'file_validate_extensions' => array('png gif jpg jpeg'),
    'file_validate_size' => array(2*1024*1024),
  ),
  '#prefix' => $image
);

```
> 1 votes

---
Tags: forms, media, files
---


title: improve drupal 7 multisite performance

text:
# Question
Title: improve drupal 7 multisite performance
I think this has to be performed when the project is starting and not when the project is running, but, I don't decide that. I'm only the developer. I read a lot about performance in Drupal 7, and I saw modules like (Boost, Devel...) but I'm not very experienced with this.

Devel isn't working for my project (when I enter here admin/config/development/devel the page only stay await for a couple of seconds and return a problem with the server \[The connection was reset\] and nothing happen). AS of yet, I have not tried Boost.

I want to make performance improvements not only for Drupal way but also for Apache+MySQL. I read something and some guys talked about jMeter to make some stress test and other thing. buy, I want to know what you think, what you use and your experience dealing with performance.

(One answer will be: CACHE, but I'm looking something more than a cache).

So much thanks guys!

# Answer
# Drupal

When it comes to multiple sites, you should consider what would be effects of managing multiple sites. Having a separate MySQL database for each Drupal site would means that your could do the following without disturbing others

* take one Drupal Site offline
* load new content into one site
* alter contents of one site

Consequences

* Upgrading Drupal content for one site may possibly affect others that are still running previous versions
* Doing an Upgrade requires a full shutdown of all sites
* Features for improving performance of one site (such as Boost Cache) may hurt performance for other sites

# MySQL

When it comes to MySQL, you will have to consider one of two things

* Using MyISAM Storage Engine
* Using InnoDB Storage Engine

MyISAM and InnoDB have strengths and weaknesses.

* MyISAM only caches Index Pages
* InnoDB caches data and index pages
* InnoDB can also be configured to have InnoDB bypass OS caching
* InnoDB can be configured to access multiple cores/CPUs
* There are some instances where MyISAM can be as fast or faster than InnoDB
* As of MySQL 5.5, only MyISAM supports FULLTEXT indexing. MySQL 5.6 will introduce FULLTEXT indexing to InnoDB

# Please see my past posts about other Pros and Cons:
> 1 votes

---
Tags: 7, performance, multi-sites
---


# Question
Title: Trying to integrate website theme to work with drupal
Well, I wanted to switch over from single file Site, to Drupal, to manage the site easier. However, I wanted to use the theme I made, So i started trying to make it drupal comatiable, So it would work there, I got some working, But it does not Show the pages, post, but title and other things. Anyways, I am a newbie to theming in drupal. I used some help using Bratic theme, and some from a Website that had the variables that can be used. Code:

```
<!DOCTYPE html>
<!-- Theme created by Tek Owner of gameTek.me and tf2tek.com -->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <title><?php print $htitle ?></title>
  <?php print $head ?>
  <?php print $styles ?>
  <?php print $scripts ?>
  <script type="text/javascript"><?php /* Needed to avoid Flash of Unstyle Content in IE */ ?> </script>

     <script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-32116318-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
<script type="text/JavaScript" src="jquery.js"></script>
<script type="text/JavaScript" src="main.js"></script>
     </head>
  <body>
<div id="Secret"></div>
        <div id="Container" >
        <div id="Left"></div>
        <div id="Right"></div>
        <div id="gLogo"></div>
        <div id="Spy"></div>
        <div id="Demo"></div>

        <div id="Top">
        <?php print $primary_links; ?>
         </div>

         <div id="Header">
          <h1><?php print $title; ?></h1>
         </div>
         <div id="Content">
            <!-- Content or other goes here -->
                <?php print $content; ?>
         </div>

          <p>
                    <script type="text/javascript"><!--
google_ad_client = "ca-pub-4060951217224891";
/* Footer - gtek */
google_ad_slot = "9898201888";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
          </p>
         </div>
         <div id="Footer">
           <p><?php print $footer_message; ?></p>
         </div>
        </div>
    </body>
</html>

```

Demo: 84.234.160.79/drupal-7.15/

CSS:

```
body {

               background-image:url(Media/Background.jpg);

           }

            #Container {

                width:100%;

                height:100%;

            }

            #Left {
            position:absolute;
            height:100%;
            width:150px;
            left:-1px;
            background-image:url(Media/SideLeft.png);
            }
            #Right {
            position:absolute;
            height:100%;
            width:150px;
            right:-1px;
            background-image:url(Media/SideRight.png);
            }
            #gLogo {
            position:absolute;
            height:762px;
            width:197px;
            top:40px;
            left:10px;
            background-image:url(Media/Gtek90.png);
            }
            #Demo {
            display:none;
            position:absolute;
            height:414px;
            width:181px;
            top:110px;
            left:0px;
            background-image:url(Media/Demo.png);
            }
            #Spy {
            position:absolute;
            height:245px;
            width:270px;
            right:-25px;
            top:20px;
            background-image:url(Media/Spy.png);
            }
           #Top {

                position:relative;

                height:50px;

                text-align:center;

                vertical-align: middle;

                margin: 0px auto 0 auto;

                z-index:0;

                background-image:url(Media/Nav.png);
                padding:0px;

                margin-top:-16px;

           }
           #Button {
           position:relative;
           top:11px;
           }

            #Header {

                position:relative;

                min-width:720px;
                max-width:80%;
                height:40px;

                text-align:center;

                margin: 0px auto 0 auto;

                z-index:0;

                background-image:url(Media/Top.png);
                padding:0px;
                color:#BF0000;

            }
               #Nav {

                position:relative;

                min-width:720px;
                max-width:80%;
                height:40px;

                text-align:center;

                margin: 0px auto 0 auto;

                z-index:0;

                background-image:url(Media/Nav.png);
                padding:0px;

            }

            #Content {

                position:relative;

                min-width:720px;
                max-width:80%;

                text-align:center;

                margin: 0px auto 0 auto;

                z-index:0;

                background-image:url(Media/Content.png);

                padding:0px;

               margin-top:-16px;
               color:#FFA500;
               border-left:1px solid #000;
               border-right:1px solid #000;
            }

            #Footer {

                position:relative;

                min-width:720px;
                max-width:80%;

                height:26px;

                text-align:center;

                margin: 0px auto 0 auto;

                z-index:0;

                background-image:url(Media/Bottom.png);

                padding:0px;

               margin-top:-16px;

               border-top:1px solid #000;

               line-height:1px;

            }

```

# Answer
> 0 votes
You are using D7 so instead of printing the `$content` variable, you should do it this way:

```
print render($page['content']);

```

Few other things:

* D6 and D7 have some differences in outputting the variables. Make sure you are following up tutorials/reading articles about D7.
* You should not include the scripts/styles directly in the template. Place them in theme's .info file and Drupal will do that for you. This way Drupal can compress them if your performance settings are saved that way.
* `$main_menu` should be  `$main_menu, 'attributes' => array('id' => 'main-menu', 'class' => array('links', 'inline', 'clearfix')), 'heading' => t('Main menu'))); ?>`

See this link to get started on theming with Drupal:

Check existing themes in more details (Bartik for example) and see how they are made and structured.

Hope this helps.

# Answer
> 0 votes
Having a glance at your demo site, I suggest you to use a per-existing theme which has lots of regions that resembles your web layout. Instead of coding your theme from scratch, you can leverage Drupal's block system to place items in the required regions and add custom css styling. I suggest you Corolla Theme, which has a lot of regions that can be used for your website and it also supports mobile devices.

---
Tags: theming
---


title: Group content types together

text:
# Question
Title: Group content types together
I have a view (table style) filtered three content types, added fields i want, but each type has a date field.

I needed to group all's nodes by date so i added a `Global: custom text` with replacement patterns i get what i need (one date field to three content types).

I grouped my view by this field but the problem is each content type has own table.

how can i group those three content types together in one table for every date value?

# Answer
OK, I think I'm noticing this difference: when I don't set a field to sort by, my content types seem to be in separate tables too.

But if I set the 'Sort Criteria' to a field that all of the content types have, like 'Post date', desc, then I get all the content types correctly incorporated into one table:

Anyway, hope this helps you!
> 1 votes

---
Tags: 7, views
---


# Question
Title: taxonomy name filter to get terms with special characters
I am getting my term description using `taxonomy_get_term_by_name()`.

I'm having problems with term names like "barnes & noble" and "Café"; I guess it must have something to do with the special characters. How can I filter my taxonomy name input the best way to get back term results?

I'm using the function in a views-view-list.tpl.php template, where `$title` is outputting the taxonomy; then I use `$title` with the following code.

```
$terms = taxonomy_get_term_by_name($title, 'places');

```

`$title` seems to be stripped from all kind of htmltags - its plain text.

# Answer
It was only the & charter there was making problems. This was the solution:

```
$terms = taxonomy_get_term_by_name(str_replace('&', '&', $title), 'places');

```
> 0 votes

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


# Question
Title: how to get the value from a field in hook_node_load($nodes, types)
I have a **hook\_node\_load()**, when I dsm($nodes), it returns an array, I need to get the value from field\_tt\_status (contains 1 or 0). I know I have to do something like

```
$status = $nodes['field_tt_status']['und']['0']['value'];

```

but it that doesnt work. Can someone help me?

# Answer
The `$nodes` variable is an array of node objects. You either need to loop through the array and extract the field values, or get the first item off the array and use that. For example:

```
foreach ($nodes as $node) {
  if ($node->type == 'content_type') {
    $field_items = field_get_items('node', $node, 'field_tt_status');
    $status = $field_items[0]['value'];
  }
}

```
> 3 votes

---
Tags: 7, nodes
---


# Question
Title: Why did upgrading Drupal 6 cause a huge increase in database traffic?
Last week I inherited a several-year old messy implementation of a mid-sized Drupal site. Short version: 1 NFS/mysql server, 3 Apache servers. Everything was overloaded and crawling along. The first thing I did was add a memcached server to the mix which cut the network traffic to the mysql server a lot. Next I got the code all running on local file systems using VCS and only used the NFS mounts for the *files* directory. Again, network traffic went down.

The CMS was actually an extended install of Pressflow dated at v6.20. I had the bright idea to update this to 6.26, which I did using the Pressflow 6.26 package. Other than a few conflicts with other modules that had to be resolved, this went pretty smoothly. The site works fine.

However, looking at the interface stats on the mysql server, since the upgrade the ethernet traffic is about 100% more to handle the same site load. It's been three days now and the pattern is the same. **The network traffic hugely increased corresponding to the upgrade to 6.26.** The metric I'm using here is bytes transferred in and out of the DB server. Unfortunately I don't have stats about number of queries run.

What changed between 6.20 and 6.26 that would cause this and is there anything I can do to mitigate it?

# Answer
> 3 votes
Apart from the NewRelic suggestion, which I put in a comment, consider reproducing this issue in a second environment, I assume you do have a staging/testing environment of the site, or at least a local installation. If not, you should get one ;)

Then you can install the devel.module, enable query logging and/or xhprof profiling. Then you can actually switch between the old version and the new one and compare the difference within Drupal. Devel's query logging will tell you exactly which queries are executed and how long they took.

# Answer
> 3 votes
We had kind of the same experience some days ago when upgrading from latest Drupal 6.26 to Pressflow 6.26. The migration was done within a few hours and everything started smoothly but when the traffic came in we saw a 20% higher CPU load on average and significantly higher activity on the database server. This was quite surprising and we are still investigating the reasons. We already run memcache, XCache, CDN to reduce Apache and DB workload. After analysing slow-queries (from the MySQL slow query log) we found some ankers to start some optimization work but still it does not explain the increase in CPU and DB traffic for me. Additionally we will head towards Varnish to get requests away from the Apache.

# Answer
> 2 votes
Unfortunately, I think you have too many variables to really point to what could be going on. You upgraded core and also updated contrib modules(?), so the issue could really be with both. I also think that profiling based on net traffic is open to too many errors.

It also sounds like you have the files directory mounted on the same machine that machine that runs MySQL? You also are measuring your load based on network IF stats, which would be both MySQL traffic and NFS traffic? If this is the case, then your problem may not really be on the MySQL side, but rather with the NFS side.

Personally, this is what I would do.

Disable memcached, run your Drupal site for a few days, and then run mysqltuner. Tweak your my.ini as needed. This will get your MySQL instance at a good starting point. Then you can re-enable memcached.

Go through your Drupal settings and double check all of the performance related ones. Make sure JS and CSS aggregation is on (could be a major source of network traffic to the files dir), and make sure your caching rules make sense for your organization.

Look at your Apache config and check your caching rules. Drupal has URL cachebusting, so there is no real reason to not have aggressive caching turned on. Look at the .htaccess for HTML5 Boilerplate for some ideas. Implementing these has has *drastic* improvements on Drupal sites for me. In your case they would reduce requests for images/JS/CSS which would decrease load on your server.

Then go through your files directory, and see what it is being used for. If you dumped image cache, then traffic could be from that and will level off when all of your image derivatives get rebuilt. It could be from backup/migrate files not being compressed now. Check the other things in files, too. And then figure out a way to get files off of NFS.

As for the Drupal/Pressflow side, I can't think of anything that would account for major DB load. If you do think this is the issue, then you need to go through the CHANGELOGs for both Drupal and Pressflow. However, I think that Pressflow was just tracking Drupal changes at that point.

---
Tags: database, 6
---