title: Course as a Product in Ubercart

text:
# Question
Title: Course as a Product in Ubercart
I'm trying to understand how course connects to product in ubercart.

There is a module called Course Ubercart, and I'm trying to create my courses as ubercart products with no luck.

Here's the description of the module:

```
Course ubercart 7.x-1.0-beta3   Supports Course as an Ubercart product and restricts enrollment to paid courses.
Requires: Course (enabled), Chaos tools (enabled), Universally Unique ID (enabled), Views (enabled), Views Bulk Operations (enabled), Entity API (enabled), Rules (enabled), Entity tokens (enabled), Order (enabled), Product (enabled), Image (enabled), File (enabled), Field (enabled), Field SQL storage (enabled), Store (enabled)

```

How am I supposed to use this? I have tried creating new products, looking to see if there is anything in the course content type UI for it, and I see absolutely nothing.

# Answer
> 1 votes
Just putting my comments in as answer...

https://drupal.org/node/2106647

How to make custom content type as product in ubercart drupal 7?

You have to create content type as product. Thanks

---
Tags: ubercart
---


title: Custom navigation menu bar

text:
# Question
Title: Custom navigation menu bar
I use the main menu as navigation bar, and I would like to obtain the following result: When the mouse is hovered on one navigation item, the sub menu should be shown as `<div>` under this item. I would like to be able to style the sub menu `<div>`s as well.

Shall I actually use the navigation menu or just the main menu?

I am using Drupal 7.

# Answer
It sounds to me like you are looking for something like Superfish or Nice Menus.

My personal preference is Superfish, as it has become pretty damn useful in recent updates. It's also responsive if that's a requirement, and support touchscreens quite nicely.

**EDIT**

Something I missed (possibly another personal preference) is that I find the CSS for Nice Menus an absolute NIGHTMARE in comparison with Superfish.
> 4 votes

# Answer
I depends on your theme. It is often useful to turn off the main menu in the theme appearance settings, and then using the block system to place the menu.

NiceMenus or Superfish give you the ability to modify the drop-downs. With NiceMenus you'll have to set the @media breakpoints yourself for different screen sizes. Superfish has these features built-in, which can save you a lot of responsive design-time.

Also, see the Menu Block module which has lots of menu placement options.
> 0 votes

---
Tags: routes, navigation
---


# Question
Title: sort comments descending programmatically
I want to sort all comment descending programmatically, I found this Comments sorted by oldest first but I dont want use those modules or views solution.
anybody know how can I sort comment descending programmatically?
I means comments in below node(contents) , first ideal is get comments related to node by query and set `orderby DESC` but everything show reversed in thread mode, **replies come above comment !!!**.

# Answer
> 0 votes
```
<?php
$query = db_select('comment') ->fields('comment', array('cid')) ->condition('nid', arg(1), '=');
$query->orderBy('created', 'DESC');
$result = $query->execute();
$cids = $result->fetchCol();
$comments=comment_load_multiple($cids);
foreach($comments as $comment)  {
  //do some stuff with the comment
}
?>

```

---
Tags: comments, theming
---


# Question
Title: How to use EntityFieldQuery with a simple text field?
I have a content type called `foo` and it has a textfield called `field_bar`. I have one that has a value set to `baz`.

I'd like to use the EntityFieldQuery object to find all `foo`s that have `field_bar` with the `baz` value.

```
$nodeQuery = new EntityFieldQuery();
  $nodeQuery->entityCondition('entity_type', 'node', '=')
    ->entityCondition('bundle', 'foo')
    ->fieldCondition('field_bar', 'value', '12345', '=');

```

The problem is that I get no results or error back. If I remove the fieldCondition, I get all `foo`s including the one I am looking for.

As the documentation is vague and only for experts, I googled a lot, but can't find any reason for my query not returning my node.

I also tried with

-\>fieldCondition('field\_bar', 'value', array('12345'), '=');

to see if that matters, but its the same. I `dd`-ed the `$nodeQuery` but can't see the executed SQL.

Is there anything special with textfields?

# Answer
From the canonical reference on EFQs,

> `->fieldCondition($field, $column = NULL, $value = NULL, $operator =
>  NULL, $delta_group = NULL, $language_group = NULL)`
>
> These conditions are specific to a field implementation.
>
> Looking at the body field in the article node type, a field condition would look like this: -\>fieldCondition('body', 'value', 'A', 'STARTS\_WITH')
>
> * field name. Though the field table in the database is named 'field\_data\_body', the actual field name is 'body'. This is in the field\_config\_instance table.
> * column. This is the column in the database that should be matched, with field name prefix removed. For body field, the database columns are: body\_value, body\_summary, body\_format, and language. 'value', 'summary', 'format', and 'language' are the actual arguments you would use. Likewise an image field would use 'fid', 'alt', and 'title' as column names; an entity reference field would use 'target\_id' and 'target\_type' as column names.

So, your syntax is correct, assuming your field name is correct (you want the machiine name), and your column is correct. Text and Longtext fields both use "value". You can verify this by looking at the database itself.

If your field name is `field_bar`, there will be a table called `field_data_field_foo`. Look at the columns. You should see one called `field_bar_value`.
> 2 votes

# Answer
Ok, this is very important!

The solution was adding this to the query:

```
 $nodeQuery->addMetaData('account', user_load(1));

```

As I mentioned I was running the code in the context of a Services module resource request. Looks like that I am prevented from filtering on a particular field, however not prevented from getting everything if I don't specify filter just load all and use `node_load`.
> 1 votes

# Answer
Have you tried to debug that EntityFieldQuery with dpm() like this?

```
dpm($nodeQuery->execute());

```

What is your result?

PS: you need the Devel module to run dpm() function...
> 0 votes

---
Tags: 7, database
---


# Question
Title: Problem loading classes in drupal module
I'm having trouble loading classes in drupal7. Let me start with a WORKING EXAMPLE that doesn't have problems.

If I create a file called `sites/all/modules/johnmodule/test.php` with the following contents

```
require_once(dirname(__FILE__) . "/dompdf-0.5.1/dompdf_config.inc.php");
$obj = new DOMPDF();

```

Then I go to the url `http://mysite.com/sites/all/modules/johnmodule/test.php`, then I get successful page load which is simply a blank page with nothing in it.

Now I tried to include these two lines of code into a drupal module, but it breaks everything. So what I did was I created a `sites/all/modules/johnmodule/johnmodule.info` and a `sites/all/modules/johnmodule/johnmodule.module`. For the contents of `johnmodule.module`, I have the following:

```
function johnmodule_billing_block_info()
{
    $blocks['johnmodule_billing'] = array('info' => t('Billing'), 'cache' => DRUPAL_CACHE_PER_ROLE);
    return $blocks;
}

/**
* Implements hook_menu()
*/
function johnmodule_billing_menu()
{
    $items = array();
    $items['billing'] = array(
    'title'         => 'My Billing History',
        'page arguments'    => array(1),
    'page callback'     => 'johnmodule_billing_view',
        'access callback'   => TRUE,
        'type'      => MENU_CALLBACK
    );

    return $items;
}

function johnmodule_billing_view()
{
    require_once(dirname(__FILE__) . "/dompdf-0.5.1/dompdf_config.inc.php");
    $obj = new DOMPDF();
}

```

Then when I go to `http://mysite.com/billing/`, I get a server error. When I looked in the apache error logs, I see:

```
PHP Fatal error:  Class 'DOMPDF' not found in /var/www/dev/mysite.com/public_html/sites/all/modules/johnmodule/johnmodule.module on line ZZZ, referer: http://mysite.com/billing

```

If I comment out the line `$obj = new DOMPDF()`, then the page loads fine.

WHy is Drupal not loading classes?

Additional Info

I tried to modify my `johnmodule_billing_view()` by using DOMPDF's \__autoload() function to force drupal to load the classes that DOMPDF needs like so:

```
function johnmodule_billing_view()
{
    require_once(dirname(__FILE__) . "/dompdf-0.5.1/dompdf_config.inc.php");

    $arrClassFix = array();
    if ($handle = opendir(dirname(__FILE__).'/dompdf-0.5.1/include')) {
    while (false !== ($entry = readdir($handle)))
        if(preg_match('/\\.cls\\.php$/',$entry))
        $arrClassFix[] = preg_replace('/\\.cls\\.php$/','',$entry);
    closedir($handle);
    }
    foreach($arrClassFix as $cls){ __autoload($cls); echo $cls;}

    $obj = new DOMPDF();
}

```

This made sure drupal loaded DOMPDF class and all dependent classes, but now when the dompdf object (within itself) needs to call one of it's dependent classes, it can't seem to access the classes I already loaded, and i get the following error in the apache logs:

```
PHP Fatal error:  Class 'Abstract_Renderer' not found in /var/www/dev/mysite.com/public_html/sites/all/modules/johnmodule/dompdf-0.5.1/include/inline_renderer.cls.php on line 48, referer: http://mysite.com/billing

```

But I double checked the arrClassFix and can confirm that Abstract\_Rendered was loaded in my foreachloop!

How do I get drupal these DOMPDF classes?

# Answer
> 0 votes
Ok, I solved my problem. Here's what I did

* I moved the folder dompdf-0.5.1 to the `/sites/all/libraries` folder
* I edited dompdf\_config.inc.php by replacing the `DOMPDF_autoload()` function with:

Code:

```
function DOMPDF_autoload($class) {
  /* Add this checking - START */
  if (mb_strtolower($class)== 'firephp'){
    return;
  }
  /* Add this checking - END */

  $filename = mb_strtolower($class) . ".cls.php";
  require_once(DOMPDF_INC_DIR . "/$filename");
}
if ( !function_exists("__autoload") ) {
  /**
   * Default __autoload() function
   *
   * @param string $class
   */
  function __autoload($class) {
    DOMPDF_autoload($class);
  }
}

```
* Then I updated the `johnmodule_billing_view()` function like so

Code:

```
function johnmodule_billing_view()
{

    require_once(realpath('.')."/sites/all/libraries/dompdf-0.5.1/dompdf_config.inc.php");
    spl_autoload_register('DOMPDF_autoload');

    $obj = new DOMPDF();
}

```

This worked and I was able to use the DOMPDF object/class.

---
Tags: 7
---


title: How to create a Views user page?

text:
# Question
Title: How to create a Views user page?
I'd like to create a users page (author page) where Articles by that user will be displayed. For example mysite/users/John needs to return teasers of articles that wrote the Author John.

I don't know how to make this when I have names in the URL. I can make the list of recent articles of a user only on paths like mysite/users/1.

This is how my configuration in Views looks like:

In Content: Author uid I have selected Provide default value --\> User ID from URL. From that it only looks for ID and can't recognize a name in the URL (i'm using pathauto).

# Answer
> 0 votes
In your contextual filter settings select "provide default value" -\> "user id from url" and it will work.

