# Question
Title: Can't get Varnish working properly, not caching anything. (varnishd is running , status is tick)
System info:

* Ubuntu / LAMP
* Drupal 7.14
* Varnish 3.0.2
* Varnish module: 7.x-1.0-beta1
* http port 80

I have installed Varnish in server.

I started it as:

```
$ sudo varnishd -f default.vcl -s malloc,1G -T 127.0.0.1:2000

```

varnishd started and running.

default.vcl details (from this page: https://www.varnish-cache.org/trac/wiki/VarnishAndDrupal)

```
backend default {
    .host = "127.0.0.1";
    .port = "80";
}

sub vcl_recv {
  // Remove has_js and Google Analytics __* cookies.
  set req.http.Cookie = regsuball(req.http.Cookie, "(^|;\s*)(__[a-z]+$
  // Remove a ";" prefix, if present.
  set req.http.Cookie = regsub(req.http.Cookie, "^;\s*", "");
  // Remove empty cookies.
  if (req.http.Cookie ~ "^\s*$") {
    unset req.http.Cookie;
  }

  // Cache all requests by default, overriding the
  // standard Varnish behavior.
  // if (req.request == "GET" || req.request == "HEAD") {
  //   return (lookup);
  // }
}

sub vcl_hash {
  if (req.http.Cookie) {
    hash_data(req.http.Cookie);
    return (hash);
  }
}

```

Vanish module enabled.

Following conf added to settings.php

```
$conf['cache_backends'][] = 'sites/all/modules/varnish/varnish.cache.inc';
$conf['cache_class_cache_page'] = 'VarnishCache';
$conf['page_cache_invoke_hooks'] = FALSE;

```

Varnish module configuration page screenshot:

Performance page screenshot:

Then I browse my site. (as anonymous), repeatedly refresh various pages. Checked stats of varnish

```
$ varnishtop

```

apparently it is **not receiving any request**, not caching anything.

Also check the site on http://www.isvarnishworking.com/ , shows Vanish is not working on the site.

---

**What is wrong?**

**Thanks for any help.**

# Answer
By default, Varnish is not working on port 80 (and in this case it could not be either since your Apache is occupying that port). You should configure your Apache to listen to another port, then use that port for your backend setup in Varnish. You should also configure Varnish to listen to port 80.

To debug, you should try to figure out what port your Varnish is listening to now and browse using that port, then you should see traffic in varnishtop.

The reason I'm being vague on the varnish configuration is that I have only used Varnish on CentOS which reads in the startup defaults from /etc/sysconfig/varnish - since you are using Ubuntu you should try to find out where that default configuration is being kept on your system. A fair starting point might be the /etc/init.d/varnishd script which might give some clues.
> 3 votes

---
Tags: caching, proxies
---


# Question
Title: Show teasers to anonymous visitors but not allow access to the body/node
I want to encourage visitors to create an account by allowing them to read the teasers on the front page and know that creating an account is worth their effort to access the rest of the content.

i'm using v7.x

P.S. *I also hope this will enable Search engines to see enough content to index properly*

# Answer
One way to do this is to use Panels. Override the front page and the default node template; create two variants for each, one for anonymous and one for authenticated users (using selection rules).

Then, for the front page for anonymous users, only use teasers and remove the links to the full content. For the anonymous node template, limit everything to teasers.

For authenticated users, enable everything just as you'd like them to see it.

Note: this is not a full tutorial on Panels, but should hopefully provide some hints to get you started.

* Keep in mind that doing this will cut the search engines off from your non-teaser content as per Clive's comment.
> 2 votes

# Answer
The Premium content module allows you to restrict access to the content body by role, but show teasers to all.

From the project page:

> This is useful on a news or membership site where teasers are available to the general public but the full body is only available to privileged users. Premium nodes appear in listings with full title and teaser available to anyone. If a user does not have adequate privileges, the default behavior is to show a simple message, but you can use Panels or theme overrides to do more custom things.
> 2 votes

# Answer
Sadly, Drupal's node access rights system does not support such granularity.

But, using an implementation of `hook_node_view_alter()` to alter the renderable array used to view a node in any context that uses `node_view()` (like the /node/%nid pages do), you can ensure that anonymous users don't have access to full view of a node (ie. `$build[view_mode] == 'full'`). To disable an element, simply set it `#access` property to `FALSE`. For some of them (`body`), it should also be possible to alter the theme variable to, for instance, render them as teaser text (vs. full text).

In order to support full content indexation by *external* search engine (such as Google), you will need to disable page caching. Otherwise, a search engine indexer may see an incomplete page generated for a *normal* anonymous, or the reverse. You also have to find a way to instruct Drupal to produce an *authenticated user* page when the request comes from a search engine indexer. If you use custom code to disabled full rendering of the body (like I suggest), you can do this be having a condition that only filter out anonymous users who are not indexers. Another solution may be to find a trick to lure Drupal into automatically logging search engine bot as *special* authenticated user (but I don't known how).
> 0 votes

---
Tags: 7, users, nodes
---


# Question
Title: Image in View with Lightbox2 formatter lacking alternative text tag
I have a page view for image gallery. It has only 1 *Photo* field of *Photo* which has a field of type *Image*. In view it use "*Lightbox2: lightshow: small-square -\> large*" as formatter. **small-square** is a custom image style.

The rendered page doesn't show any alt tag:

```
<img typeof="foaf:Image" src="http://www.example.com/sites/default/files/styles/small-square/public/6486388587_61846b6d84_1323732945.jpg" width="240" height="240">

```

# I need to add **alt** tag to images. What do I have to change?

My drupal installation has these versions:

* **Drupal** 7.10
* **Lightbox2** 7.x-1.0-beta1
* **Views** 7.x-3.0-rc3

looking at Lightbox2 modules's file **lightbox2.formatter.inc** it seems that alt tab should be forced to show, using image title.

```
  // Set up the title.
  $image_title = $item_data['description'];
  $image_title = (!empty($image_title) ? $image_title : $item_data['title']);
  $image_title = (!empty($image_title) ? $image_title : $item_data['alt']);
  if (empty($image_title) || variable_get('lightbox2_imagefield_use_node_title', FALSE)) {
    $node = node_load($node->nid);
    $image_title = $node->title;
  }

  $image_tag_title = '';
  if (!empty($item_data['title'])) {
    $image_tag_title = $item_data['title'];
  }

  // Enforce image alt.
  if (!empty($item_data['alt'])) {
    $image_tag_alt = $item_data['alt'];
  }
  elseif (!empty($image_title)) {
    $image_tag_alt = $image_title;
  }  $image_tag_alt = '';
  if (!empty($item_data['alt'])) {
    $image_tag_alt = $item_data['alt'];
  }
  elseif (!empty($image_title)) {
    $image_tag_alt = $image_title;
  }

```

So... where is the error?

# Answer
> 1 votes
For people coming to this page...I wanted to use the title of the node containing the image as the caption on the lightbox2 image, which I was displaying in a view, but I didn't want to modify the module, which I think is the issue with the above technique.

What I ended up doing was making my own image formatter. Basically I cut and pasted the hook\_field\_formatter\_info and hook\_field\_formatter\_view from the lightbox2 module and modified them. There may be a better way, but it works, solved my problem, and I can upgrade lightbox2 without worrying about breaking my site.

```
/**
 * Implementation of hook_field_formatter_info().
 */
function mymod_field_formatter_info() {
  $formatters = array();
  if (module_exists('image')) {
    $formatters["mymod_custom_formatter"] = array(
      "label" => "Field formatter for my Photos",
      "field types" => array("image"),
    );
  }
  return $formatters;
}

/**
 * Implements hook_field_formatter_view().
 */
function mymod_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  $pieces = explode('__', "lightbox2__lightbox__thumbnail__large"); // forced this, you could do something trickier, but it solved my issue

  ... untouched ...
  foreach ($items as $delta => $item) {
    // here is the bit I added which sets the node title to be the image caption
    if ($entity_type == 'node') {
      $item["title"] = $entity->title;
    }

    $uri = array(
    ... etc ...

```

# Answer
> 0 votes
I solved this adding a patch to `lightbox2/lightbox2.formatter.inc`. This get title from node if image's title/alt is not defined.

```
function theme_lightbox2_image($variables) {
  $path = $variables['path'];
  $item = $variables['item'];
  $image_style = $variables['image_style'];
  $node_id = $variables['node_id'];
  $field_name = $variables['field_name'];

  // PATCH Start
  if (!isset($item['title'])) {
      $node = node_load($variables['node_id']);
      $item['title'] = $node->title;
  }
  if (!isset($item['alt'])) {
      $item['alt'] = $item['title'];
  }
  // PATCH End

```

---
Tags: 7, views, entities, javascript
---


# Question
Title: Can Views output clean URLs from titles with quotes, and other special chars?
I have a view that really needs some nice clean URLs; the links are the titles of the content items in the view.

I am pretty sure I have been able to clean up URLs with views before (I could be wrong though), but I just can't seem to find it today.
Removing spaces is simple enough but I need more.

Any help greatly appreciated.

# Answer
If you are loading nodes they will already have a path associated with them. Assuming you have setup path aliases (url aliases), and potentially url patterns with the pathauto module) for these nodes there will already be a field (Content: Path). This field will contain a clean and tidy url you can add which will give you the path to these nodes. If you just want the node title to be linked to itself there is an option to 'Link this field to the original piece of content' when you add 'Content: Title'.

tl;dr Try to keep this stuff out of Views and add the relevant fields that are already available.
> 1 votes

---
Tags: 7, views, uri
---


title: Fill Blocks from Ctools Page Manager

text:
# Question
Title: Fill Blocks from Ctools Page Manager
I am using Panels 3 and Ctools to structure my pages and pass arguments both via context as well as inputs on pane settings (fixed text as well as keyword substitutions). The "input on pane settings" is very important to me.

I need to fill some block regions from the theme, and if possible I would like to do this via the page manager in order to keep selections and variants in one place.

I am aware of mini-panels and that they can be placed in blocks. But they would require to replicate all selection and context logic from the ctools page manager.

Panels Everywhere seems to go quite deep and I cannot predict whether it will actually allow me to modify the existing non-PE theme within a reasonable time.

Alternatively, I was thinking of modifying the theme's CSS and adding css-classes in page manager or to use javascript to replace the blocks with regular panes. Unfortunately, this would require separate variants per theme.

Are there any suggested ways to fill blocks from the page manager? I am using D6, but suggestions for D7 are good as well.

**Clarification**: I am looking for ways for filling a themes' block regions (eg. sidebars, headers etc.) from the page manager, in contrast to eg. mini-panels added and configured on the blocks screen. I am now trying to backport bricks, but ideally the block content should be defined within page manager.

# Answer
If you are using Panels and Page Manager successfully (they share a common interface for many capabilities) you are well on your way to getting this together. Your question does not indicate if you are using views. Adding its functionality to your setup in conjunction with Panels/Page Manager is important for gaining the control you need.

First, enable View Content Panes module in the Ctools Suite. Content panes work similarly to blocks, but are 'smarter' and handle context information passed from Panels/Page Manager. To define a content pane in views, select the add button in views and the content pane option will be available. You define a content pane similarly to a views block (you can learn more by viewing 'Taming the Beast'). Once defined, your content panes will show up in Panels/Panel/variant/content/add-content menu just as blocks and other content types do already.

Mini Panels are also similar to blocks plus they accept contexts from Panels/Page Manager and they have the ability to subdivide the content of a block in a specific layout. LIke panel pages, they have access to a large variety opf content types including views and view content panes. They show up in admin/structure blocks for theme layouts and in a Panels/Page-Manager variant's content tab. If you don't need the additional layout control, you should be able to accomplish what you need using the content panes from views.

Panels Everywhere provides a vehicle for taking control of the entire display layout, not just the content area. I works the same as Panels for content control so really will not add anything new for your issue here.

For more on panels and mini-panels see this answer.
> 1 votes

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


# Question
Title: Use createFilter to build an advanced query using AND and OR with the search API
I have a search index of about 15 fields (profile2 fields) build with the search API indexer (mysql) and I need to build an advanced query. All fields are fulltext. The query input form would have about 6 fields:

```
name, postal code, zip, city, keywords

```

The complete sql query (pseudo code), conditionally based on what the user entered in the form fields, would look like this

```
SELECT
  *
FROM
  {index}
WHERE
  (field_last_name = 'name' OR field_first_name = 'name')
AND
  field_postal_code = 'zip'
AND
  field_city = 'city'
AND
  (field_interests = 'keywords' OR field_hobbies = 'keywords' OR ...)
ORDER BY ...

```

Is this possible at all to build a filter like this?

I try to find a way to build an advanced search and I first tried Views using the filter criteria but I can not build an exposed form like I want. Also as a next step I need to integrate a proximity search on the postal code field. After some reading and hours of using google I thought the search API would give me a go to get a solution on that problem.

To completely understand my problem please refer to this question I asked yesterday: Views 3 Custom filter for Profile2 data

I would really appreciate some hints if I am on the right track or if I have to code a completely distinct module to build that kind of search engine.

Thanks to you all for your help!

# Answer
> 2 votes
This should be possible:

```
<?php
$or1 = $query->createFilter('OR');
$or1->condition('field_last_name', 'name');
$or1->condition('field_first_name', 'name');
$query->filter($or1);

$query->condition('field_postal_code', 'zip');
$query->condition('field_city', 'city');

$or2 = $query->createFilter('OR');
$or2->condition('field_interests', 'keywords');
// if field is fulltext, the default '=' operator is interpreted as 'contains'.
// to search over all fulltext fields: $query->keys('keywords')
$or2->condition('field_hobbies', 'keywords');
//...
$query->filter($or2);
$query->sort('field', 'ASC');
$query->execute();

```

But IMHO and unfortunately you won’t be able to further nest queries/filters like `AND ((field1 = 1 AND field2 = 1) OR (field1 = 2 AND field2 = 2))`. I’m going to open another thread for this problem.

---
Tags: 7, search
---


# Question
Title: How can I remove zombie Panel menu item links caused by Features?
I have a site that uses several panels, each of which has a menu link. Recently I decided to remove the links on my local dev copy. I updated my feature (which contains the panels) and then reverted on my host... But the links were still there.

Because the links are provided by Panels in code, they can't simply be deleted from the menu. How can I delete these links?

# Answer
To fix this, disable and then re-enable each Panel one-by-one on the production server. Hope someone finds this useful!
> 1 votes

---
Tags: panels, features
---


title: Block render array image_formatter

text:
# Question
Title: Block render array image_formatter
How can I pass a renderable array from within a block?

```
$block['content'] = array(
  '#theme' => 'image_formatter',
  '#variables' => array('path' => 'hello.png'),
);

```

How do I pass the variables that image\_formatter needs when I use a renderable array from within a block?

# Answer
> 4 votes
```
$image = array(
  '#theme' => 'image_formatter',
  '#image_style' => 'thumbnail',
  '#item' => array(
    'uri' => $user->picture->uri,
    'alt' => '',
    'title' => '',
  ),
);
$block['image'] = $image;

```

# Answer
> 1 votes
It is a bit confusing until you've done it a couple of times (it had me scratching my head for ages); you need to prefix the names of the variables with a `#`, as properties of the array:

```
$block['content'] = array(
  '#theme' => 'image_formatter',
  '#path' => 'hello.png',
  '#alt' => 'Hello!'
);

```

That would be the equivalent of:

```
theme('image_formatter', array('path' => 'hello.png', 'alt' => 'Hello!'));

```

---
Tags: 7, blocks
---


# Question
Title: Drupal 7 permission to editor type user showing certain admin menus
I have created the editor type user and now I would like to show only content menu and block menu to show in administrator area. But even I have change the permssion but top admin menu is not showing. if i assigned the admistrator role to editor user whole administrator menu showes up. but I only want to show certain options in top menu.

How can I do this.

# Answer
sorry for being stupid. if you give the rights to "toolbar" in permission area. toolbar will show up :) you can also use Content access
> 2 votes