---
Tags: views
---


# Question
Title: Search index only part of custom content type
If I add a `search index display` on all my custom types, and set visible only a few columns, those columns will only be included in the search index ?

My problem is that i have columns i don't want to index (like file names), and i don't know how to do it.

# Answer
The search index is a view mode, but it is hidden by default (for some unknown reason).

Goto the **Manage Display** page for your content type. Expand the **Custom Display Settings** at the bottom. Tick **Search Index** and save.

A new tab, **Search Index** will appear. Click this, and then configure your content type to show / hide the fields you want indexed.

You may need to dump the search index (admin/config/search/settings) and then reindex the site. I can't recall if saving the search index does this automatically, of if I normally form alter that form to do it. The easiest way to do this is with drush:

```
drush -y search-reindex
drush -y search-index

```

As a side note, I will be releasing a small module to help debug search issues and check things like this. I am test driving it on a few sites now, and think it will be ready soon.
> 1 votes

---
Tags: search
---


title: Validate date selection in date picker

text:
# Question
Title: Validate date selection in date picker
I am using a javascript datepicker to allow users to select a date (which I have functioning in my form). What I don't know how to do is limit the dates that can be selected. Is there a way to do this using the datepicker instead of validating the form on submission?

Here is the code I am using to create the date selector:

```
drupal_add_library('system', 'ui.datepicker');
drupal_add_js($path . '/providers/support/js/datepicker.js');
drupal_add_js(array('dateselector' => array('date_format' => $date_picker_format)), 'setting');
return array(
  '#type' => 'textfield',
  '#default_value' => $current_value,
  '#attributes' => array('class' => array('datefield')),
);

```

Am I missing an option somewhere?

# Answer
To limit available dates you want `minDate`, `maxDate` and `beforeShowDay` datepicker options. `beforeShowData` is useful to limit allowed values programatically.

minDate and maxDate can be passed to js as:

```
drupal_add_js(array('dateselector' => array('date_format' => $date_picker_format, 'minDate' => '+1d')), 'setting');

```

.. and here's an example of beforeShowDay usage: https://drupal.stackexchange.com/a/60121/8437

btw, I'd recommend using Date's date\_popup form element in conjunction with Date Restrictions, for a variety of advanced restrictions.
> 0 votes

# Answer
I don't see, how you initialize the datepicker (probably in \*/providers/support/js/datepicker.js file), but for this functionality you should use maxDate and minDate options of datepicker library.
> 0 votes

---
Tags: 7, forms, javascript
---


# Question
Title: Custom theme doesn't show up in Blocks section
I've looked through different threads about this issue and didn't see any answers. I have a fresh install of Drupal 7 with no extra modules enabled. I've started building a custom theme but it doesn't list itself in the blocks section even though it's enabled. It shows the original bartik theme and the admin seven theme. The odd part is I added a new block under Header which I have listed in my .info page and it showed up in my theme but I can't edit the block because the it only gives access to those two themes and not mine. How can I fix this?

I also have all of these error messages in the admin and I've barely added anything to my theme. Not sure what I'm missing.

> Notice: Undefined index: name in block\_menu() (line 146 of /home/infanity/public\_html/beta/modules/block/block.module).
> Notice: Undefined index: name in block\_menu() (line 165 of /home/infanity/public\_html/beta/modules/block/block.module).
> Notice: Undefined index: name in system\_menu() (line 647 of /home/infanity/public\_html/beta/modules/system/system.module).
> Notice: Undefined index: name in \_ctools\_list\_themes() (line 574 of /home/infanity/public\_html/beta/sites/all/modules/ctools/includes/plugins.inc).
> Notice: Undefined index: name in block\_menu() (line 146 of /home/infanity/public\_html/beta/modules/block/block.module).
> Notice: Undefined index: name in block\_menu() (line 165 of /home/infanity/public\_html/beta/modules/block/block.module).
> Notice: Undefined index: name in system\_menu() (line 647 of /home/infanity/public\_html/beta/modules/system/system.module).
> Notice: Undefined index: name in \_ctools\_list\_themes() (line 574 of /home/infanity/public\_html/beta/sites/all/modules/ctools/includes/plugins.inc).
> Notice: Undefined index: name in system\_sort\_modules\_by\_info\_name() (line 944 of /home/infanity/public\_html/beta/modules/system/system.admin.inc).
> Notice: Undefined index: name in system\_sort\_modules\_by\_info\_name() (line 944 of /home/infanity/public\_html/beta/modules/system/system.admin.inc).
> Warning: uasort() \[function.uasort\]: Array was modified by the user comparison function in system\_themes\_page() (line 139 of /home/infanity/public\_html/beta/modules/system/system.admin.inc).
> Notice: Undefined index: name in system\_themes\_page() (line 148 of /home/infanity/public\_html/beta/modules/system/system.admin.inc).
> Notice: Undefined index: name in system\_themes\_page() (line 190 of /home/infanity/public\_html/beta/modules/system/system.admin.inc).
> Notice: Undefined index: name in theme\_system\_themes\_page() (line 2728 of /home/infanity/public\_html/beta/modules/system/system.admin.inc).

I've stripped my theme to just the .info file which the manual says is all that's required and I still get errors and although enabled still doesn't show up as the default theme in the block section. Here is my .info file labled fod.info in a folder labeled fod in the sites/all/themes folder.

```
name = fod
core = 7.x

stylesheets[all][] = css/style.css
regions[header] = Header
regions[highlighted] = Highlighted
regions[help] = Help
regions[content] = Content
regions[navigation] = Navigation
regions[sidebar_first] = Left sidebar
regions[sidebar_second] = Right sidebar
regions[footer] = Footer

```

And here are the errors I'm still getting in the admin.

> Notice: Undefined index: name in block\_help() (line 69 of /home/infanity/public\_html/betaD/modules/block/block.module).
> Notice: Undefined index: name in block\_menu() (line 146 of /home/infanity/public\_html/betaD/modules/block/block.module).
> Notice: Undefined index: name in block\_menu() (line 165 of /home/infanity/public\_html/betaD/modules/block/block.module).
> Notice: Undefined index: name in system\_menu() (line 647 of /home/infanity/public\_html/betaD/modules/system/system.module).

# Answer
*If you want to skip the full story*

Search for any "\*.info" file in your drupal repo that has no line similar to "name = xxxx".

My problem was due to a file named "lcov.info" in a grunt module (grunt-svgmin) in my theme. I happended "name = lcov is not a theme" at the beginning of the file and the issue fade away. I'll check svg-min later.

---

**Full story**

I had the same notice problem for few days.

The notice was a pattern of 3 lines :

in block.module :

line 146 :

```
'title' => check_plain($theme->info['name'])

```

and line 165

```
'title' => check_plain($theme->info['name']),

```

in system.module line 647 :

```
'title' => $theme->info['name'],

```

This pattern is replicated a variying number of times depending on the pages.

I've tried switching theme in vain.

I first tried to cleanup - hence the last part may apply. It worked at first (which explains my first response), but came back.

**What I did : ** Open system.module and go to line 645

```
  foreach (list_themes() as $theme) {
    $items['admin/appearance/settings/' . $theme->name] = array(
      'title' => $theme->info['name'],

```

insert these two var\_dump lines :

```
 foreach (list_themes() as $theme) {
    var_dump("-----------------");
    var_dump($theme->info['name']);
    $items['admin/appearance/settings/' . $theme->name] = array(
      'title' => $theme->info['name'],

```

Visit your site. It should show something like

```
string '-----------------' (length=17)
string 'A Theme' (length=5)
string '-----------------' (length=17)
string 'Bartik' (length=6)
string '-----------------' (length=17)
string 'Garland' (length=7)
string '-----------------' (length=17)
null
string '-----------------' (length=17)
string 'Seven' (length=5)
string '-----------------' (length=17)
string 'Stark' (length=5)
string '-----------------' (length=17)
string 'Zen' (length=3)

```

**See this empty line where it is written null ????** This is the F....g theme. So I looked up to the admin theme to find the culprit and got rid of "engines" folder ...But discovered engine is not a theme, so added it back. I then went

```
drush pm-list --type=Theme

```

And found a disabled theme named **\*lcov (lcov) ***

*Believe it or not : it is not a drupal theme !!*

*it is a file named lcov.info in a node module -- grunt-svgmin -- in my theme*

\*TADA !!! *

---

First attempt

The sub theme I heritated was based on ZEN, but zen was not inclued any longer. Also, theme name included numbers abc123

On a another instance of the local site I :

Added a fresh version of zen and activated it

ran `drush zen "My human readable Theme name" mymachinethemename` /\* the latter will generate a clean version of your ZEN subtheme \*/

Adjusted the subtheme.info file for regions, assets and optins

Moved the badly named theme to another folder outside of the site

started adding back assets from the old theme, then templates and includes, piece by piece, renaming functions to match the theme name

No need to say you need to backup and work on a dedicated branch and database. You might have to reposition blocks in admin.

Not sure it was the most efficient but as I'm roughly new to drupal it was a great way for me to dig in this legacy theme.

Charles
> 3 votes

# Answer
Blocks are put into regions. The regions are defined in the \*.info file of your theme an put into place in the page.tpl.php. Actualy I have never worked without this building blocks in plac,e but if the theme hasn't any regions, they cannot show up in the blocks configuration.

If you're new to drupal theming I sugest to take a base theme and create a subtheme to tweak it to your nedds. The zen theme is a good starting point and it commes with a ready built start-kit for subthemeing. Also have a look at drupal theming guide.

Hope this get's you going.
> 0 votes

# Answer
The error you are getting is caused from the fact the name is missing from the .info file for your theme.
In block\_menu(), the code that is causing the error is the following one.

```
$items['admin/structure/block/list/' . $key] = array(
  'title' => check_plain($theme->info['name']),
  'page arguments' => array($key),
  'type' => $key == $default_theme ? MENU_DEFAULT_LOCAL_TASK : MENU_LOCAL_TASK,
  'weight' => $key == $default_theme ? -10 : 0,
  'access callback' => '_block_themes_access',
  'access arguments' => array($theme),
  'file' => 'block.admin.inc',
);

```

```
$items['admin/structure/block/demo/' . $key] = array(
  'title' => check_plain($theme->info['name']),
  'page callback' => 'block_admin_demo',
  'page arguments' => array($key),
  'type' => MENU_CALLBACK,
  'access callback' => '_block_themes_access',
  'access arguments' => array($theme),
  'theme callback' => '_block_custom_theme',
  'theme arguments' => array($key),
  'file' => 'block.admin.inc',
);

```

In system\_menu(), the code causing the error is the following one.

```
  foreach (list_themes() as $theme) {
    $items['admin/appearance/settings/' . $theme->name] = array(
      'title' => $theme->info['name'],
      'page arguments' => array('system_theme_settings', $theme->name),
      'type' => MENU_LOCAL_TASK,
      'access callback' => '_system_themes_access',
      'access arguments' => array($theme),
      'file' => 'system.admin.inc',
    );
  }

```

In all the cases, the error is raised when Drupal tries to access `$theme->info['name']`, but the "name" index is not defined.

Be sure there isn't any strange Unicode character before `name =`, especially an invisible character.

If you are editing the .info file of the theme when the theme is enabled, you need to first disable it, and re-enable it, as the content of the .info file is cached.
> 0 votes

# Answer
Try to save you themename.info file as ANSI code.
> -2 votes

---
Tags: 7, blocks
---


# Question
Title: Rules: how to display the value of variables?
I use the Devel module on Drupal 7 to debug some rules of my site but I can't debug without knowing the value of variables I created.

In the case, I have a loop where I sum different values and at the end of the loop I store that in a second variable that I compare to fixed parameters.

Is there something that can show me every value of the rules variables?

In the default log I have only events but I don't know anything else... Thanks!

# Answer
Two options:

* At admin/config/workflow/rules/settings, set "Show debug information" to "Always."
* In the rule's actions, add the action "Show a message on the site" (under the System group, I believe). Pass it the variable(s) you want to debug.
> 6 votes

---
Tags: rules, debugging
---


# Question
Title: Migrate error: Call to a member function count() on a non-object
I am trying to implement a user migration with the migration module but am getting this error:

> Fatal error: Call to a member function count() on a non-object in E:\wamp\www\website\sites\all\modules\migrate\includes\migration.inc on line 946

here is my migrate class:

```
abstract class CakeBaseMigration extends Migration {
  public function __construct($arguments) {
    parent::__construct($arguments);

    $this->team = array(
      new MigrateTeamMember('Chris', 'chris@somewhere.com',
          t('developer')),
    );

    Database::addConnectionInfo('for_migration', 'default', array(
      'driver' => 'mysql',
      'database' => 'databasename',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'prefix' => '',
    ));

  }
}

class CakeUserMigration extends CakeBaseMigration {
  public function __construct($arguments) {

    parent::__construct($arguments);
    $this->description = t('Lagacy cakePHP system customers');

    $query = Database::getConnection('default', 'for_migration')
    ->select('customers', 'c')
    ->fields('c');

    $this->source = new MigrateSourceSQL($query);
    $this->destination = new MigrateDestinationUser();

    $this->map = new MigrateSQLMap($this->machineName,
        array('id' => array(
          'type' => 'int',
          'not null' => TRUE,
          'description' => 'Account ID.'
        )
        ),
        MigrateDestinationUser::getKeySchema()
    );

    $this->addFieldMapping('username', 'name');
    $this->addFieldMapping('pass', 'password');
    $this->addFieldMapping('mail', 'email');
    $this->addFieldMapping('created', 'modified');
    $this->addFieldMapping('roles')
    ->separator(',')
    ->defaultValue(DRUPAL_AUTHENTICATED_RID.',4');

  }
}

```

running the drush command `drush migrate-audit --all`says that that cakeUser is missing a source and destination.

I don't get it, Setting the database and running the query at devel/php returns the expected rows from the database.

Any help on this would be fantastic :)

# Answer
> 0 votes
It seems the problem was the files not saving properly after I updated them, The code I posed above seems to be working ok now.

---
Tags: 7, migrations
---


# Question
Title: How can I construct an HTTPS POST with drupal_http_request?
I want to do a post request to an HTTPS server address... I have this example code that demonstrates sending a POST request -

```
$data = 'name=value&name1=value1';

$options = array(
                'method' => 'POST',
                'data' => $data,
                'timeout' => 15,
                'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
        );

$result = drupal_http_request('http://somewhere.com', $options);

```

and also on `drupal_http_request`, there is this code -

```
case 'https':
  // ***************
  // Note: Only works when PHP is compiled with OpenSSL support.
  // ***************
  $port = isset($uri['port']) ? $uri['port'] : 443;
  $socket = 'ssl://' . $uri['host'] . ':' . $port;
  $options['headers']['Host'] = $uri['host'] . ($port != 443 ? ':' . $port : '');
  break;

```

to demonstrate sending a POST to an HTTPS connection. Problem is, I can't figure out out to implement the HTTPS options in the POST example code above. Can someone please help me and explain how to do this? I'm quite new to PHP code writing and Drupal and could definitely use the guidance. The `drupal_http_request` documentation are great as an index, but it doesn't help you a lot if you want to learn things from scratch.

**edit-**

after your comment's, i got to this code -

```
    $data = 'access_token=455754fhnaI&href=fb&template=You have people waiting to play with you, play now!';

$options = array(
                'method' => 'POST',
                'data' => $data,
                'timeout' => 15,
                'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
        );

$result = drupal_http_request('https://graph.facebook.com/1000721/notifications?', $options);

```

but its still dosen't work... if i post via FIREFOX poster with this patten -

```
https://graph.facebook.com/1000080521/notifications?
     access_token=45575FpHfhnaI&
     href= fb &
     template=You have people waiting to play with you, play now!

```

it's working... so i am probably not constructing the request properly in drupal... thanks a lot everyone... really hope someone could help me figure this out...

# Answer
You should only need to set it in the protocol.

```
$result = drupal_http_request('https://somewhere.com', $options);

```

### Parameters

**$url**: A string containing a fully qualified URI.

**array $options**: (optional) An array that can have one or more of the following elements:

* **headers**: An array containing request headers to send as name/value pairs.
* **method**: A string containing the request method. Defaults to 'GET'.
* **data**: A string containing the request body, formatted as 'param=value&param=value&...'. Defaults to NULL.
* **max\_redirects**: An integer representing how many times a redirect may be followed. Defaults to 3.
* **timeout**: A float representing the maximum number of seconds the function call may take. The default is 30 seconds. If a timeout occurs, the error code is set to the HTTP\_REQUEST\_TIMEOUT constant.
* **context**: A context resource created with stream\_context\_create().
> 3 votes

# Answer
Alternative to this is to use HTTPRL. Try replacing drupal\_http\_request with httprl\_override\_core. If it works, there is a setting `admin/config/development/httprl` you can set in the GUI to make core use HTTPRL.

When using HTTPRL you don't need to manually encode the $data. Leave it as an array (skip http\_build\_query).
> 2 votes

---
Tags: 7
---


title: DrupalDatabaseCache::set Devel Module

text:
# Question
Title: DrupalDatabaseCache::set Devel Module
I seem to be getting slow speeds with DrupalDatabaseCache::set and DrupalDatabaseCache::getMultiple

i am using drupal 7 and am on a Virtual Private Server on Dreamhost which is running Fast CGI and xchache

Any tips on how to get these requests (40+ milliseconds) down under 5mills?

there are some other querries that are above 5 milliseconds user\_roles, menu\_get\_item, menu\_item\_visibility\_load etc..

any tips for overall improvement in the time querries take to load?

# Answer
1. Best Option: Use a non DB cache backend like Memcache
2. Next Best: Use a MySQL derivative that supports blob columns in a memory table and convert all cache tables to be of the type memory. Be sure to rebuild the indexes as BTREE's instead of HASH after converting to MEMORY. More details on this can be seen in this presentation: http://www.percona.com/resources/technical-presentations/drupal-and-mysql-performance-percona-live-mysql-webinar
3. Still good: Follow the directions here: Drupal 7: Database select query FROM cache\_bootstrap brings server down

Note that all 3 of the above options are independent from each other; so you can do all 3. Also noted that the answer in #3, his database server was configured reasonably well; you might need to tune InnoDB in order to get better performance out of your's.

EDIT:
Also checkout my guide on tuning D7 https://docs.google.com/presentation/d/1AgnurTWsWdMAFjfFmSU7mk2zfJu8jG\_KmVdZ7-o6Pok/edit#slide=id.p
> 1 votes

---
Tags: caching, debugging
---


# Question
Title: How can write reffering page node or url in a field of entity form
I have an entity form and need to know which page refered to form. How can write refferer url or node id to a field ?

# Answer
Using an entityreference to the page the entity form is displayed on solved this for me. Here's some code providing a entity form block with the values prefilled and locked:

```
<?php
/**
 * Implements hook_block_info().
 */
function mymodule_contact_block_info() {
  $blocks['mymodule_contact'] = array(
    'info' => t('mymodule contact form'),
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function mymodule_contact_block_view($delta) {
  $block = array();
  switch ($delta) {
    case 'mymodule_contact' :
      module_load_include('inc', 'entityform', 'entityform.admin');
      $entity_form_name = 'contact'; // machine name of entity form
      $render_contact_form = entityform_form_wrapper(entityform_empty_load($entity_form_name), 'submit', 'embedded');
      $render_contact_form['field_contact_page']['#access'] = FALSE; // machine name of entity reference field
      $block['content'] = drupal_render($render_contact_form);
      break;
  }
  return $block;
}

/**
 * Implements hook_entity_presave().
 *
 * set the page reference to the current active menu object
 */
function mymodule_contact_entity_presave($entity, $type) {
  if ($type == 'entityform' && empty($entity->draft) && $entity->type == 'contact' && $entity->is_new == TRUE) {
    $node = menu_get_object();
    if (isset($node->nid)) {
      $entity->field_contact_page[LANGUAGE_NONE][0]['target_id'] = $node->nid;
    }
  }
}

```
> 1 votes

---
Tags: tokens, entities
---


title: Profile2 and Panels in Drupal 7

text:
# Question
Title: Profile2 and Panels in Drupal 7
How can I override a Profile2 profile page using Panels in Drupal 7?

The page I'm looking to override is the edit for for one of the new profile2 pages. Here is an example URL: http://example.com/profile-user\_settings/%uid/edit

# Answer
> 6 votes
There is a work around using Page Manager Existing Pages (as suggested by Letharion) and hook\_menu().

hook\_menu() was required as Profile2 doesn't seem to register profile pages with the menu router. This was preventing Page Manager Existing Pages from being able to intercept the page.

```
function MYMODULE_menu() {
    $items['profile-example'] = array(
        'page callback' => '_profile2_form',
        'page arguments' => array(),
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
    );
    return $items;
}

function _profile2_form() {
    global $user;
    module_load_include('inc', 'profile2_page', 'profile2_page');
    $profile2 = profile2_by_uid_load($user->uid, 'profile2_profile_system_name_goes_here');
    $entity_form = entity_ui_get_form('profile2', $profile2, 'edit');
    return $entity_form;
}

```

This can now be intercepted by Page Manager Existing Pages and properly displayed by the Panels module.

# Answer
> 0 votes
You can plan it with blocks using Node Block module that would help to bring any node content to configurable block for profile page.

You can also focus page-profile.tpl.php, if you are looking customization on that page regarding layout. e.g. new region placement etc.