# Answer
Maybe Menu per role module could help yo set up exactly the type of menu you want for your role.
> 0 votes

---
Tags: 7
---


# Question
Title: Drupal 7 views Contextual filters with Blocks, default value doesn't work properly , wield
I have a view created that show content based on the url: eg: domain.com/projects/\[username\]/\[projectname\], which shows a project of a specific user, that works well. Additionally, I want to show the related projects of this user on the sidebar, so I create a block view, using the Contextual filters and the default value.

because my url is projects/username ,By using the default value -\> raw value from URL, so I set the path component as 2. but that doesn't work for me. eg: suppose my username is "abc".

in the preview, if the url path is "projects/abc", it doesn't show anything although the username is in the 2ed component of url path.

if the url path is "abc/\*", it will show the related content, meaning as long as the username is in the first argument of the url path, it works.

I don't what happens, it seems that configuration of path component as 2 doesn't work. I am so puzzled , what happened ?

# Answer
If your first contextual filter is your username filter then it will respond to the first argument passed in the preview textfield, no matter what default value you have specified. Your default value is for when an argument is **not** passed. So, entering "projects/abc" in the Preview with contextual filters box will pass 'projects' to your username filter, but passing a valid username as the first argument as in "abc/\*" will work correctly.

It sounds like you've got it set up correctly to me. Have you tried deploying your block view on an actual page?
> 0 votes

---
Tags: views
---


# Question
Title: How to set reading permission for each separate page?
How to set reading permission for each separate page? Do already have existing drupal setting for us to use? or I need to coding it? Thanks.

# Answer
The Content Access module allows you to configure permissions by content type or, with some additional configuration, by node (per page). It works on D6 and D7.
> 1 votes

# Answer
Modules like Nodeaccess and Node access user reference should give full access control over each node.
> 0 votes

---
Tags: users
---


title: Good themes with youtube integration

text:
# Question
Title: Good themes with youtube integration
Are there any good themes for drupal which have already been integrated with YouTube?

I have been searching for Drupal themes, but it looks like they are integrated with JWplayer rather than YouTube.

Also are there any video tutorials for YouTube integration in Drupal?

# Answer
> 2 votes
There are many modules that facilitate embedding YouTube videos on your site. You can also just paste the Embed code where you need to.

Take a look at Media http://drupal.org/project/media

Embedded Media Field with Media: YouTube extension is also very popular http://drupal.org/project/emfield http://drupal.org/project/media\_youtube

---
Tags: theming, files
---


# Question
Title: D7 Organic Groups - Set group context in panel
I'm using Organic Groups for committee membership on a university intranet. Each group has a landing page created with panels per these d.o instructions. This is working fine, however, I cannot get the panel to pass the group context (gid / group ID) to views contained within the panel. In D6, Group ID (gid) and Node ID (nid) were the same; in D7 they are different. I need to pass the group ID to a view in order to show content generated by that group on the landing page. I've been struggling with this for a while. Am I missing something really basic?

Versions:

* **Context** 7.x-3.0-beta2
* **Context OG** 7.x-1.x-dev
* **Organic Groups** 7.x-1.4
* **Panels** 7.x-3.2
* **Views** 7.x-3.3

Thanks,

Jordan

# Answer
Ahh. After a week of fighting with this, I figured out that the "OG Members" Content Pane will work after some extensive customization. Somehow, I deleted this in my install, so I didn't know about it. I will use this as a starting point template for future group/panel needs.
> 1 votes

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


# Question
Title: Show menu even if node it's not in that menu
Setup I got has two content types, page and article. Pages are normal pages and articles are news. On the site I also have three menus: main, sub and subsub. Main shows first level, sub shows second level items and subsub shows all below items.

Menu:

```
Front page
News
-Breaking news
About
-History
--Early years
-People in charge
Contact

```

Now when admin creates a news article it doesn't go to any menu. It's showed on the News page with view. And when user clicks the news it goes to the news article page where the news is showed fully. But now since the news article is not in menu, the submenu disappears. How can I "trink" Drupal to think that user is on sub page of News page -\> The sub menu would visible?

# Answer
There's a few modules for this that you might be able to use: Menu position, Menu Trails and Menu Trail By Path. It's also possible to code the logic yourself with menu\_tree\_set\_path().
> 0 votes

# Answer
In the settings for the menu item itself, there is a checkbox below "enabled" that says "expanded". Check this box for all items whose children you want to be visible all the time.
> 0 votes

---
Tags: theming, routes
---


title: Node Validation and Dereferncing