# Answer
> 0 votes
I haven't looked at this, but a guess says that Profile2 will need to implement a ctools "task" for the form to become accessible like other things in the Panels UI.

In your simple use case though, you could try Page manager existing pages which will wrap an existing page for you. This should be enough for your current use case.

# Answer
> 0 votes
This is a known issue it seems with Panels2. Overrides can still be done with the default Drupal template engine.

# Answer
> 0 votes
Responding to Citricguy above, I tried a number of iterations of your great tip, but what finally worked was to, effectively, hardcode the profile2 path for each profile in our system. Ex:

```
$items['user/%user/edit/consumer_profile'] = array(
  'page callback' => '_profile2_form',
  'page arguments' => array(),
  'access callback' => TRUE,
  'title' => 'My Profile',
  'type' => MENU_LOCAL_TASK,
);
return $items;

```

The rest of your example remained true. That said, I can probably pass in the "consumer\_profile" bit to your entity fetcher helper.

# Answer
> 0 votes
There is a patch here to provide the missing glue between Panels and Profile2.

https://drupal.org/node/1011370#comment-6884220

# Answer
> 0 votes
Regarding the "workaround using Page Manager Existing Pages", I assume you wouldn't want `'access callback' => TRUE,` in your menu hook since anonymous users (i.e. uid = 0) wouldn't have a profile and this would result in downstream errors. I suppose you can just add

> 'access arguments' =\> array('edit own main profile'),

to the array instead to mimic pre-existing permissions for Profile2.

---
Tags: 7, panels
---


# Question
Title: What are the major differences in building an install profile for Drupal 8?
There is a good guide for drupal 7 which explains how to build a `install profile` for drupal 7. I built an install profile using it.

But I want to build an install profile using Drupal 8. What changes do I need to make to my Drupal 7 install profile to make it work for Drupal 8.

PS: I know Drupal 8 is not ready yet but I'm doing this for learning purposes.

# Answer
Apart from specific code changes like converting the .info file to a .info.yml, the biggest conceptual change is that most of what an install profile will contain are configuration files.

Basically, you can take the configuration directory of in installed site, copy it into the config folder of an install profile and then you're already pretty close to building an install profile that will at the end look like the site.

There will still be a few challenges, for example dependencies between configuration and content. Lee Rowlands (@larowlan) is working on a default content module that allows to import content entities from .yml files too https://github.com/larowlan/default\_content, but you can't just stuff all of it into an install profile.

Take a custom block for example. You have a block configuration, which depends on a custom block content, which in turn depends on a custom block type (bundle of the custom block). I'm guessing the way to solve that will be to split an install profile in a set of modules, that depend on each other.
> 3 votes

---
Tags: 8, installation-profiles
---


# Question
Title: Facet API and views contextual filters (facets block on non-search page)
I'm using Facets API with SOLR and it all works fine.

I also have a standard view set up using a facets block from the search-index view. This also works OK, but it shows the complete unfiltered facet list.

What I'd like to do is apply a contextual filter from the path to the facet block, but it doesn't seem to work - I get nothing.

I'm wondering whether this is possible and if so how (and if anyone even understands what I'm asking?!)

Thanks, Chris

# Answer
OK, worked this out myself:

Use the contextual filters prefixed "Search:" in the list (not "Indexed node:". There are 2: "Search: Fulltext search" and "Search: Indexed taxonomy term fields"

Not sure if Search: Fulltext search is ideal as I'm using it for place names and there are a few with more than one word.
> 2 votes

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


# Question
Title: Drupal add class to body if page is unpublished
I would like to be able to add an unpublished class to the body tag of a node (for both its main view and edit view) if the node has been unpublished.

How can I do this?

---

**Steps I have taken:**

1) Node Object The node object contains if a node has been published or unpublished (with `$node -> Status`), but I am not sure how to test this for each node and then add it to the body class.

This question is similar, but the provided answer doesn't work.

2) Drupal 6 This page explains how to do it for Drupal 6, but the code doesn't work for Drupal 7.

# Answer
> 7 votes
in your theme's template.php:

```
function mytemplate_preprocess_html(&$vars) {
  $node = menu_get_object();
  if ($node && isset($node->nid)) {
    if ($node->status) {
      $vars['classes_array'][] = 'published';
    } else {
      $vars['classes_array'][] = 'unpublished';
    }
  }
}

```

---
Tags: theming
---


title: Add class based on published state

text:
# Question
Title: Add class based on published state
I am trying to add a body class to my site in template.php based on whether or not a node is published or not. I had a look around here and on drupal.org and pieced together some code but I am getting an error. Here is what I have tried so far:

```
function responsive_process_html(&$variables) {

 if ($node->status == 1){
        //$variables['#attributes']['class'][] = 'pub';
        $variables['classes_array'][] = 'published';
    }

    else {
        $variables['classes_array'][] = 'not-published';
    }
}

```

... but I am getting this error:

```
Notice: Undefined variable: node in responsive_process_html() (line 37 of /sites/all/themes/responsive/template.php).
Notice: Trying to get property of non-object in responsive_process_html() (line 37 of /sites/all/themes/responsive/template.php).

```

I also tried `$variables['#attributes']['class'][] = 'published';` instead of `$variables['classes_array'][] = 'published';` but it made no difference.

# Answer
I ended up finding a sweet little function from the Zen Theme (7.x-5.1). In template.php add this preprocess node function:

```
function MY_THEME_preprocess_node(&$variables, $hook) {
        // Add $unpublished variable.
        $variables\['unpublished'\] = (!$variables\['status'\]) ? TRUE : FALSE;
    }

```

Then in node.tpl.php or your node--custom.tpl.php grab the `unpublished` variable and add something like this:

```
 <?php if ($unpublished): ?>
    <!-- whatever code you want here using the variable-->
    <p class="unpublished"><?php print t('Unpublished'); ?></p>
 <?php endif; ?>

```

You can then theme this any way you want and it's a great visual indicator to the user that the node is unpublished. (see screen capture).
> 2 votes

# Answer
in your theme's template.php:

```
function mytemplate_preprocess_html(&$vars) {
  $node = menu_get_object();
  if ($node && isset($node->nid)) {
    if ($node->status) {
      $vars['classes_array'][] = 'published';
    } else {
      $vars['classes_array'][] = 'unpublished';
    }
  }
}

```
> 4 votes

# Answer
That `$node` variable isn't defined, but may be passed along inside...

```
$node=$variables['node'];

if (!empty($node)) { // we are displaying a node

  if ($node->status) {
    // we are published
  } else {
    // we aren't published
  }

} else { // we are in a view or another none node type page
  // do whatever here then
}

```

... if you are displaying a full node page, so I'd check to see if it's in there. It would be in preprocess\_page() so may be available to preprocess\_html() as well.

ADDITION:

For example, see if this works....

```
function YOURTHEME_OR_MODULE_preprocess_html(&$variables) {

  $node=$variables['node'];

  if (!empty($node)) {

    if ($node->status) {
      $variables['classes'].=' published';
    } else {
      $variables['classes'].=' not-published';
    }

  }

}

```

...but I am just looking at the code as I don't have a D7 testbed to actually run this on.
> 1 votes

---
Tags: 7, theming
---


# Question
Title: How can I embed a node inside on another node?
In Drupal 7 I have a content type created by admin (say content type X), And the other part i have a content type created by users (say content type Y). Now that is what I do when a user creates content type Y, he can select a node of content-type X to embed node x in node Y.

Without link title node by "References Module" or coding html by "node\_embed Module".

# Answer
You can use entityreference together with display suite and have the display of the entityreference field set to rendered entity. Using rendered entities you can can render any entity with a view mode you need for your display. See this question if you want to create a custom template for the output of that node: How to provide template for particular view mode?
> 2 votes

---
Tags: 7, nodes
---


# Question
Title: 403 forbidden error loading "sites" files
I had an installation of Drupal 7.24 and I was doing a new install with 7.26. Everything went well until the end, when I tried to login. When I try to login or submit any form the page just refreshes back to where I was.

I inspected element to see what was going on and noticed a bunch of files from `site/default/...` were returning 403 forbidden. I chmod-ed all the files in `sites/default` to `777` to try it out and it still did the same thing.

What part of Drupal could this problem reside in?

EDIT: deleted cookie, fore refreshed, tried in incognito.

# Answer
Have you checked out if you have set the public &/or private file permission on configuration page \> Media \> File System. Also do check permission of what ever form your are trying to submit.
> 1 votes

---
Tags: 7, files
---


# Question
Title: Automatically change field when another field value is selected
I have a content type called Jobs.

This include a field contact which is user reference.

I have another content type called Job application.

This includes a node reference based on Jobs and field contact which is user reference.

I want when a user selects a job in the node reference select list on the job application form to automatically change the contact field in that form which the value that exists in the contact field for the relevant job selected.

Example: Job: Educator contact: Michael

On Job application upon selected the job "educator" the user reference field should automatically take the value Michael.

Any ideas on how to solve this? Would Rules work and if so how? If through programming, is there a module that allows for injecting code for content types?

Preferably I am looking for a solution that does not involve programming.

# Answer
> 0 votes
This sounds like a bad case of data de-normalization. You shouldn't have a "Contact" field on your "Job application" content type if it's simply going to duplicate whatever is already in the "Job" content type.

If you're simply wanting to be able to see who the contact is for a given application, use the "Rendered entity" formatter for the job reference field on the application content type. (I'm assuming you're using the Entity Reference module?) In the formatter settings, choose a view mode that only displays the contents of the Contact field on the job node.

This way, if the contact ever changes for the job, it'll live-update across all job applications.

# Answer
> 0 votes
You need to create a new role and give permission to that role and include Michel accordingly to that role from people tab on administrative menu.

---
Tags: nodes, users, rules
---


title: how can i add user avatar to admin menu

text:
# Question
Title: how can i add user avatar to admin menu
What function do I need to use for adding the image in the admin menu?

>

# Answer
> 1 votes
Above menu is rendered from toolbar.tpl.php inside toolbar module.

All you need to is override above toolbar.tpl.php by copying it to your themes folder and modify code to add image.

```
<?php

/**
 * @file
 * Default template for admin toolbar.
 *
 * Available variables:
 * - $classes: String of classes that can be used to style contextually through
 *   CSS. It can be manipulated through the variable $classes_array from
 *   preprocess functions. The default value has the following:
 *   - toolbar: The current template type, i.e., "theming hook".
 * - $toolbar['toolbar_user']: User account / logout links.
 * - $toolbar['toolbar_menu']: Top level management menu links.
 * - $toolbar['toolbar_drawer']: A place for extended toolbar content.
 *
 * Other variables:
 * - $classes_array: Array of html class attribute values. It is flattened
 *   into a string within the variable $classes.
 *
 * @see template_preprocess()
 * @see template_preprocess_toolbar()
 *
 * @ingroup themeable
 */
?>
<div id="toolbar" class="<?php print $classes; ?> clearfix">
  <div class="toolbar-menu clearfix">
    <?php print render($toolbar['toolbar_home']); ?>
    <?php print render($toolbar['toolbar_user']); ?>
    <?php print render($toolbar['toolbar_menu']); ?>
    <?php

    $variables = array(
      'path' => 'path/to/img.jpg',
      'alt' => 'Test alt',
      'title' => 'Test title',
      'width' => '5px',
      'height' => '5px',
      'attributes' => array('class' => 'some-img', 'id' => 'my-img'),
      );
      print theme_image($variables)?>
    <?php if ($toolbar['toolbar_drawer']):?>
      <?php print render($toolbar['toolbar_toggle']); ?>
    <?php endif; ?>
  </div>

  <div class="<?php echo $toolbar['toolbar_drawer_classes']; ?>">
    <?php print render($toolbar['toolbar_drawer']); ?>
  </div>
</div>

```

---
Tags: media
---


title: Fatal error: while enabling AT theme

text:
# Question
Title: Fatal error: while enabling AT theme
I tried to enable AT theme and now have a white page with the error:

`Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 72 bytes) in /Applications/MAMP/htdocs/test/includes/theme.inc on line 98`

I changed my **php.ini** `memory_limit = 128M`. No difference.

I am so crazy pressed for time, this is the worst thing to happen now. How can i fix this? Please somebody HELP!!!!!

The site is on a localhost.

PS- now i see a different error:

```
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 72 bytes) in /Applications/MAMP/htdocs/test/sites/all/modules/ds/includes/ds.registry.inc on line 554

```

Drupal 7.2.4

# Answer
> 1 votes
Looks like 128M of memory is still not enough, try more. If that still fails there's probably a memory leak or endless loop somewhere, or a too bloated configuration (e.g. too many fields, trying to debug a structure that has too many entries and so on).

---
Tags: theming
---


# Question
Title: Drush make and SVN: Leaving behind the .svn folders
Maybe I am missing a parameter, but when I use the below code in my make file, the ".svn" folder is removed. I would like that folder to remain. How can I do this?

```
projects[module_name][type] = "module"
projects[module_name][download][type] = "svn"
projects[module_name][download][url] = svn+ssh://company.com/home/svn/drupal7modules/module_name

```

# Answer
Use the `--working-copy` option.

Help tekst: Preserves VCS directories, like .git, for projects downloaded using such methods.
> 1 votes

---
Tags: drush
---


# Question
Title: How to add content title as dropdown list for exposed filter?
I have a node ABC and using view where content is of type ABC. I have content title as a field in Views.

What is the way in which I can get a drop down for field content title in the filter criteria?

# Answer
> 0 votes
You have to implement a hook\_form\_alter with a custom module like this:

```
    function mytools_form_alter(&$form, $form_state, $form_id) {
  if($form_id == 'views_exposed_form') {
    //unset($form['average']);
    $form['average'] = array(
      '#type' => 'select',
      '#options' => array(0 => t('<any>'), 20 => '*', 40 => '**', 60 => '***', 80 => '****', 100 => '*****'),
      '#default_value' => 0,
      '#title' => t('The average vote is more than'),
    );
  }
}

```

Where the form\_id is your current views form ID (you can see it with firebug in your code).

---
Tags: 7, views
---


# Question
Title: Automatically open linked pdf (bypassing download box)
I've created a Content type that allows me to upload files (specifically pdf's).

After uploading a pdf file and then linking to it in a static document, clicking the link gives me a download page.

I want the link to open the pdf directly. I tried the recommendation at http://www.drupalgardens.com/content/file-content-type but get a similar page, without the link.

Assistance in fixing this would be greatly appreciated!

---

**Try it for yourself**

There are three bulleted links on the page: http://roguepublishing.ca/content/Communicating\_Science

The regular 'Table of contents' leads to a page with one URL on it. That is the same URL as the hard-coded 'Table of contents'. As you can see, using these links opens the pdf's.

The 'Resource' Content type has * Enable Display field is checked * Files displayed by default is checked * The Manage Display is set to "URL to file" If I change Manage Display to "Table of files", I get a table with a link to the file. Clicking that link launches the pdf.

*Simply: how do I get Drupal to launch the pdf from the alias on the first page?*

# Answer
> 1 votes
You are just linking to files, and the default action for the browser to take is to ask to download the file.
Files will sometimes automatically open if the browser is set up to do so.
If you want to make sure the pdf is always displayed, you will have to look into pdf viewer modules. Here is a site that compares a few.
https://drupal.org/node/1781960

# Answer
> 1 votes
### **Closing this discussion**

I am surprised that Drupal has such advanced functionality in core, but such a simple task requires an external module. Apparently, File Entity will do this, but I haven't figured out how. Yet.
I have summarized and generalized the problem at https://drupal.org/node/2207001

Thanks,
Roy Jensen

---
Tags: nodes, files
---


# Question
Title: Does 'aggregate and compress CSS files' actually use gzip?
Under performance settings in my D7 site, I have "Aggregate and compress CSS files" enabled.

When I run YSlow, I get this:

> Grade F on Compress components with gzip. There are 4 plain text components that should be sent compressed:
>
> * /files/css/css\_CKoWqiBj9gVXhPuDSnNphuEB0b0J2To76x0pX0EGqn4.css
> * /files/css/css\_5lmdLBQE3741385dmh2zZ\_gO\_fPyq-62r9KkuUzfIH0.css
> * /files/css/css\_UIg6lj2uEi5H1zubqecd1x6N7\_ejFWRiwKYJ\_qrEmOQ.css
> * /files/css/css\_oYatxLY13v2flmA\_6hUfSrbPmK\_x8KS-tOsczLXYqqo.css

This suggests that the aggregated CSS files aren't being gzipped by Drupal?

# Answer
> 3 votes
As MPD says the options in the performance screen only concatenated and minify the files.

To also Gzip you should turn it on in your Apache config or .htaccess

```
<IfModule mod_deflate.c>
  <FilesMatch ".(js|css|html|php|txt)$">
    SetOutputFilter DEFLATE
  </FilesMatch>
</IfModule>

```

# Answer
> 6 votes
There is a difference. You are seeing aggregated (ie, concatenated) and minified CSS when you tick that option on the performance page.

That YSlow report is talking about the webserver sending the results compressed responses the wire. I honestly can't remember if there is a Drupal option for output compression as I always use mod\_deflate rules to do this.