text:
# Question
Title: Node Validation and Dereferncing
I have some content types (nodes) that are attached to various taxonomies. For specific node types, I want to do some validation on the taxonomy. I do not want to hard-code the nodes types and their corresponding fields that reference the taxonomy. So I put them in array. However, I am unable to dereference the field names. I've tried double $$, quotes, etc, but can't get it to work. Is what I want to do possible?

```
<?php

$node = (object) array(
    'nid' => NULL,
    'vid' => NULL,
    'uid' => '1',
    'type' => 'price_document',
    'language' => 'und',
    'field_taxonomy_price' => array(
        'und' => array(
            array(
                'tid' => '94'
            )
        )
    ),
);

  $nodes_to_check = array("price_document" => "field_taxonomy_price",
                          "package"        => "field_taxonomy_package",
                         );

  if (array_key_exists($node->type,$nodes_to_check)) {
    $taxonomy_field = $nodes_to_check[$node->type];
    print_r($taxonomy_field);
    $tid = $node->field_taxonomy_price ['und'][0]['tid']; //  <- this works but, how
    //$tid = $node->"$$taxonomy_field" ['und'][0]['tid'];     <- can I deref variable?
  }
?>

```

# Answer
> 0 votes
You just need to use curly braces; there's no need for variable variables in this case:

```
$tid = $node->{$taxonomy_field}['und'][0]['tid'];

```

---
Tags: nodes, forms
---


# Question
Title: One node for every referenced node in views
I have a view that uses the table display mode. I want to show up the last created node for every referenced node; for example, I have two users, and I want to show the last post for both users.

> user number 1 | last post title
> user number 2 | last post title

# Answer
> 1 votes
You can also use View Field View module and create a view named Content View in which you may have:

**Fields**

* Content: Title

**Sort criteria**

* Content: Post date: Sort ascending or Sort descending

**Filter criteria**

* Content: Type *(or anything else to filter only certain posts)*

**Pager**

* Use pager: Display a specified number of items | 1 items

**Contextual filters**

* Content: Author uid

Now create another page view or a block view (whatever you want) named User View

**Relationships**

* Content: Author

**Fields**

* User: title
* Global: View (in this field select the view: Content View)

User View passes arguments in every raw to the Content View and thus it filters content by user id.

# Answer
> 0 votes
I must say I didn't test it right now but you could try to aggregate on userid and sort your View on node creation date on group by User id and show limited number of nodes only, for example 1 per user.

In your View configuration: go to Pager section set up Use pager: Display a specified number of items Items per page: 1 More link: No

go to Advanced: Use agregation: Yes

go to Fields: click on field Date aggregation settings go to Configure group settings for field Date Aggregation Type: Minimum Group Column: Value

---
Tags: 7, views, nodes
---


# Question
Title: How do I include a term's additional fields on node display?
With Drupal 6 there was Taxonomy Image to do this, but with the field goodness of Drupal 7 we can just add an imagefield to a certain vocabulary. This works quite well to output stuff with views, but I can't seem to find a way to show up the additional field on the node display.

In my case I simply have a vocabulary called countries that has an additional imagefield to hold the country's flag. When viewing a node that has assigned a country term I need the flag of the country to show up instead of its name.

Regards, Daniel

# Answer
I've not played with semantic fields before, but I can tell you that configuring a term's display is the same as configuring a nodes display. The administration for a vocabularies display can be found at Structure --\> Taxonomy --\> VOCAB\_NAME --\> Manage Display or the path

```
admin/structure/taxonomy/VOCAB_NAME/display

```

Again, same as nodes you can configure the labeling & formatting options from this area. However, the location to configure a node's display is Structure --\> Content Types --\> YOUR\_TYPE --\> Manage Display

These settings are used for Drupal's native output. Using views can bypass these settings depending on the view (fields) or can work together (full, default, teaser).
> -1 votes

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


# Question
Title: Collapsible items in menu administration
In sites with a lot of nested menu items on a menu (e.g the `main-menu`) administration becomes painful. Is there a module which will add expand/collapse capabilities to the `admin/structure/menu/manage` screens?

This has also been discussed in http://drupal.org/node/521546 but doesn't seem to be resolved.