Typically, I add the rules directly to the Apache config for my whole server (so I don't have to worry about core updates nuking my .htaccess file). Lately, I have been using the rules from HTML5 Boilerplate:

```
<IfModule mod_deflate.c>
  # Force deflate for mangled headers developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping/
  <IfModule mod_setenvif.c>
    <IfModule mod_headers.c>
      SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
      RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
    </IfModule>
  </IfModule>

  # HTML, TXT, CSS, JavaScript, JSON, XML, HTC:
  <IfModule filter_module>
    FilterDeclare   COMPRESS
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/html
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/css
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/plain
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/x-component
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/javascript
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/json
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/xhtml+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/rss+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/atom+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/vnd.ms-fontobject
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $image/svg+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $image/x-icon
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/x-font-ttf
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $font/opentype
    FilterChain     COMPRESS
    FilterProtocol  COMPRESS  DEFLATE change=yes;byteranges=no
  </IfModule>

  <IfModule !mod_filter.c>
    # Legacy versions of Apache
    AddOutputFilterByType DEFLATE text/html text/plain text/css application/json
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE text/xml application/xml text/x-component
    AddOutputFilterByType DEFLATE application/xhtml+xml application/rss+xml application/atom+xml
    AddOutputFilterByType DEFLATE image/x-icon image/svg+xml application/vnd.ms-fontobject application/x-font-ttf font/opentype
  </IfModule>
</IfModule>

```

Note that this works on MIME type, and not file extensions, so more respones from Drupal will get compressed.

# Answer
> 1 votes
Just came across this while looking for something else. I too wondered if the gzip versions of my css files were being served. I posted my findings on this here:

https://drupal.org/node/2162911

Hopefully it'll help anybody coming across this (and people can comment on its accuracy or otherwise).

---
Tags: 7, theming
---


# Question
Title: How can you force a stylesheet reload in Drupal7?
This is about that old trick of tacking a fake query argument onto the URL of a stylesheet (e.g., `<link rel="stylesheet" type="text/css" href="http://www.example.com/site.css?v=123">`) so that, when you change the stylesheet, it'll be reloaded by the users' browsers, since it looks like a URL that's not in the browser's cache.

So, the question: How can you do this in D7 where the stylesheets are specified in the .info files? I tried adding a query arg onto the entry in my site's info file -- `stylesheets[all][] = site.css?v=123` but without any luck (the page rendering got very unhappy). Any ideas?

# Answer
By default you can navigate to `/admin/config/development/performance` and select the `Clear all caches` button. Behind the scenes this will actually do what you describe by appending a new query-string to the CSS URL.
> 9 votes

# Answer
You can do this with drush

```
$ drush help cache-clear
Clear a specific cache, or all drupal caches.

Arguments:
 type                                      The particular cache to clear. Omit
                                           this argument to choose from
                                           available caches.

Aliases: cc

```

So you can do

```
drush cc css-js

```

and this will rescan the cached CSS and JS files, nuke them if they are stale, and generate a new key that gets appended to CSS and JS URLs.
> 12 votes

# Answer
Flushing the Drupal caches should take care of this issue for you.
> 5 votes

# Answer
You can see your changes made to your theme.info file by issuing the 'theme-list' cache clear Drush command:

```
$ drush cc theme-list

```

you can also add this line to theme.info to force rebuilding cache on every page load:

```
settings[clear_registry] = 1

```
> 0 votes

---
Tags: .info, theming
---


# Question
Title: In Drupal 6 is there a way to edit custom blocks of text in a quick way?
I'm working on a client site that is Drupal 6 and many of the footer/header region areas have many blocks of text created via the blocks page. Its currently very cumbersome to go into the blocks page and find which blocks they reside in. Is there a way to show a quick "edit" hover button on these text blocks? I think D7 has this but I don't think D6 has a setup for this.

# Answer
> 1 votes
Just miss read the requirements. I would add the user\_access('Administer content') condition instead of $logged\_in. Only Administer users needs to see this link. So the condition will be:`if (user_access('Administer content') && is_numeric($block->delta) && $block->delta != 0 && $block->module == 'block-block')`

# Answer
> 0 votes
I created a custom block.tpl.php and have it insert an "edit" button on every block. Currently it checks to make sure its a real block and not some other generated block via views or panels as this edit button was showing in a bunch of random places that dynamically generated a block.

```
<div id="block-<?php print $block->module .'-'. $block->delta; ?>" class="block block-<?php print $block->module ?> clear-block">

<?php if ($logged_in && is_numeric($block->delta) && $block->delta != 0 && $block->module == 'block-block'): ?>
  <em class="blk-edit"><a href="<?php print '/admin/build/block/configure/block/'. $block->delta; ?>">EDIT</a></em>
<?php endif;?>

<?php if ($block->subject): ?>
  <h2 class="block-title"><?php print $block->subject ?></h2>
<?php endif;?>

  <div class="block-content clear-block">
    <?php print $block->content ?>
  </div>
</div>

```

This was the section I added:

```
<?php if ($logged_in && is_numeric($block->delta) && $block->delta != 0 && $block->module == 'block-block'): ?>

<em class="blk-edit"><a href="<?php print '/admin/build/block/configure/block/'. $block->delta; ?>">EDIT</a></em>

<?php endif;?>

```

# Answer
> 0 votes
Nice approach by duckx. I rather use Admin permissions. like this.

```
<?php if (user_access('Administer content')) : ?>
<em class="blk-edit"
  <?php print l(t('edit'), 'admin/build/block/configure/block' . $block->delta); ?>
</em><?php endif; ?>

```

Check - https://api.drupal.org/api/drupal/modules%21user%21user.module/function/user\_access/6

---
Tags: theming, 6, blocks
---


# Question
Title: Create custom variables for a template file inside a menu callback function
here is a good one that has always stumped me.

I would love to see a solution in both D6 and D7.

I create custom modules and usually work with the menu api to create menu type -\> MENU\_CALLBACK.

Here is an example:

```
function example_menu() {
  $items['example/page1'] = array(
    'page callback'     => 'example_page1_callback',
    'access callback'   => TRUE,
    'type'              => MENU_CALLBACK,
  );
  return $items;
}

```

I would like to see the exact code solution to provide three different variables to be printed in a custom theme template based on the following code. To add to that challenge, I would like the code to be written in the menu callback function only. I know there are many possible ways to do it but could never figure out how to do it in a menu callback function which would be the most useful way.

```
//****************************************
// This code block goes in a custom module called example_menu_variables.module

// hook_menu example
function example_menu() {
  $items['example/page1'] = array(
    'page callback'     => 'example_page1_callback',
    'access callback'   => TRUE,
    'type'              => MENU_CALLBACK,
  );
  return $items;
}

// hook_meny callback function
function example_page1_callback() {
  // please provide code within this function to turn these next three
  // variables into separate output variables for the template.
  $variable_to_print1 = 'Foo';
  $variable_to_print2 = 'Bar';
  $variable_to_print3 = array('bing', 'bang', 'bong');
  return;
}
//****************************************

//****************************************
// This block of code represents the part of the custom theme template related to the menu location from the hook_menu call
// D6 template name would be page-example-page1.tpl.php
// D7 template name would be page--example--page1.tpl.php

<div><?php print  $variable_to_print1?></div>
<div><?php print  $variable_to_print2?></div>
<div><?php print  $variable_to_print3[0] . ' ' . $variable_to_print3[1] . ' ' . $variable_to_print3[2]?></div>

/*
output should look like:
Foo
Bar
bing bang bong
*/

//****************************************

```

Hope this is the kind of problem that someone wouldn't mind solving. Thanks for your time. :)

Ray James

# Answer
> 1 votes
I got this working in Drupal 7, simply by setting the variable in the render array returned from the page callback.

**In .module file**

```
function example_page1_callback() {
$render_array['variable_to_print1'] = 'Foo';
$render_array['variable_to_print2'] = 'Bar';

// set other render array items for the page

return $render_array;
}

```

**In page.tpl.php file**

```
<div class="someDiv">
  1st variable = <?php print render($page['content']['system_main']['variable_to_print1']); ?><br />
  2nd variable = <?php print render($page['content']['system_main']['variable_to_print2']); ?><br />
</div>

```

# Answer
> 6 votes
I don't believe you can do this without using `hook_theme`, but this is exactly what it's for and it's quite simple. (This code is for Drupal 6.)

```
/**
 * Implements hook_menu().
 */
function example_menu() {
  $items['example/page1'] = array(
    'page callback'     => 'example_page1_callback',
    'access callback'   => TRUE,
    'type'              => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Page callback function
 */
function example_page1_callback() {
  $variable_to_print1 = 'Foo';
  $variable_to_print2 = 'Bar';
  return theme('example_contents', $variable_to_print1, $variable_to_print2);
}

/**
 * Implements hook_theme().
 */
function example_theme() {
  return array(
    'example_contents' => array(
      'arguments' => array('variable_to_print1' => null, 'variable_to_print2' => null),
      'template' => 'example-contents',
    ),
  );
}

```

`$variable_to_print1` and `$variable_to_print2` are now available in `example-contents.tpl.php`.

# Answer
> 2 votes
The code written by Adam is correct (my +1) Your variables are available in example-contents.tpl.php file - it is a template file of your module output.

However, if you need these variables in page.tpl file, then you can just create them:

**in your module file:**

```
/**
 * Page variables
 *
 * @return
 *  custom page variables
 */
function custom_variables(){

  $variable_to_print1 = 'Foo';
  $variable_to_print2 = 'Bar';
  $variable_to_print3 = array('bing', 'bang', 'bong');

  return array( 'variable_to_print1'    => $variable_to_print1,
                'variable_to_print2'    => $variable_to_print2,
                'variable_to_print3'    => $variable_to_print3
  );
}

```

**in your template.php file:**

```
/**
 * Override or insert variables into the page templates.
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("page" in this case.)
 */
function YOURTHEME_preprocess_page(&$variables, $hook) {

  // pass your module variables to page--example1.tpl.php file
  if (in_array('page__example1', $variables['theme_hook_suggestions'])){
    if (module_exists('your_module')){
        $your_module_variables = custom_variables();
        $variables['variable_to_print1'] = $your_module_variables['variable_to_print1'];
        $variables['variable_to_print2'] = $your_module_variables['variable_to_print2'];
        $variables['variable_to_print3'] = $your_module_variables['variable_to_print3'];
    }
  }
}

```

# Answer
> 1 votes
Had same problem, this is what worked for me on Drupal 7.x

```
function example_menu() {
  $items['example/page1'] = array(
  'page callback'     => 'example_page1_callback',
  'access callback'   => TRUE,
  'type'              => MENU_CALLBACK,
  );
return $items;
}

function example_page1_callback() {
  $variable_to_print1 = 'Foo';
  $variable_to_print2 = 'Bar';
  $variable_to_print3 = array('bing', 'bang', 'bong');

  //use below given statement when you only want to pass one variable
  // to your template
  //return theme('example',array('output'=>$variable_to_print1));

  //use this statement when you want to pass array
  return theme('example',array('output' => $variable_to_print3));
}

```

In addition to all this you need a example\_theme() hook

```
function example_theme(){
    //lets say your template file is called example.tpl.php and it resides
    //within your module directory.
    $custom_example_template = array();

    $custom_example_template['example'] = array(
        'template' => 'example',
        'variables' => array('output' => NULL)
    );
}

```

Now what about your example.tpl.php

```
<div id='someotherid'>
    <?php
             //use this code when you have passed only one variable
             print $variables['output'];
    ?>
</div>

```

You can name your variables whatever you want, you don't need to stick with 'output' as I did. For some reason you can't see my foreach loop to loop through the array we have passed.

# Answer
> 0 votes
I got Jack's method to work, although I must say the render\_array idea is simpler. Here's what worked for me:

In Module:

```
//page callback to create the page and include some CSS & Javascript
function my_callback() {
   drupal_add_css(...);
   drupal_add_js(...);
   return '';
}

function _my_module_vars(){
   $var1 = 'foo'
   $var2 = 'bar'
}

```

In theme's Template.php

```
function MYTHEME_preprocess_page(&$vars) {
   //add some custom variables to the module page
    if(in_array('page__my_content_type', $vars['theme_hook_suggestions'])) {
       if(module_exists('my_module')) {
          $my_vars = _my_module_vars();
          $vars['var1'] = $my_vars['var1'];
          $vars['var2'] = $my_vars['var2'];
    }
  }
}

```

In page.tpl.php (or you could use page--my\_content\_type.tpl.php):

```
print $var1;
print $var2;

```

---
Tags: theming, routes
---


title: Issue in clearing cache

text:
# Question
Title: Issue in clearing cache
i have added modules to my website , but now when i want to open modules from admin section its showing blank and i am getting PDOException: SQLSTATE\[42S02\]: Base table or view not found:

# Answer
> 1 votes
Check in your database

1.If cache\_views table is exist or not .if not exist import this table

```
CREATE TABLE IF NOT EXISTS `cache_views` (
  `cid` varchar(255) NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique cache ID.',
  `data` longblob COMMENT 'A collection of data to cache.',
  `expire` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.',
  `created` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry was created.',
  `serialized` smallint(6) NOT NULL DEFAULT '0' COMMENT 'A flag to indicate whether content is serialized (1) or not (0).',
  PRIMARY KEY (`cid`),
  KEY `expire` (`expire`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Generic cache table for caching things not separated out...';

```

# Answer
> 0 votes
Have you run update.php? May be your module need database updates. Try www.yourdomain.com/update.php

---
Tags: views, caching
---


# Question
Title: Wrong text being shown in a template file
When I add text in Hebrew inside html.tpl.php, it shows me strange characters instead of the ones I am expecting.

How can I fix this?

# Answer
> 3 votes
You need to set the encoding of new files to utf-8 in your text-editor. The image below is on Notepad++. There should be a similar setting in your text editor.

To test if you got it right, create an HTML/PHP file with the Hebrew text outside of Drupal first.

For Notepad, `Save As` and select `UTF-8` as the `Encoding`.

Also, make sure you have the following line in the `<head>` tag of your HTML:

```
<meta charset="utf-8">

```

---
Tags: theming
---


# Question
Title: How to load the images in views using ajax?
There is a website with rich content (high resolution images).

I wish to load that view block contents (3 view blocks), but not the image, during the page load. Image should load in AJAX after the page load, without any external DOM element trigger. How can I achieve that?

### Note

The whole point is increasing the performance without giving up on the functionality.

# Answer
Check out Image Lazy loader module

> This is a small helper module which will automatically lazyload all images for sites with multiple images, which will make the site load faster.
>
> All images will only load when it's visible to the browser window.
> 3 votes

---
Tags: views, blocks, ajax, media, performance
---


# Question
Title: How to make the submit button not appear on form unless an option is selected from radios?
I have a form with three form elements:

1. `'#type' => 'radios'` element having two options (Yes or No),
2. `'#type' => 'submit'` &
3. `'#type' => 'checkbox'`

When the user lands on the form page, he should only see the `radios` element first and can see the `checkbox` & `submit` elements only if he selects an option from `radios` element.

Is there a Drupal way to do this using the Form API?

# Answer
> 4 votes
You can use #states attribute in form api to hide submit button and check box

For Example

```
$form['email_canceled']['settings'] = array(
    '#type' => 'container',
    '#states' => array(

      // Hide the settings when the cancel notify checkbox is disabled.

      'invisible' => array(

       ':input[name="email_canceled_toggle"]' => array('checked' => FALSE),
      ),
    ),
  );

```

---
Tags: 7, forms
---


# Question
Title: Failed validation redirects to normal path
I'm using the sub-pathauto module.

I can edit *node 1* of type *list* from the path *list/1/edit*. However, when validation fails I'm redirected back to *node/1/edit* (the normal path).

Is this a known limitation of the module? Something I have to accept?

# Answer
> 0 votes
In your custom module add below code,It check If url not in alias path, redirect it to aliased path.

```
function mymodule_init() {
    if(module_exists('subpathauto'){
  $alias = subpathauto_lookup_subpath('alias', current_path(), current_path());
  if (!empty($alias) && $alias != request_path()) {
    drupal_goto($alias, array(), 301);
  }
 }
}

```

---
Tags: path-aliases
---


# Question
Title: Render fields in node template with different view mode
I have some fields for nodes. I hide the content and render fields separately as below.

```
hide($content);
print render($content['field_01']);
print render($content['field_02']);
print render($content['field_03']);
print render($content['field_04']);
print render($content['field_05']);

```

I set different field formats in content type at Manage Display" like field\_01 is an image and i set large image in Full Content and Thumb image in Teaser view mode. field\_02 is a taxonomy reference field which i set Link in Full Content and Plain Text in Teaser view mode.

When i render fields in node template, all fields render as view mode "Full". Now i want render all fields from default view mode "Full". Only I want to render field\_01 & field\_02 from Teaser view mode.

# Answer
> 2 votes
> Let me give you an example. I have one `date field` into my `content type`. Now I want to render that field twice. For getting that that i will print the output as `Birthdate : Feb 22, 2006` for first instance and for second I want to print `Age : 7 yrs old`. In `manage display` I have format `to date` as well as `Time ago` and I want to use both format.

The easiest way to do this would be to create a second variable in your `theme_preprocess_node()` function, pull out the value that you want to format a second time, format it differently, and then print the variable where you want to see it a second time in your `template`. Dates are particularly easy to format using the `format_date()` function, so you don't need to use a different `views mode` to achieve this.

In your theme's `template.php` file add something like;

```
function mytheme_preprocess_node(&$variables) {
  $node = $variables['node']; // Nice shorthand.
  $lang = $node->language; // Shorthand again.
  $variables['new_date'] = format_date($node->field_date[$lang][0], 'medium');
}

```

Then in your `node--whatever.tpl.php` file print it out like;

```
<div class="time-ago"><?php print $new_date; ?></div>

```

# Answer
> 1 votes
You can write a small module and implement hook\_node\_view to alter what fields are displayed in another view mode.

If thats too much custom coding modules like Display Suite let you easily create new `view_modes` or field display formatters with little or no code.

**EDIT:**

the Template you're refering to renders after the hooks and node loading occurs for the node. Thats why the template just does `render($content['field_01'])`. To change how `field_01` looks you have to alter/configure its desired output view prior to hitting the template. Thats what the hook(s) and for instance DS let you do.

# Answer
> 1 votes
It is a little hard to tell exactly what you are trying to achieve, but if you only want to print some fields when in the teaser mode you can do something like this:

```
// Only print fields 1 & 2 for teasers.
if ($view_mode == 'teaser') {
  print render($content['field_01']);
  print render($content['field_02']);
}
// Print these fields always.
print render($content['field_03']);
print render($content['field_04']);
print render($content['field_05']);

```

It's worth noting though that you could just set the fields to hidden via the display settings UI instead of this.

Or do you mean you want all the fields to always display, but you want them to use your teaser display settings for the first 2 fields even when viewing the full version?

If that is the case, just change the display settings for those fields for the default view mode via the display settings UI. I don't see why you should need any custom code to achieve this.

# Answer
> 0 votes
Instead of using render simply use node\_view instead:

```
print node_view($node, $view_mode = 'teaser');

```

The node should be available in the node template, if using this outside of the node template you will need to get the node object.

So in the above example we are assuming that your teaser view mode shows only field 1 and 2 or whatever fields you want. If not then make a view mode that displays what you want and render it according to that.

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


title: Issue with drupal cache

text:
# Question
Title: Issue with drupal cache
I have developed website using drupal 7. I created block using Views Slideshow Cycle. I uploaded the site to server. The slideshow not displayed in live site. But after clearing cache(using configuration-\>Development-\>Performance) the slideshow is visible.The problem is that i need to clear the cache frequently to display the slideshow. **The below image is the site without slideshow.**

**This is the site with slideshow after clearing cache.**

I am also having hidden fields using field permission. That are also visible to anonymous users. But I gave the field view permission only to authenticated users. Those fields are hidden for anonymous user after clearing cache.
I didn't enabled cache pages and cache blocks. But the site in my local system does not have this issue. These issue only with my live site. My hosting server is apache.
I have this problem for a month. Please suggest me a solution

# Answer
> 1 votes
There is an issue when views, javascript and caching are used in combination. Some information that may be of help:

https://drupal.org/node/1873970 https://drupal.org/node/1811828 https://drupal.org/node/1984774

As far a I can understand the cached page or block cause the js to fail. In another answer it is stated:

> This may be a timing issue, flexslider may require the images to be loaded when it is called so it can work off their attributes, remember that $(document).ready() fires after the DOM has finished loading whilst $(window).load() fires after all images on the page have loaded \- giving you intermittent results if they are cached etc, replace:
>
> $(document).ready(function(){ ... }); with
>
> $(window).load(function(){ ... });

I have not found a sure fire answer /solution to the issue and may broaden out the question to see if there is an advised fix for views+cache+js=problem.

---
Tags: entities, blocks, caching, views
---


# Question
Title: Notice: Undefined index: highlighted in include() (line 124 of page.tpl.php
I keep getting this error in a fresh drupal install with fusion and a custom fusion subtheme:

```
Notice: Undefined index: highlighted in include() (line 124 of /home/username/public_html/modules/system/page.tpl.php).

```

Would anyone happen to have any clue as to what is causing this?

# Answer
If I am correct highlighted is a region name and you might have not defined it in you theme info file which is why it is throwing this error.

Give me more details of your info file and your page tpl file so that I can guide you in a better way.
> 1 votes

# Answer
In case anyone face the same issue :

Search for any "\*.info" file in your drupal repo that has no line similar to "name = xxxx".

The "\*.info" file might be outside of your themes.

For instance, my problem was due to a file named "lcov.info" in a grunt module (grunt-svgmin) in my theme. I happended "name = lcov is not a theme" at the beginning of the file and the issue fade away. I'll check svg-min later.

for more, see https://drupal.stackexchange.com/a/105233/26878
> 1 votes

---
Tags: theming
---


# Question
Title: How can I select a set of nodes directly linked to a node using views and wikitools
I'm a newbie with Drupal so I apologize if my question is not presented appropriately, I'll try to be as specific as possible.

So I am developing an academic wiki using Wikitools (gathering academic information such as papers, economic data, etc.). The two types of content I will mention here are (i) Articles - each article presents an academic paper written by one or several authors; and (ii) Authors - a page presenting a particular author/researcher and providing internal and external links related to the researcher (e.g. his website, videos, etc.).

What I would like to do is to select all the Article pages for which a researcher is categorized as an author and display them in the Author page corresponding to that person.

I tried to do that with Views: I created a view, filtered using 'Content type' (i.e. Articles) and 'Links to' as criteria. The view has been integrated into the Author page and links have been established between Article pages and the Author page using Wikitool link format (\[\[name|name\]\]).

However, no article pages get displayed in the Author page. I removed the 'Links to' criterion to see what would happen, and all article pages created get displayed. So the view is working correctly but it seems that the links created using the Wikitool format are not recognized as actual links. It's the only explanation I could think of so far, and I could not find any hint in other forums.

So if you guys have any idea, I would really appreciate some help... I'll stay posted to provide additional details if needed.

Thanks a lot for the awesome work you're all doing. I've just discovered Drupal and I still can't believe how innovative and well-designed the whole project is.

Cheers, Igor

# Answer
So I found a very simple solution to my problem: I used a contextual filter (in Views) and a Node Reference. Each Article page is linked to corresponding Author page(s) using a node reference. Then using a Contextual Filter in Views, I was able to select all articles written by a given author and display them in the author's page.

I'll give additional details on how to set up the contextual filter, even though it might seem simple to experienced users, new users like me might find the information useful. To set up the contextual filter for the task I described, I selected: 'Provide default value' ('Content ID from URL'), then 'Override title' (and I entered "Articles mentioning %1" in the blank space), 'Specify validation criteria' ('Content', 'Author pages') and 'Node ID' as filter value format.

I don't know whether it can be helpful to someone else but I would have saved a lot of time if I had found that information earlier... :)
> 0 votes

---
Tags: views, navigation
---


title: Help with Pager

text:
# Question
Title: Help with Pager
I am using the Drupal 7 and i want to use the Pager into my query

This is my query and the way i can use

```
$qury = db_select("SELECT `entity_id` , `field_keywords_value` , COUNT( DISTINCT ( `entity_id` )) total
FROM `field_data_field_keywords`
WHERE `bundle` = 'song'
GROUP BY `field_keywords_value`");

$query = $qury->extend('PagerDefault');
        $result = $query
  ->extend('PagerDefault')
  ->limit(2)
  ->execute();

```

but it give me the error, PDOException: erro

And if i can use it in the following way:

```
$qury = db_query("SELECT `entity_id` , `field_keywords_value` , COUNT( DISTINCT ( `entity_id` )) total FROM `field_data_field_keywords` WHERE `bundle` = 'song'
                GROUP BY `field_keywords_value`");
$query = $qury->extend('PagerDefault');
$result = $query
  ->extend('PagerDefault')
  ->limit(2)
  ->execute();
echo "<pre>";
print_r($result);
die('tert');

```

Then my page not working and give me the blank page.

Any help will be appreciated.

# Answer
> 4 votes
First check which Drupal version you are using

if using Drupal 7 the use see below given example

```
    <?php
$result = db_select('table_name', 'table_alias')
    ->fields('table_alias',array('column_name1', 'column_name2', 'column_name1', .....))//SELECT the fields from user
    ->condition('type', 'article')
    ->extend('PagerDefault')
    ->limit(10)  // Set the limit per records
    ->orderBy('created_date', 'DESC')//ORDER BY created or
    ->execute()
    ->fetchAssoc();
?>

```

See more example at

http://api.drupal.org/api/drupal/includes!database!database.inc/function/db\_select/7

# Answer
> 1 votes
Check examples module how pager is given in this.

You are using select in select query. So its giving exception error.

For running SQL queries as it is, use db\_query(). ex:- db\_query("select emmpno from emp") For running db\_select() we need to follow Drupal standards. ex:- $query=db\_select('emp','e'); $result=$query-\>fields()-\>execute();

No select in a select.

# Answer
> 1 votes
An example Drupal 7 query with joins, conditions, limit and pagination:

```
$query = db_select('table_name1', 't1');
$query->join('table_name2', 't2', 't.id = t2.tid');
$query
->fields('t1', array('column1', 'column2', 'column3'))
->fields('t2', array('column1'))
->condition(db_or()->condition('t1.column2', '%' . db_like($match) . '%', 'LIKE')
                              ->condition('t2.column1', 'string', '=')
);

if($user->uid > 0) { $query->condition('t2.column2', '1', '='); } // only for logged in user

$query->groupBy('t1.id');
$search_results = $query->extend('PagerDefault')->limit(5)->execute(); // set pagination

```

# Answer
> 0 votes
I have resolved the problem bye my self

```
 $query = db_select('field_data_field_keywords')->extend('PagerDefault');
 $query->fields('field_data_field_keywords', array('field_keywords_value', 'entity_id'));
 $query->condition('bundle', 'song');  $query->condition('field_keywords_value', arg(2));
 $query->distinct('entity_id');
 $result = $query ->limit(1)->execute()->fetchAll();

```

hope this is helpful for someone who is new in D7.

# Answer
> 0 votes
// $list is the list of items you are paging through

$list = array ('Cat','Dog','Mouse','Horse','Pony','Winged mongoose'); $per\_page = 2;

// Initialise the pager

$current\_page = pager\_default\_initialize(count($list), $per\_page);

// Split your list into page sized chunks

$chunks = array\_chunk($list,$per\_page, TRUE);

// Show the pager

print theme('pager', array('quantity',count($list)));

// Show the appropriate items from the list

print theme('item\_list', array( 'items' =\> $chunks\[$current\_page\], ));

---
Tags: 7, paging
---


# Question
Title: Drupal mail problem - Greylisting in action
I'm not sure how to solve this one and even not sure if it's a drupal issue or misconfiguration.

I'm running a Drupal site (7.22) and have huge problems with the sending mails. Most of the mails can't be delivered and I (the admin) get immediately a Mail Delivery System message:

> This is the mail system at host OUR\_MAIL\_HOST.
>
> I'm sorry to have to inform you that your message could not be delivered to one or more recipients. It's attached below.
>
> For further assistance, please send mail to postmaster.
>
> If you do so, please include this problem report. You can delete your own text from the attached returned message.
>
> ```
>               The mail system
>
> ```
>
> : host
> USER\_MAIL\_HOST said: 450 4.7.1
> : Client host rejected: Policy Rejection- Greylisting in action; Please try again later. (in reply to RCPT TO command) Reporting-MTA: dns; OUR\_MAIL\_HOST X-Postfix-Queue-ID: D8047189CE9 X-Postfix-Sender: rfc822; admin@mail Arrival-Date: Wed, 26 Feb 2014 08:22:24 +0100 (CET)
>
> Final-Recipient: rfc822; user@mail Action: failed Status: 4.7.1 Remote-MTA: dns; USER\_MAIL\_HOST Diagnostic-Code: smtp; 450 4.7.1 \< OUR\_MAIL\_HOST\[OUR\_MAIL\_HOST\_IP\]\>: Client host rejected: Policy Rejection- Greylisting in action; Please try again later.
>
> The original mail content...

So to get a mail through this greylisting-filter requires sending the mail again, but I don't know whether it should be done via Drupal or via the mail server? The admins of the mail server told me to send the mail again, but this means, I have to tell Drupal to send each mail twice if it gets greylisted. This sounds pretty odd to me and I'm sure there is a clean solution. So any ideas? I'm sure I'm not the only one with such a problem.

# Answer
In your setup PHP `mail()` sends mail, but it's your mailserver who gets "false rejection" notification - possibly a different machine, and even if the same machine, it's totally separate system. PHP `mail()` never receives anything, so it can't resend. And your mailserver never sent it, so it can't resend, either.

Simplest way to fix it is to use SMTP module

> This module allows Drupal to bypass the PHP mail() function and send email directly to an SMTP server. The module supports SMTP authentication and can even connect to servers using SSL if supported by PHP.

PHPmailer module

> The main differences to the SMTP module are:
>
> * Integration with Mime Mail module
> * Improved bulk-mail performance through SMTP keep-alive connections (if supported by the mail server)
> * Built-in e-mail rerouting option (useful during site building and development)

or similar solutions, there are a few more.

That way your Drupal will only need to send mail once, and your outgoing mail server will take care about graylists - most of them are configured in a way that works with graylist receiving servers out of the box.
> 2 votes

---
Tags: emails
---


# Question
Title: How do I paginate results with db_query?
How do I paginate results with `db_query` in Drupal 7? I didn't find any example using `db_query`.

# Answer
`db_select()` is the way to go using a so called query extender. Here is a simple example:

```
$query = db_select('node', 'n')
  ->condition('type', 'article')
  ->extend('PagerDefault')
  ->limit(10);

```

Then `theme_pager()` can be used for outputting a pager.

Find more details on this drupal.org working example
> 8 votes

# Answer
The following code works successfully for me.

```
$limit = 10;
$start = isset($_REQUEST['page']) ? $_REQUEST['page'] * $limit : 0;
$query = "<your query>";
$count_query = "<count query>";//count(*) AS total
$count_result = db_query($count_query);
$query_items = db_query_range($query,$start,$limit);
$items = $query_items->fetchAll();

pager_default_initialize($count_result->total, $limit, $element = 0);
$pager = theme('pager',array("quantity"=>5));
return theme("<page-theme>",array("items"=>$items ,"pager"=>$pager));

```
> 6 votes

# Answer
This worked for me:

```

  // $list is the list of items you are paging through
  $list = array('Cat', 'Dog', 'Mouse', 'Horse', 'Pony', 'Winged mongoose');
  $per_page = 2;

  // Initialise the pager
  $current_page = pager_default_initialize(count($list), $per_page);

  // Split your list into page sized chunks
  $chunks = array_chunk($list, $per_page, TRUE);

  // Show the pager
  print theme('pager', array('quantity', count($list)));

  // Show the appropriate items from the list
  print theme('item_list', array(
      'items' => $chunks[$current_page],
  ));

```
> 0 votes

---
Tags: 7, database
---


title: Site logo display is low quality

text:
# Question
Title: Site logo display is low quality
My site logo looks pixelated even though the image has been sized exactly. When I open the image url in a separate window, the quality is as per expected, however, the display on the site is low quality. Is there any settings I should be tweaking in Drupal?

# Answer
> 0 votes
After a lot of trial and error, I realised that as long as the image goes through processing by Drupal, it's resolution somehow deteriorates during the process. As the issue with the site logo was a client complaint, I chose to bypass Drupal processing altogether by replacing site logo with site title, then applying text-indent: -9999px and background: url("../logo-image.png") to render the logo instead.

---
Tags: files
---


title: Best way to create HTML meta tags?

text:
# Question
Title: Best way to create HTML meta tags?
**Issue**

Users will input text that need to be copied into (hidden) meta tag fields when the user have written them into normal fields on the input node.

What I am looking for is either a module to help me with this, a user guide to doing it or an alternative solution to the issue described in the background.

**Background**

I need to use Meta tags quick to annotate user submitted content on my website.

The user submit article information in normal fields (ie for example an Author field exposed on any node with the article content type). My plan is to to use the Meta tags quick module to create hidden fields and then have those fields filled in by copying content from the user input fields.

An alternative is of course to use the Metatag module but I find it harder to work with and I also need to copy some other fields.

# Answer
You can metatags from fields on the node with

`hook_preprocess_html`

e.g

```
/**
 * Implements hook_preprocess_html
 */
function THEME_preprocess_html(&$variables){
  // Only add on node pages
  if($node = menu_get_object('node')){
    // Read node fields, wrapper requires entity api module
    $wrapper = entity_metadata_wrapper('node', $node);
    if(isset($wrapper->field_some_field)){
      if($some_content = $wrapper->field_some_field->value()){
        $element = array(
          '#tag' => 'html_tag',
          '#type' => 'meta',
          '#attributes' => array(
            'name' => 'some-metatag',
            'content' => $some_content,
          ),
        );
        drupal_add_html_head($element, 'some_metatag');
      }
    }
  }
}

```
> 3 votes

# Answer
I don’t know the **Meta tags quick** module, but according to this comparison it seems to support tokens.

So the same method that works for **Metatags** should work for **Meta tags quick**, too:

Take the token of the field and set it as content for the meta tag.
> 1 votes

# Answer
Mmmh.. You're issues is not really detailed so I will give a general answer.

```
function yourmodule_form_alter(&$form, &$form_state, $form_id){
  if( $form_id == 'your form id' ){

    $form['field_B']['#access'] = FALSE;
    $form['#validate'][] = 'yourmodule_validate';

  }
}

function yourmodule_validate($form, &$form_state) {

    $field_A_value = $form_state['values']['field_B']
    $form_state['values']['field_B'] = $field_A_value;

}

```
> 0 votes

---
Tags: 7, meta-tags
---


# Question
Title: How can I use an URL (being a field content) as a contextual filter in views?
I'm working on an academic wiki containing two types of pages: **an 'Author page' and an 'Article page'**. I am trying to create a **block view displaying all the articles written by an author into her corresponding page**. The view selects the 'Article pages' using a content type filter and I tried to use contextual filters to select the articles written by a particular author.

The difficult part is that the 'Author page' and the 'Article page' do not share a similar field for the author's name. However, **when creating an 'Article page', the user has to enter all participating authors and the URLs corresponding to their respective page** in the wiki.

So what I would like to do is to **use the last component of this URL (the node ID of the 'Author page') and compare it to the node ID of the page the user is looking at**. If the IDs match, the view displays selected fields from the 'Article pages' which have written by the author the user is looking at. But so far I have been unsuccessful in doing so, any hint on how I could perform this functionality?

I'm new using Drupal (and site building actually), so I apologize if my question lacks clarity or details.

Thanks in advance for your help!

Igor

# Answer
I found a much simpler solution than what I was trying to do: I used node references. That's exactly what I needed but I wasn't aware of the existence of this functionality. So yes, the solution is simply to use a node reference to link the 'Article page' to the 'Author page'.
> 0 votes

# Answer
I had a similar issue a while ago. I understand that you have already solved the issue for yourself but I think a reply may help other who stumble here through Google.

To set the contextual filter you need to add the Relationship, "Content: Author" (this is located under the advanced tab when creating the view).

The add a Contextual filter "User: Uid". When making the filter you also need to set the following option:

Under **When the default value is not available**

Provide deault value of type "User ID from URL".
> 0 votes

---
Tags: views
---