# Answer
The Big Menu module seems to do the job. Here is a quote about it (from the module's project page):

> An alternative to core menu management - adds scalability to the admin menu management screen, by loading subtrees via AJAX (not related to megamenu & similar display modules - this is an admin-only content management utility).
>
> When dealing with a site menu that contains thousands of links, the Drupal Menu UI admin interface becomes so unwieldy as to be impossible to use. When the drag & drop functions for tree management are running, a page can take minutes to render.
>
> This module attempts to replace the all-in-one global tree view with a similar interface, but sub-trees are "collapsed" below a certain level, and can be expanded as needed.
> 1 votes

---
Tags: 7, routes, users, forms
---


# Question
Title: Add database value in views for entity type user
I want to extend the user profile with a rank (a decimal ranging from 500 - 2500), which needs to be updated on a regular basis (10 times per minute) for several users. (it is for http://achtungdiekurve.net/ ) I already implemented it with a seperate table, containing a rank field and implemented a table to show the rankings (http://achtungdiekurve.net/ranks ).

However, I want to use views to create this table. But I cant seem to alter the entity type user in such a way, that it shows Rank in the views forms. How to do this? My current code:

```
<?php
function achtung_entity_property_info_alter(&$info) {

  $info["user"]["properties"]["rank"] = array(
    "label" => t("Rank"),
    "description" => t("The rank of the user"),
    "type" => "decimal",
    "getter callback" => "achtung_get_entity_callback",
    "computed" => true,
    "entity views field" => true,
    "query callback" => "entity_property_query",
  );
  watchdog("ACHTUNG entity info alter", "<pre>".print_r($info, true)."</pre>");
  return $info;

}
function achtung_get_entity_callback($account, $options, $name, $entity_type) {
  watchdog("ACHTUNG entity info callback", "<pre>".print_r($account, true)."</pre>");
  return 2;
}
?>

```

# Answer
Although I haven't had a chance to play with it myself just yet, assuming everything else is implemented correctly, it seems as though using EntityFieldQuery Views Backend as your Views backend should make your new Rank field visible to Views.
> 1 votes

# Answer
AFAIK, the default Views backend does not support Entity properties. Instead, it support fields from the Field API and known entity properties such as `nid`. In order to use your custom property as a Views field, you need to either use EntityFieldQuery Views Backend (as suggested by David Watson) or provide an implementation of `hook_views_data()` to expose your table and column to Views.
> 0 votes

---
Tags: views, entities
---


# Question
Title: What are best practices for creating node relationships?
In Drupal 7, what are the best ways of creating relations between nodes?

Say I have a number of articles about famous writers. I want to build an alphabetical list of them using Views. As writers often have pseudonyms, I want these pseudonyms to appear in the list too but creating a node for a pseudonym that is identical to its respective Writer node in all aspects except title sounds like not quite good idea.

I thought a bit and came up with 2 node types, Writer and Writer\_Pseudonym:

* **Writer**

+ Title
    + Body
    + All other fields
* **Writer\_Pseudonym**

+ Title
    + Target Node Id

Now I want to build a view in which nodes of type Writer\_Pseudonym will display body text of their target nodes:

> Title: Doe, John (Writer)
>
> Body: John Doe, also known as Evil John, is a writer that became famous after creating an autobiographical novel "Foobar".
>
> Title: Evil John (Writer\_Pseudonym)
>
> Body: John Doe, also known as Evil John, is a writer that became famous after creating an autobiographical novel "Foobar".

Is it possible to do it with Views? And if not, are there any other ways to establish relations between nodes while being able to use fields of target nodes?

# Answer
Your best bet for this kind relationship is going to be Taxonomy. You can create a free tagging vocabulary (exactly like the vocab that is initialized with the Article content type in a standard profile D7 install) and as these "Authors" come up with a need for a "Pseudonym" you just tag that node with it's term.

Views supports most every use case (if not all) you can imagine working with Taxonomy.

Because Taxonomy is core it's further developed and easier to use than alternative relationships (references, hierarchy, etc).

For the above example, you'd could configure the view to display all (full, teaser) or part (fields) of the "Author" content type based on being tagged with the relative "Pseudonym". Views are a little daunting at first but if you keep playing with them, you'll soon realize their immense capability.

Just comment if you need clarification on any of the above...
> 0 votes

---
Tags: 7, views, nodes
---


# Question
Title: Commerce field with no value, but printed
My commerce product type has a text field, which is printed even if it has no value. Every commerce field is printed within a `<div classes_here></div>`. Is there any way to avoid this issue??

thanks

# Answer
> 1 votes
Here is a link to this issue, with a patch for commerce 1.3

---
Tags: 7, commerce
---


# Question
Title: Is it possible to return form, themes, content in an array for my page callback function?
For right now I need to return a themed table, a form, & content on one page. In my page callback function how do I properly store and return this variable/array?

I looked at the page below, but the code did not seem to work properly. I can only get the themed table (first in array) to show, but nothing else after it.

Return both a form and content in a menu callback

EDIT:

i tried the code below for my return, but it doesn't work. $header & $rows are both properly declared and holding the right data.

```
return array(
  'my_content' => array(
    '#type' => 'markup',
    '#markup' => 'Some markup',
  ),
  'my_table' => theme('table', array('header' => $header, 'rows' => $rows)),
);

```

# Answer
> 1 votes
Remember that `theme('table'..` returns HTML markup, so you are assigning a HTML string to the `my_table` key. In the example you linked `drupal_get_form` was being used which returns a renderable array, so it would have functioned correctly. Since `render()` doesn't know what to do with an HTML string, you must pass the render function the information before it has been turned into HTML:

```
return array(
  'my_content' => array(
    '#type' => 'markup',
    '#markup' => 'Some markup',
  ),
  'my_table' => array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
  ),
);

```

---
Tags: forms, routes, 7
---


# Question
Title: Why does Drupal display node titles at the page level instead of the node level?
I'm doing some work with 'Extra Fields' and keep tripping up on the fact that Drupal tends to display the title of a node at the page level when viewing the full node page. It seems to be that it makes more sense to always display the title at the node level. Is there a reason I'm not seeing that makes it better to display it at the page level instead?

# Answer
Not every page is a node. It's really as simple as that; if node pages' titles were displayed on the node level but other pages' titles were displayed at the page level it makes things inconsistent and more difficult to maintain, document, predict, etc.
> 2 votes

---
Tags: theming, nodes
---


# Question
Title: Create A Block To Add Field Collection Item
I want to create a block that would hold links to add different field collection items. How would i do this? I am new to drupal, please point me to right direction or help me get started.

# Answer
Have you tried the Views module yet? You can easily create blocks and add whatever field items you want through it. It's a very powerful and at times complex module so you can refer to the nodeOne video tutorials. Good luck!
> 1 votes

---
Tags: entities
---


title: Menus as per Role

text:
# Question
Title: Menus as per Role
A form which has two field Role and a Tree View Menu with checkboxes. I want to assign menus to role so that if a user with that role login the user would be able to see only those menus that have been assigned. The menu would be shown as dropdown to the user

# Answer
I think this module will do what you want: Menu Per Role
> 1 votes

# Answer
Assuming Drupal 7, create different menus, one for each role. Then configure the menu blocks: place them in the same region and restrict each one to the respective roles through the `Configure` link.
> 0 votes

# Answer
As Joe suggested Menu Per Role module is best for you, it will give you "Restrict item visibility" option through which you can set the visibility for different roles, i have used this module for the same purpose and it works fine for me.
> 0 votes

---
Tags: navigation
---


title: Location City synonym support?

text:
# Question
Title: Location City synonym support?
I would like to allow users to search node location using location city with synonyms.

For example:

* New York
* NY
* NYC
* New York City

etc.

should bring the same search results.

How to do this ?

# Answer
> 0 votes
I have created the related feature request here.

> If this feature is not yet available in the location module, I could maybe use Views, create the indexed synonyms as taxonomy terms vocabulary and term reference field `Content: Location Synonyms`, modify the view's `Global: combine filters filter` setting `Choose
>  fields to combine for filtering` as `Location: City` and `Content:
>  Location Synonyms`? This would require tagging each node `location
>  synonyms` manually or would require setting up a Rule (using Rules contrib module) that would add these synonyms automatically depending on the `Location: City` selected. The standard Drupal search would index these tags.
>
> It would be better to have it either inside the Location module or as an additional contributed helper module.

There is also a contributed module Location Taxonomize that might help in achieving this.

---
Tags: 7, location
---


title: Text inside Search box

text:
# Question
Title: Text inside Search box
How could I add a default text inside drupal's search box? I have done this with jquery but I need the text to be translated.

I know this can be done with the Custom Search module but it is a little overkill to add a module for such a small feature. Hopefully this can be achieved using my theme's preprocess function. Any ideas on how this can be done?

# Answer
Use Drupal to communicate a translated string to Javascript:

```
drupal_add_js(array('my_string' => t('Default Text')), 'setting');

```

Then, have your jQuery read the value:

```
var str = Drupal.settings.my_string;

```
> 0 votes

---
Tags: theming, search
---


# Question
Title: Domain Access module: Adding nodes programmatically to subdomains
I am using Drupal 6 and Domain Access-6.x-2.11. I need to programmatically add nodes to subdomains defined in Domain Access configuration. I've been looking the source code of domain.module but can't figure out how to use the api of the module to add a node to certain subdomains.

Any suggestions?

# Answer
Since I didnt find a way to do this with api I solved this by editing the table where domain access keeps the info about which node belongs to which domain.
> 0 votes

# Answer
Answer for Drupal 7:

```
$node->domains = $domains;
$node->domain_site = FALSE;
$node->domain_source = '1';

```

Where $domains is an associative array like that:

```
$domains = array(
 '1' => '1',
 '4' => '4',
);

```
> -2 votes

---
Tags: domain-access
---


title: if statement befor creating a node

text:
# Question
Title: if statement befor creating a node
I need to set an `if` statement before creating a specific content type's node.

How can I stop the creation process if the condition returns false, and get back to the creation page with error message to let the user to correct the wrong value.

Is there a function to get it work?

# Answer
> 1 votes
Another option would be to use `hook_node_validate`.

> Perform node validation before a node is created or updated.
>
> This hook is invoked from node\_validate(), after a user has has finished editing the node and is previewing or submitting it. It is invoked at the end of all the standard validation steps, and after the type-specific hook\_validate() is invoked.
>
> To indicate a validation error, use form\_set\_error().

Something *like* the following would work:

```
function mymodule_node_validate($node) {
  if ($node->type == 'mynodetype') {
    if ($node->myfieldsvalue != 'what it should') {
      form_set_error('field_name', t('Your error message'));
    }
  }
}

```

References:

`hook_node_validate`

`form_set_error`

# Answer
> 0 votes
I would try the Rules module. For example, you can write a rule that fires on the event *Before saving new content* with the **condition** *data comparison* (on the relevant field's value) and an **action** of *print status message*. You can of course further customize this to get it to do exactly what you want.

---
Tags: 7, nodes
---


title: Editing content with views

text:
# Question
Title: Editing content with views
This is a very basic question so please check for idiocy as I haven't worked with views that much.

I want to edit the main page of a content type like an article through views. To me it seems views only works with the "listing" of the contents not the content itself. I might be missing an option right in front of me but I can't seem to figure out what it is.

Repeat, I want to edit the main content page not the listing. Please help!

EDIT: This is the screenshot of my content page. I want change this layout through views like reorder the fields or add new ones like it's typically done in views. So is it possible?

Drupal has done this ugly presentation itself and I want to change it.

# Answer
I found the solution by creating a panel of my content type and editing the `Node`template.
> 0 votes

# Answer
You are basically right regarding views. Views is a way to see data aggregated together in some fashion. Think visual SQL.

The original request seems a bit confusing to me. I think you are asking for 2 things. Theming the content based on type as well as theming the views output.

For content type, take a look at theming nodes by content type . Drupal 6 and 7 are different in the way they go about this but for drupal 6 you are more or less looking to use the template `node-[NODETYPE].tpl.php`. This will adjust your node's output on a full view.

For theming your view, take a look at your view in the edit mode. Under basic setting you will see `Theme: Information`. Click on that and you will get a listing of possible templates that you could use to theme your view. Generally the same way you would edit your node type template you would edit your views template file. Check Theming Views for more info.
> 2 votes

# Answer
Having read your edit, let me try: the key would be to add to your View a field labeled "Content: Edit Link" and insert into your template using `print $fields['edit_link']->content`. That should get you the link to open the node edit form.
> 1 votes

# Answer
As usual with Drupal you have several options:

1. You could alter the form using hook\_form\_alter(). It might seem scary, but it's the easiest way sometimes.
2. You could use field\_group module to put your unused fields into separate tab, it's quick and easy and greatly improves usability
3. you could override the edit page using page manager and panels, there is a nice tutorial available at http://dev.nodeone.se/sv/node/814
> 0 votes

---
Tags: views, nodes
---


# Question
Title: Add Rating Widget to a custom full content layout in drupal 7
Can anyone know how to add a rate widget to a custom full content layout in drupal 7.

Let say I have a content type article.A have customized the layout with the help of Ds module for the full content.I have added my the field to my choose.Now I need a rating in the full content page with that the user can vote the article whether they like it or not.For that I added a module called Rate widget.With that I try to add a Thumb up/down to the full content page of the article but it is not showing me.Can any one know how to add rate widget to the custom full content.

# Answer
You can use below function to print rate field

```
rate_embed(&$node, $machine_name, $mode = RATE_FULL);

```

Like `print rate_embed($node, 'rate', $mode = RATE_FULL);`
> 2 votes

---
Tags: nodes, rating
---


# Question
Title: Standard practice for adding new fields to a table created by a contrib module
I have to add a field to the webform table generated by the webform contrib module.

I was thinking about implementing the enable hook in the .install of a custom module in order to do this:

```
function mymodule_enable( ) {
  db_query('ALTER TABLE webform ADD COLUMN is_valid int') ;
}

```

But I don't know if this will generate problems if the module is disabled and enabled again in the future and tries to add the field (which would be already created by then).

Is this correct or is there a better way to do this?

# Answer
> 2 votes
Well, you could always use hook\_update to generate a new field in the table. This gets executed when you do a database update.

It's even possible to use it in your own module.

http://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook\_update/7

---
Tags: database, 6, webforms
---


# Question
Title: How do I set up a view to filter on URL path?
Can views show me all menu items with paths that match a particular pattern?

I have a documentation section which is mostly basic pages, but there's some views that belong here, too. I have set the views' paths to doc/some-view-name.

I would like to use a View to find all documentation pages (including pages created by Views) identified by the path doc/\*

Is this possible?

# Answer
> 1 votes
To be able to filter nodes by their path you will have to use menu\_link. (i havent used it though).

As far as i know there is no simple way of displaying content of the menu related tables, which is what you would have to do to include the views in the result. Some discussion and a direction of coding is here : http://groups.drupal.org/node/22731 Unfortunately the module suggested there wouls help you neither - it is again just for nodes.

---
Tags: 7, views
---


# Question
Title: Is it possible to add a second `drupal.behaviors` to your module?
I have a module that uses a bit of jQuery.

But when I submit a form I want it to call an other bit of jQuery on the landing page.

So I thought adding another `Drupal.behaviors` to my module. But this doesn't seam to work.

```
(function ($) {
  Drupal.behaviors.popover_hide = {
    attach: function (context, settings) {
     // open link in new window.
     var linky = $('clickedme').attr("href");
     alert(linky);
     alert('linky');
     // remove class from link

     // set focus on new window eventueel
    }
  };
})(jQuery);

```

when I already have a `Drupal.behaviors.popover` loaded. ("popover" is the name of the module)

# Answer
> 0 votes
Turns out this does work I just needed to clear cache...

If you have this issue: go to `admin/config/development/performance` and press the clear cache button.

`.js` files are cached even though if you have set caching to disabled on the page I just mentioned.

---
Tags: 7, javascript
---


title: automatic class to all boolean fields

text:
# Question
Title: automatic class to all boolean fields
I have a `Boolean` field on a content type. Possible values are `completed` and `not completed`. The default rendering is not satisfactory though since it doesn't include any CSS class to represent the boolean state (true, false) so I cannot act on this using CSS or JavaScript.

```
<div class="field
            field-name-field-status
            field-type-list-boolean
            field-label-inline
            clearfix">
  <div class="field-label">Completion status: </div>
  <div class="field-items">
    <div class="field-item even">completed</div>
  </div>
</div>

```

What's the best way to add such a class on `.field` or `.field-item`?

What I've tried so far:

* `hook_field_display_alter` but this doesn't provide me with data nor field type
* `hook_node_view` but I cannot iterate fields by type. I'd need to pinpoint the specific field instance I need to modify but I don't know that in advance.
* by providing a custom node template, but this solution is not generic for all occurrences of a boolean field

# Answer
> 3 votes
You can implement `hook_preprocess_field()` and add the class there.

Get field type :

```
$element = $variables['element'];
$type = $element['#field_type'];

```

Add something to field class :

```
$variables['classes_array'][] = 'class-name';

```

---
Tags: 7, entities, theming
---


title: Webform menu access control

text:
# Question
Title: Webform menu access control
I'm using Drupal 7 with Webform and Content Access contrib modules.

I wrote a little snippet that displays all items for a given menu, and greys out the ones that the user doesn't have access to, while the accessible ones are links.

I get the access control information with

```
menu_link_load(menu_load_links(menu_my_menu)[mlid])[access]

```

...if that helps at all. It returns 1 if access should be granted, and NULL if not.

The problem I'm encountering is that, while this code works swimmingly for normal nodes, webforms seem to return a 1 for access even when the logged-in user does not have permission to submit that form. So the link shows up, and then it takes the user to a page that says "You do not have permission to view this form."

What function do I call to find out whether a webform of a certain path (or title or whatever I can find out from menu\_link\_load) should be visible to the user?

# Answer
> 2 votes
I think the easiest way to resolve this is to use Content Access and specify the View permission for a Webform, rather than Webform's "can submit" permission. In other words, **by using the Content Access module's View Permission** instead of the Webform "can submit" permission, **you can utilize the code you're currently using**. To do this you'll have to set a separate View permission for each Webform.

The problem originates from Webform's permissions conflict with Drupal core: Drupal's standard View permission may be true, but the Webform "You can submit this form" permission can be false, which gives a different Access Denied message from above.

I attempted to dig up an alternate solution, creating some custom code to derive the access for Webform menu items, but it really was looking horrendous. Webform does not have a function that returns "You can submit this webform" access, and trying to efficiently determine if a menu item is a webform was looking pretty foul.

---
Tags: routes, webforms
---


# Question
Title: A way to share content structure across several panel pages
I develop a site which presents content along with multiple blocks of information on side bars. They're context related by nature, so I decided to use panels instead of block module.

That approach worked great for some time and was flexible enough. I created multiple view panes and passed the arguments through panel contexts.

But soon I realized there is a problem. I have a bunch of pages on a site which usually implemented using views pages. But they must more or less share the same side bars. So they must be panel pages too.

But there is a dozen or so of panes on a panel, so copying panel content (say, by using export and import) creates an awful mess and redundancy which greatly hampers maintenance and subsequent changes.

I'm thinking about creating all the pages in code by customizing one rough part created through gui. But I'm hesitating whether it's a good way. Any ideas?

# Answer
> 1 votes
Mini-panels were not in option in my cause because of a custom panel layout containing multiply panel regions. But I found quite a nice solution.

I created a panel with a path wildcard and setup a context based on it in arguments tab. After that I added all the needed views on a page and setup visibility rules based on string comparison. Views in a main panel region shown on positive match and corresponding overviews on the right side - on negative.

This way I have only three panels - one for nodes, another one for taxonomy and third for all the auxiliary views.

# Answer
> 1 votes
Why not use mini panels, one of the sub-modules of Panels. Mini-panels are just like panel pages except that instead of taking a path and acting like a page they act like blocks. They are specifically designed to be embedded in other panels/pages.

So you can make a mini panel called *sidebar* and then if you ever have to make a change just update it in one place.

# Answer
> 1 votes
In the Panels universe, the intended solution for this problem is Panels Everywhere.

With it, you can "wrap" your entire page layout built with Panels, in an outer Panel, called the "Site template". As site template support variants, just like all other Panels, you can create one variant that displays all the sidebar content next to your Views, and a second site template that does not.

---
Tags: 7, views, blocks, panels, nodes
---


title: apache 2.2 + mod_pagespeed + varnish

text:
# Question
Title: apache 2.2 + mod_pagespeed + varnish
Did anyone try the combination Drupal 7 + apache 2.2 + mod\_pagespeed + varnish?

Does it produce any problem?

IS Drupal own CSS and JavaScript aggregation mechanism needed if mod\_pagespeed is used?

# Answer
Have yet to test it out. I do know that domain specific code CAN be better in comparison to a generalized tool like mod\_pagespeed; but I would imagine it would take a lot of effort to beat mod\_pagespeed. mod\_pagespeed should bring an improvement in comparison to drupal's core aggregation; you will get CSS & JS Compression among some other nice things.

In Drupal land we are working on improving the page load time. Here are some projects for that.

Long story short: Use mod\_pagespeed today; checkout some of these projects in the future.
> 4 votes

# Answer
I can confirm that Varnish won't work properly if mod\_pagespeed is enabled. I tested, if mod\_pagespeed enabled, Varnish stop caching anything.

For reference: http://code.google.com/p/modpagespeed/issues/detail?id=232#c4
> 0 votes

---
Tags: 7, caching
---


title: Store Fields in an external database

text:
# Question
Title: Store Fields in an external database
I'm interfacing an external database with Drupal 7. I have created custom entities and custom fields to represent the tables in the external database. Is there a simple way to set the fields up so all CRUD uses the external database?

I still want to use Drupal's default field\_sql\_storage.module, but have it switch to the external database and back for these fields automatically. Can I say "for this field, use this other database".

Something simple like:

```
function mymodule_field_info() {
  return array(
    'customfield' => array(
      'label' => t('My Custom Field'),
      'description' => t('This field stores text in the external database.'),
      'settings' => array('max_length' => 255),
      'instance_settings' => array('text_processing' => 0),
      'default_widget' => 'text_textfield',
      'default_formatter' => 'text_default',
      // Simple setting to change database.
      'database' => 'externaldb', // From settings.php $database connections.
    ),
}

```

The hard way is to create a custom storage backend and use it for these fields like the Mongodb module. I've tested this and it works, but it seems like there should be any easier way if you want to use Drupal's default field\_sql\_storage.module.

Would the strategic placement of db\_set\_active() allow me to avoid creating a full custom storage backend?

# Answer
There is a Field Storage API you can use for external storage in fields.
> 1 votes

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


title: Link directly to a file from a block

text:
# Question
Title: Link directly to a file from a block
I have a full-HTML block and I want to put a link to a file into it that varies with the sitepath. I saw somewhere something about putting public:// instead of http:// to route to `sites/default/files`, but it doesn't seem to work from block content at least (is that only in php?)

So I have a block with `<img src="public://img/screenshot.png"/>` in the content and nothing is happening. Any ideas how to make this work? I don't to use image module or anything like that yet.. just a link to a file.

# Answer
You'll need to use file\_create\_url() and the 'PHP code' format (comes with the core 'PHP filter' module) for this to work:

```
<img src="<?php print file_create_url('public://img/screenshot.png'); ?>"/>

```

If possible I would suggest adding it inside the block's template file instead though.
> 3 votes

---
Tags: 7, files, navigation
---


# Question
Title: Export multilingual settings with features
I'm using features to export 10 content types, but I don't get the multilingual settings. My question is, whether this is even possible, maybe with strongarm or I'm stuck having to change those settings by hand?

I use the i18n module and want the content\_type to be translatable, in the content\_type edit menu i set:

* Publishing Settings-\>Multilingual Settings-\> Enable with Translation
* Multilingual Settings-\>Extended language options-\>Require language (Do not allow Language Neutral).

# Answer
> 11 votes
Yes, you can do this with Strongarm. You'll want to add all the variables that are prefixed `i18n_`, `language_`, and `locale_`.

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


title: commerce product display news

text:
# Question
Title: commerce product display news
I have a problem that I am not sure how to address. I am using commerce guys and Drupal 7. I have some products around 200. But each one will have updates or news of what it is going on with them. How could I accomplish this so each product will display its news. For instance

Product Name
Description
Origin

**PRODUCT NEWS**

Month 1
lorem Ipsum is simply dummy text of the printing and typesetting industry.

Month 2
lorem Ipsum is simply dummy text of the printing and typesetting industry.

Month 3
lorem Ipsum is simply dummy text of the printing and typesetting industry.

**view all product news**

The first part is easily done with view mode but I have no clue what it is the best way to integrate news to a product display. I have searching in commerce guys and display suite but still don't have an idea. Do you have any advice, experience or module or how could I accomplish this?

# Answer
I would establish a Product News content type, and equip it with an Entity Reference field, whereby you could link the news to a product sku or product display - your choice. Then, in the product display you could introduce a Viewfield which would gather the related news through a View criteria that you will set up). The view would have to accept an argument (product sku or product display node id - depending on what the news should refer to).
> 1 votes

# Answer
A similar way would be to use Entity Views Attachment (EVA) along with a Product News content and utilize the tagging on the product to obtain a related news view
> 2 votes

---
Tags: 7, commerce
---


# Question
Title: Best way to modify views output with a custom function?
I have view with a block display that shows user profile info and the user's points (from user point module). I want to show the "point level" which is a text string based on the number of points the user has.

How do I add that to the block?

I already have a custom function that returns a text string based on the number of points.

I don't want to use views\_PHP anymore because it prevents caching of the block.

Should I use hook\_block\_view\_alter()?

# Answer
I would much prefer a solution that I would allow Views to the render the text you want directly, so technically, I'm not going to answer your question here.

My suggestion is that you add a new formatter, that you use to directly render the user points as a text string instead. This allows your level to work correctly with all of core, not just one particular block. You can then just add user points twice to the View, with different formatters.

I haven't given the particular code below a proper test, as I don't use user points anywhere, but it's copied and cleaned up from live project where I use do something similar, so I know that it works.

```
/**
 * Implements hook_field_formatter_info().
 */
function user_level_field_formatter_info() {
  return array(
  'user_level' => array (
      'label' => t('User level'),
      'field types' => array('user_points'),
    ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function user_level_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $user_level = 'green';

  switch ($items[0]) {
    case > 5000:
      $user_level = 'veteran';
    case > 2500:
      $user_level = 'experienced';
  }

  return array(0 => array('#markup' => $user_level));
}

```

The code above assumes that user points is a real field on the user. If that is not the case, then you can add a new text field on the user, set `'field types'` to `array('text')` instead, and in the formatter grab the number of user points directly from user points, with say a `user_load($uid)`, instead of from `$items[0]` as I do. You will probably also hide the textfield from `user_edit` with a `hook_form_alter`.
> 5 votes

---
Tags: 7, views, blocks
---


# Question
Title: If a pager is missing, then appears when using another theme, does that narrow the problem to the original theme?
I have a pager missing from one page, while visible on another. These pages are generated by my custom module. I'm working with a custom theme that's been hacked together (wasn't me!) When I switch the theme to Bartik everything works as expected.

Here is the query function:

```
function query_activities($tid = NULL, $did = NULL) {
  $record_count = variable_get('promo_list_count');
  $query = db_select('node', 'n')->extend('PagerDefault');
  $query->fields('n', array('nid', 'title'));
  if ($tid) {
    $query->leftJoin('taxonomy_index', 'ti', 'ti.nid = n.nid');
    $query->condition('ti.tid', $tid);
  }
  $query->condition('n.type', 'activity_promo_list');
  $query->condition('n.status', 1);
  $query->groupBy('n.nid');
  $query->orderBy('n.sticky', 'DESC');
  $query->orderBy('n.promote', 'DESC');
  $query->orderBy('n.changed', 'DESC');
  $query->orderBy('n.created', 'DESC');
  $query->limit($record_count);
  $results = $query->execute()->fetchAll();
  return $results;

```

I have a function that wraps the query results in theme arrays and can post the whole thing if needed (it's 120 lines) but I think the only relevant part is:

```
  $content['pager'] = array(
  '#theme' => 'pager',
  '#weight' => $count,
  '#quantity' => 5,
  );
  krumo($content['pager']);
  return $content;

```

The krumo() dump shows the pager array populated on both pages (pager visible & pager missing).

Does this narrow the problem to theme layer?

What should I look for to fix or diagnose the missing pager?

# Answer
I stumbled on tostinni's answer in Pager disappears when adding "GROUP BY" in the SQL query.

> Your query with the `GROUP BY` is incorrect, MySQL is lax enough to let you write this kind of queries but it is by no way recommended. When you use a `GROUP BY` clause you should group all the columns without a aggregate function.

I then fixed two queries that have poorly formed `GROUP BY`s, but my pager was still missing. I bust out Devel's query logging feature; the offending SQL query resulted to be used by the Nodequeue module. I checked the bug reports for that module, and found the one about that query: Grouping error" when creating a simple queue (PostgreSQL).
> 0 votes

---
Tags: theming, paging
---


# Question
Title: How do I implement a clickable JavaScript map?
I've found a great clickable map over at code canyon which includes all the JavaScript, CSS, and XML to make it happen. A demo of the map can be viewed here.

I figure the best way to accomplish this would be to create a custom module and load the JavaScript, XML, and CSS files via the .info file.

The code to display the map is a simple html statement or two that could be placed on a basic page.

```
<div id="container">

    <div class="mapWrapper">
            <div id="map"></div>
            <div id="text"></div>
    </div>

</div>

```

Would it be better to create a page template specific to the node? How does one load the CSS and JavaScript from the module to the page?

# Answer
You can use drupal\_add\_js() and drupal\_add\_css() in the menu call back function to add js and css files on the specific page.

Adding in the .info file would add js and css on all the pages.

You can also use hook\_library() to define the library of js files and its dependancy with jquery or core js files.
> 2 votes

# Answer
If you want to add the map just to individual pages, `drupal_add_js()` and `drupal_add_css()` are your only friends. With them you will be able to hack the map into any node (eg. `node--419.tpl.php`) or any view (most probably `views-view--VIEW-NAME.tpl.php`). And then you'll get tempted to make it all into a module ;-)
> 2 votes

---
Tags: 7, javascript
---


# Question
Title: 'Illegal choice' error while submitting/validating selectbox shown with AJAX
I'm making a module where the content type and fields are created by install. Now i want to make one of those fields only to show up when an option is selected. I did this with AJAX, in some way I can't make it work with the field as defined in the module.install file. I have a radio button selector for two options. When selecting the first option there should show up a selectbox with a list of nodes to select. When selecting the second option two textfields should be shown instead. When I try to add content of this type I get the error message (when changing the value from the radio buttons):

An illegal choice has been detected. Please contact the site administrator.

Can someone give me some advice to make this work? Thanks in advance!

---

Here is my code from the install file:

```
function _concert_installed_fields() {
$t = get_t();
return array(
  // other fields left out
'venue_node' => array(
 'field_name' => 'venue_node',
 'label' => 'Select a venue from the list',
 'type' => 'list_integer',
 'cardinality' => '1',
 'foreign keys' => array(),
 'indexes' => array(
   'value' => array(
    0 => 'value',
   ),
  ),
 'module' => 'list',
 'settings' => array(
  'allowed_values_function' => '_concert_content_type_venue_options_list',
  ),
),
'venue_radio' => array(
 'field_name' => 'venue_radio',
 'cardinality' => 1,
 'type' => 'list_boolean',
)
);

```

From my .module file:

```
 function concert_form_alter(&$form, &$form_state, $form_id) {
 if($form_id == "concert_node_form") {
 $form['venue_radio'] = array(
  '#title' => t("Choose a venue from the database or add one manually"),
  '#type' => 'radios',
  '#options' => array(0 => t('Add a venue from the database.'),
                      1 => t('Add a venue manually.'),),
  '#ajax' => array(
    'callback' => 'concert_venue_callback',
    'wrapper' => 'venue_select',
    'effect' => 'fade',
  ),
);

$form['venue_select'] = array(
  '#prefix' => '<div id = "venue_select">',
  '#suffix' => '</div>',
  '#type' => 'fieldset',
);
if (!empty($form_state['values']['venue_radio']) && $form_state['values']['venue_radio']   == "1") {
  $form['venue_node']['#type'] = 'hidden';

  $form['venue_select']['location'] = array(
    '#type' => 'textfield',
    '#title' => t('location'),

  );
  $form['venue_select']['venue_city'] = array(
    '#type' => 'textfield',
    '#title'=> t('city'),
  );
}

else {
$form['venue_select']['venue_node'] = array(
    '#type' => 'select',
    '#options' => _concert_content_type_venue_options_list(),
    '#title' => t('venue node select'),
    '#default_value' => '466', // node id is select value
  );
if (!empty($form_state['values']['venue_node']))
$form['concert_venue_node']['und']['#default_value'] = $form_state['values']['venue_node'];
}

function concert_venue_callback($form, $form_state) {
   return $form['venue_select'];
}

```

The options from the selectbox are populated by a function in a file accessable for both the .install and the .module file:

```
function _concert_content_type_venue_options_list() {

$results = db_select('node', 'n')
 ->fields('n', array('nid', 'title'))
 ->condition('n.status', 1)
 ->condition('n.type', 'venue')
 ->execute();

$options = array();
  foreach ($results as $node) {
    $options[$node->nid] = $node->title;
  }
return $options;
}

```

# Answer
Setting #default\_value for the 'venue\_radio' form element solved my problem: http://drupal.org/node/1545316#comment-5914060 I also changed my code to how it is described in the Ajax altering node form example. Everything is working now in the way I wanted it to. Issue solved.
> 1 votes

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


# Question
Title: When is node_search() in the node module called?
Someone has made changes to core, and specifically the `node_search()` function in the node module.

I'm not familiar with this function. What does it do, and under what circumstances is it being called?

# Answer
`node_search()` is the node module's implementation of `hook_search()`, which:

> allows a module to perform searches on content it defines (custom node types, users, or comments, for example) when a site search is performed.

That hook is invoked from a number of different places.

At a guess I would say if someone was going to make changes to `node_search()` it would probably be for the 'search' operation (i.e. altering the results of the standard node search). That particular operation is invoked from `search_data()`.

It might be worth having a look a regular copy of `node_search()` alongside your hacked copy to see if you can understand what the differences are, and whether you can revert the changes without breaking things (if that's what you need to do).
> 2 votes

# Answer
@Clive has the right answer, but I have a sidenote that is too involved for a comment.

The search interface in Drupal is one of the least changeable, as far as the hook system and theming system goes (compared to the rest of Drupal). There are some modules for 6 that improve things (Custom Search and Search Config are two), but they only help to an extent. There is also the Apache Solr Search Integration project, which is probably the best long term solution if you can do Solr.

I have been in situations where Solr isn't an option, and the above mentioned modules don't do what the client needs. In this case, the proper thing to do is take the standard node\_search function and clone it into your own custom module, and then make modifications. Once you have this going, it is just a matter of rewiring the search form(s) and your templates. This works rather well, and you should consider this for your site as it makes applying updates a lot easier.
> 1 votes

---
Tags: 6, nodes
---


# Question
Title: variable_get() using "default value" with no reason in Pressflow 6
I'm currently having a problem with `variable_get()` that sometimes with no reason, returns the default value instead of the one from the database. I'm using memcached here (and the Drupal memcached module, of course).

Did anybody else also have this problem? How to fix it?

# Answer
If you look at the code for variable\_init() used by Pressflow, you will notice the following:

* If the `MAINTENANCE_MODE` constant is defined, it tries to acquire the "variable\_cache\_regenerate" lock; this means the code will not be executed until lock\_acquire() doesn't return `TRUE`.
* In the case `lock_acquire()` doesn't return `TRUE`, the function will call `lock_wait('variable_cache_regenerate')`, and then recursively call itself.
* After 49 recursive calls, the function set the `$variables` variable to an empty array; doing so, all Drupal variables are set to their default values.
* The comment in the function says:

> Try a limited number of times to avoid // infinite recursion if the database connection is invalid for
> // some reason, e.g., mysqld restart, loss of network, etc.

This behavior is not present in the function used by Drupal 6, where variable\_init() doesn't use any lock.

Similar code is used from Drupal 7, even though there is a slight difference: Drupal 7 reads the values of the Drupal variables from the database, while Pressflow doesn't do that. Compare the following snippets; the first one is used in Drupal 7, while the second one is used in Pressflow 6.

```
// Cache miss. Avoid a stampede.
$name = 'variable_init';
if (!lock_acquire($name, 1)) {
  // Another request is building the variable cache.
  // Wait, then re-run this function.
  lock_wait($name);
  return variable_initialize($conf);
}
else {
  // Proceed with variable rebuild.
  $variables = array_map('unserialize', db_query('SELECT name, value FROM {variable}')->fetchAllKeyed());
  cache_set('variables', $variables, 'cache_bootstrap');
  lock_release($name);

```

```
  // Wait for another request that is already doing this work.
  lock_wait('variable_cache_regenerate');

  // Run the function again. Try a limited number of times to avoid
  // infinite recursion if the database connection is invalid for
  // some reason, e.g., mysqld restart, loss of network, etc.
  $recursion_depth++;
  if ($recursion_depth < 50) {
    return variable_init($conf, $regenerate, $recursion_depth);
  }

  $variables = array();

```
> 2 votes

# Answer
Hmmm... It's going to be a tough one to track down - unless someone here has some good insight or experience of this...

When I've seen similar behaviour on my sites it was when using the (still broken) file cache on the Cache Router module which had (has) big reliability issues.

Since then I've also seen white Panels pages on my Memcache-enabled sites, I believe this was caused when the cached panels pages got too big to fit in the 1Mb 'buckets' memcache uses by default.

So it's possible your variables table has got too big to safely store in a standard 1Mb bucket, so you might have to make the buckets bigger, or maybe try the Variable Cleanup module. Did this start after you installed a poorly behaving module, perhaps?

I reckon it could also be a number of other things too - here's some ideas to look into:

* Old/faulty Drupal Memcache module.
* Silent errors/failures when data is set to or got from the (mem)cache.
* code further up in execution erroneously writing a value to the variable.
* Strongarm or another module override of variable values
* Some other OS or debugging reason that means the variables table didn't get loaded or cached properly - what I don't know!

Good luck!
> 0 votes

---
Tags: configuration, 6, caching
---


# Question
Title: Check if a field value is already in the database
I want to check if the entered value is already in the database or not. If it is, I want to stop creating the node, and show a message telling the users to change that value; if that value is not found in the database, the user should be able to create the node.

What is the correct function to call to stop the creation process?
How do I check if the field value is already in the database?

# Answer
> 2 votes
1. You should use hook\_node\_validate This allows you to return error on the specific field that fails. e.g.

```
if($query->rowCount() > 0) {
  form_set_error('machine_name', t('There already exists another node with same machine name - machine name has to be unique.'));
  // where machine_name is the field in this example
}

```
2. You wanna check database if value exists. Can you elaborate exactly what you wanna check? Is it to ensure a specific field only contains unique values?

---
Tags: 7
---


# Question
Title: How can I show/hide just one menu item based on user role?
I have a single menu item that I would like to show or hide based on user role.

Use case: I have a membership site with paid and free memberships. In the navigation menu, I want to show a link for users who do not have the "paid" role to the "Upgrade your account" page. There's no need to limit access; I simply want to show or hide the link.

I know I could make a separate menu and restrict access to that menu block by role, but is there an easy way to do the same for a single menu item link in an existing menu?

# Answer
> 1 votes
There is a way to do it without an extra module if the "Upgrade your Account" page is a view. Then you can limit access for that view to anonymous users and add the menu entry in that view.

# Answer
> 5 votes
You may try Menu per Role

> This module allows you to restrict access to menu items1 based on user roles. It depends on the Drupal core menu.module—just activate both modules and edit a menu item as usual. There will be a new fieldset that allows you to restrict access by role. The fieldset also appears in the node edit form.

D7 release is not stable yet its `7.x-1.x-dev`

# Answer
> 1 votes
Another module solution to this that I recently found is Menu Item Visibility. While it is still in beta, it actually works in D7 right now, which I couldn't get Menu Item per Role to do. (I had to keep clearing the cache every time a user saved their profile to rebuild the menu.)

---
Tags: 7, routes
---


title: Preprocess a specific table

text:
# Question
Title: Preprocess a specific table
I'm building a module to extend the functionality of Nodequeue. So in the nodequeue list I wanna add one more operation link (to the current View | Edit | Delete operations).

The list is build up in a table using theme('table') by Nodequeue.

So for me the be able to extend the content of this table and add one more link, I'm thinking I'll have to preprocess the table theme? So I'll make a MYMODULE\_preprocess\_table(&$variables)?

But I just feels like its totally overkill? It must be more simple than that? Like in the Form API hooks, I have hook\_form\_FORM\_ID\_alter().

Is there any alternative to hook\_preprocess\_hook?

# Answer
Unlike forms, specific invocations of theme functions don't have identifiers associated with them, so there's no mechanism like `hook_form_FORM_ID_alter()` that you can use unfortunately.

I can only find one call to `theme('table')` in the nodequeue module so I think you're talking about the `theme_nodequeue_arrange_subqueue_form_table()` function.

Luckily enough, this function assigns a unique id to each table (which believe me isn't always the case), so at least you *can* target it in a preprocess function:

```
function MYMODULE_preprocess_table(&$variables) {
  if (isset($variables['attributes']['id']) && $variables['attributes']['id'] == 'the_id') {
    // Alter the table
  }
}

```

As the `theme_nodequeue_arrange_subqueue_form_table()` function actually renders the table to a string (it has to, being that it's a theme function itself), I don't think there's any other way to do this.

The other (more long-winded way) would be to implement your own version of the entire `theme_nodequeue_arrange_subqueue_form_table()` function, copying the code from the original and just changing what you need to.
> 3 votes

---
Tags: 7, theming
---


title: Conflict between Corolla and Panels?

text:
# Question
Title: Conflict between Corolla and Panels?
Wanting to use a mobile savvy html5 theme, I currently chose Adaptive Themes "Corolla", however I have noticed over the past 3-4 days that when I now attempt to add any content to Panel, the Panel interface just hangs and shows the blue 'timer' graphic and goes no where even after 10 minutes. If I revert back to say Bartik and or standard theme it works as expected. Since I'm 'upskilling' with a view to future employment, I would like to know what causes such issues now of for future reference, what is is hanging on for?

Of course, cosmetically Corolla can be changed for a custom HTML5 theme, but an answer would be helpful. I'm running a webdev Ubuntu LAMP stack on a home webdev box using pure apache so no wamp/xammp etc. The webdev box emulates a live production server for future commercial projects.

The module versions are:

cTools: 7.X.1.0 alpha#1 (doesn't matter if it is later). Panels: 7.x.3.0 Alpha#2 Views: 7.x.3.0 alpha#1

I have tried a number of the above versions and I have multiple D7 projects on my LAMP box, and it makes no difference so I have concluded it is Corolla, even with the latest strain. I have no desire to go down to Drupal v6. Thank you.

Paul B.

# Answer
> 1 votes
I'm running Pixture Reloaded, another Adaptivetheme and I use Panels for nearly everything on my site and have experienced no such problems.

I have used both the 2.x and 3.x series with no incidents.

I doubt your problem is Corolla; from your post, it is clear you are still running alpha versions of Panels and Views. These modules have had stable and security releases for D7-- Views is now version 3.3. You really need to keep your modules up-to-date when there are security releases

Update all your modules to the latest versions (or at least Ctools, Views, and Panels), run `update.php`, and then do this:

1. Enable Corolla.
2. Clear the cache twice.
3. Go to the Corolla theme settings page.
4. Click save. (It doesn't matter if you make any changes.)
5. Clear the cache twice again.

This will ensure that all the files that are automatically generated by Corolla have been rebuilt properly and should fix the problem.

---
Tags: panels
---


# Question
Title: What is the purpose and differences between drupal_goto(),drupal_redirect_form() and $form_state['redirect']?
May you explain me the differences between `drupal_goto()`, `drupal_redirect_form()` and `$form_state['redirect']` with examples?

How can I pass the form values with these functions, and how can I retrieve the values using `$_GET` and `$_POST` in Drupal 7? Which is the better one to use?

# Answer
> 19 votes
First off, drupal\_redirect\_form() is not a function that a third-party module should use; it's a function used by Drupal code, and it is only used from two Drupal functions. In your code you should use drupal\_goto(), or `$form_state['redirect']`.

The difference between `drupal_goto()`, and `$form_state['redirect']` is that a form submission handler should never use `drupal_goto()`, which should be used, for example, from a page callback for a page without forms. The main reason not to use `drupal_goto()` in a form submission handler is that calling it would stop the other form submission handlers to be invoked. `drupal_goto()` contains the following code:

```
  // Drupal 6.
  // Even though session_write_close() is registered as a shutdown function, we
  // need all session data written to the database before redirecting.
  session_write_close();

  header('Location: ' . $url, TRUE, $http_response_code);

  // The "Location" header sends a redirect status code to the HTTP daemon. In
  // some cases this can be wrong, so we make sure none of the code below the
  // drupal_goto() call gets executed upon redirection.
  exit();

```

```
  // Drupal 7.
  header('Location: ' . $url, TRUE, $http_response_code);

  // The "Location" header sends a redirect status code to the HTTP daemon. In
  // some cases this can be wrong, so we make sure none of the code below the
  // drupal_goto() call gets executed upon redirection.
  drupal_exit($url);

```

Both `exit()` and `drupal_exit()` cause Drupal to stop running, and the output be returned to the browser; this means that other form submission handlers are not executed. Even if the form submission handler is for a form you use in your own module, you cannot know for sure how many form submission handlers need to be executed, and if your form submission handler is effectively the last one to be executed; other modules can add any form submission handler to your form. Using `drupal_goto()`, you are also avoiding that other Drupal code is executed; this could have any collateral effect, in the case of forms.

As per passing values to the page where the user is redirected, you can use code similar to the following one.

```
$form_state['redirect'] = array(
  $redirect_path,
  array(
    'query' => array(
      'foo' => $form_state['values']['foo'],
    ),
  ),
);

```

This snippet would cause the user to be redirect to `http://your.site.domain/$redirect_path?foo=$form_state['values']['foo']`. That page will get the value of `$form_state['values']['foo']` in `$_GET['foo']`.

Consider also that, in the case you need to pass to the page where you are redirecting the user all the values submitted by the user in the form, you probably need to rewrite the code you wrote. If the page to which you are redirecting the user needs those values to, e.g., save them in the database, then that code should be in the form submission handler, and not in the other page callback. If the page needs those values to output HTML, then the form submission handler could render the output, and save it in a session variable, which is then used from the new page handler to show its own output.
In any case, all the values submitted from users in the form should not be passed to another page handler through `$_GET` or `$_POST`. Passing some of the submitted values is fine, though.

---
Tags: forms
---


title: How does bandwidth optimization work?

text:
# Question
Title: How does bandwidth optimization work?
I have optimized to combine all CSS and JavaScript files in my site.

.

If I run Yslow in Firefox to see the components loaded for this site, it shows that it loads 8 JavaScript files, and 8 CSS files.

Why aren't these files combined?

# Answer
Aggregated CSS and JS files in Drupal 7 are split up into groups, so you'll naturally get more files than you're used to seeing in Drupal 6.

I won't go in to the whole thing as there's already an excellent article out there that explains it in good detail.

> D7 uses a new strategy to address this - aggregates are split into three groups: CSS\_SYSTEM, CSS\_DEFAULT, and CSS\_THEME for styles, and JS\_LIBRARY, JS\_DEFAULT, and JS\_THEME for Javascript. Each group is further subdivided into files that load on every page, and files that load conditionally based on the 'every\_page' option. Note this option has some potential for confusion - it doesn't cause the file to be loaded on every page - it's merely a "hint" to the core system to place it in that group.
>
> Ultimately, the intent of these divisions is to group files into functional groups that are smaller and less likely to be split by an errant conditional style or script. We get separate files for core libraries, the theme, and page-specific files. Looking at the results, a stock Drupal 7 outputs eight stylesheets (including browser styles), while D6 only has three in the default install. Is this optimal? The answer will be different for each site.

If it's causing you problems, you might want to have a look at the Core Library module:

> This module changes the Drupal core aggregation mecanism process. It greatly reduces I/O and aggregated number of files, and improves chances of client cache hit, therefore while it produces bigger aggregated files, it reduces greatly the bandwidth utilization while users browse.
> 10 votes

---
Tags: performance
---


title: Thumbnails limit max first 6 images

text:
# Question
Title: Thumbnails limit max first 6 images
I'm using Drupal 7 and create a module for my content thumbnail images frontpage display. Working this:

```
 if(count($p_detail->field_slide) > 0){
            $output .= '<div class="right">';
            $output .= '<ul class="thumbs">';
            $i=6;
            foreach($p_detail->field_slide['und'] as $thumb):
                $img_path = $thumb['uri'];
                $img_url = image_style_url('tmb_240x117', $img_path);
                $img_file = '<img src="'.$img_url.'" alt="'.$p_detail->title.'" />';

                $output .= '<li>
                                <a href="'.$p_url.'">
                                    '.$img_file.'
                                    <div class="shadow"></div>
                                    <div class="hoverimg"></div>
                                 </a>
                                <div class="img_no">0'.$i.'</div>
                            </li>';
                $i--;
            endforeach;
            $output .= '</ul>';
            $output .= '</div>';
        }

```

My thumbnails, field\_slide and i want only first 6 thumbnails (if have 6 images... for exam, have 2 images, display 2 thumbnails)

How can i do this?

# Answer
> 1 votes
If I understand you correctly then you just need to break out of the foreach loop after you got 6 thumbnails saved in the `$output` variable. With that addition the end of your loop would look like this:

```
if ($i == 1) break;
$i--;
endforeach;

```

---
Tags: 7, entities, media
---


# Question
Title: Display last 3 articles in 3 columns layout in Homepage
I would like to erase the welcome message on my homepage and to do that I need to add the last 3 articles created which will be stored in 3 columns like : \[**article1**\]\[**article2**\]\[**article3**\]

Any ideas to do that? Maybe with Display suite or Mini Panels something like that?

Thanks!

# Answer
> 3 votes
Why not use views with a descending sort on create date and limit the number of displayed items to 3. For the layout you can define css for the .views-row class (ex. width: 33%), for the styling you can use Display Suite or use views fields display mode.

---
Tags: 7, nodes
---


# Question
Title: Automatically generate a short description of a page when a user posts a link
On facebook, google plus and similar websites, when someone posts a link, the thumbnail and short description of the page is automatically generated. See the screenshot below.

Is it possible to this in Drupal 7 ? If yes, how? Is there any module for it?

# Answer
> 1 votes
Look at the source for that page, you'll see this

```
<meta name='description' content='In honor of Wolfenstein 3D's 20th anniversary, the game will be released for free to play in browser today.'/>

```

Should be fairly straightforward to grab that!

# Answer
> 0 votes
It all depends on the meta tags you have set. The easiest way to accomplish this is by installing the Meta tags module.

Once enabled, you can navigate to the configuration page and set configuration for auto-generated tags. If you need to have specific tags for a node, you can edit that node and set the meta tags there.

You should enable the Open Graph meta tags submodule, as Facebook looks for those tags when you want to share on Facebook. Whenever you update the Open Graph tags, run it through the Facebook debugger so you can see what Facebook will grab. Most of the time, Facebook should grab whatever images are available on the page and use those as thumbnails.

I use a combination of Tweet Button, Facebook Share and Google Plus One but i'm sure there are "all-in-one" shares that you can use. The most important thing remember is that if the meta tags aren't correct in the HTML, then they probably won't work correctly when you try to share your page.

---
Tags: entities, navigation
---


# Question
Title: Set a cookie whenever front page is viewed
I run a Drupal 7 site (currently 7.15) since longer time and have the problem with cookies:

I need 2 cookies for non-Drupal PHP-scripts at my web site.

I set them in the hook\_init of my custom module:

```
/**
 * Implements hook_user_login().
 */
function pref_user_login(&$edit, $account) {
    if ($account->uid <= 0) {
      return;
    }

    #drupal_set_message('<p>Hello, '.$account->name.'</p>');
    $auth  = md5(join('_', array($account->uid, MY_SECRET)));
    $year  = time() + 60 * 60 * 24 * 30 * 12;
    setcookie('pref_id', $account->uid, $year, '/', '.preferans.de');
    setcookie('pref_auth', $auth, $year, '/', '.preferans.de');
}

```

The problem is, that I need to set the both cookies each time a logged in user visits the front page and not just when the user logs in.

Does anybody please have an idea how to do it, maybe by JavaScript if I can't do it regular way?

# Answer
You could do this in hook\_preprocess\_page() and instead of setting a variable, you could do something like this:

```
function pref_preprocess_page(&$vars) {
  global $user;

  // whatever other preprocess stuff you want to do here

  if ($user->uid && drupal_is_front_page()) {
    $auth  = md5(join('_', array($user->uid, MY_SECRET)));
    $year  = time() + 60 * 60 * 24 * 30 * 12;
    setcookie('pref_id', $account->uid, $year, '/', '.preferans.de');
    setcookie('pref_auth', $auth, $year, '/', '.preferans.de');
  }

}

```
> 11 votes

---
Tags: 7, cookies
---


title: Display average from a column?

text:
# Question
Title: Display average from a column?
EDITED: This has been altered to include the code suggested by Dooshta.

I need to fill a computed field with the average value of all entries in a certain field, and only from nodes that have a specific node reference field.

What I have right now in my Computed Field is:

```
$nids = db_query('
  SELECT entity_id FROM {field_revision_field_venue_reference_review}
  WHERE field_venue_reference_review_target_id = :nid',
  array(':nid' => $entity->nid)
)->fetchCol();

$entity_field[0]['value'] = db_query('
   SELECT AVG(field_payment_review_value) FROM {field_data_field_payment_review}
   WHERE entity_id IN (:nids)',
   array(':nids' => $nids)
)->fetchField();

```

This is working, and displays the correct average from the correct nodes. However, I get a PODexception error on some pages that do not include the above code. This is confusing to me, because it seems that if there is bad syntax, then I should get the error on the page using the code as well as pages not using the code, right? Either that or it just shouldn't work.

As requested by Booshta, here are screenshots of the tables I'm querying. The first is the table containing the entity reference field in the `$nids` part of the query

The second is the table containg the values being averaged in the `$entity_field` part of the query

# Answer
I'm not familiar with the computed field module and not sure I completely understand the relationships between your nodes and fields, but here's about how you should be able to get things working.

The first query seems like it would be alright if you'd remove that extra closing bracket and used `fetchField()` to retrieve the value:

```
$entity_field[0]['value'] = db_query('
   SELECT AVG(field_payment_review_value) FROM {field_data_field_payment_review}
')->fetchField();

```

The second one needs some more work. I'm assuming that you have review nodes with the ratings and every review node is linked to a business node with a reference field of some sort.

First I would get the nid-s of those review nodes that are linked to the current business node as an array (using `fetchCol()`) with something like this:

```
$nids = db_query('
  SELECT entity_id FROM {field_data_field_business_reference}
  WHERE field_business_reference = :nid AND entity_type = :type AND bundle = :bundle',
  array(':nid' => $entity->nid, ':type' => 'node', ':bundle' => 'review')
)->fetchCol();

```

Then get the average:

```
$entity_field[0]['value'] = db_query('
   SELECT AVG(field_payment_review_value) FROM {field_data_field_payment_review}
   WHERE entity_id IN (:nids) AND entity_type = :type AND bundle = :bundle',
   array(':nids' => $nids, ':type' => 'node', ':bundle' => 'review')
)->fetchField();

```

UPDATE:

To avoid the error you're getting you can try wrapping the code inside some `if` statements to make sure it won't be executed when necessary criteria is not met:

```
$node = menu_get_object();
if (isset($node->type) && $node->type == 'venue') {
  // put the query that retrieves the nids here.
  if (is_array($nids) && !empty($nids)) {
    // put the query that calculates the average here.
  }
}

```

If that's too restrictive you might get away with just this much:

```
  // put the query that retrieves the nids here.
  if (is_array($nids) && !empty($nids)) {
    // put the query that calculates the average here.
  }

```
> 1 votes

---
Tags: entities
---


# Question
Title: How do I get the node ID from the view's URL?
I want to add a comment form to my view by using the following code:

```
print drupal_get_form('comment_node_project_form', array('nid' => $node->nid), 'comment');

```

However, it shows up a error saying that the variable $node-\>nid is undefined. I then realized it is a view, not a node.

In the view, by choosing the right URL, e.g. /projects/{username}/{nodeid}, I only show one content.

I guess I can get the node ID by parsing the 3rd argument of the URL. How do I get the node ID from the view's URL?

# Answer
If the view uses fields, you can add a field labeled `Content: Nid` \- and either build the link in the template by yourself or try to Rewrite the field in the Views admin UI. If the View uses display views, such as Teaser, you should be able to use the $node variable in the teaser (in this case) tpl file.
> 0 votes

---
Tags: views, nodes, uri
---