# Question
Title: Getting the id of all the elements in a form with errors
I am using drupal 6. All I want is to find the id of each element that has error in form\_get\_errors. I am using preprocess to theme the form error section and tried using $vars\['form'\] with no luck so far. how can i do that?

# Answer
You might need to write a custom module for this:

1. Use hook\_form\_alter for the specific form and call form\_get\_errors.
2. Theme the results of form\_get\_erros with hook\_theme to pass the results back to your theme.
> 1 votes

---
Tags: forms, theming
---


title: Entities in Drupal 7

text:
# Question
Title: Entities in Drupal 7
What are Drupal Entities in Drupal 7? I understand that Drupal Commerce built Products as an Entity. I know now there is a core Entity API and an contrib add on for Entity API.

I have a few projects this year where I would like to use Drupal 7, NoSQL and possibly the Entity API if it calls for it- but I am having trouble seeing where it would be needed.

Assuming you were building a job listing site- a job isn't necessarily like node content, could/would you make that an Entity?

Additionally, can you still get the ability to talk to modules with the Entity and how is that done? Like, a Job Posting entity getting aliased with Pathauto and exposed in Views as well as appear in XML Sitemap.

# Answer
A entity is data structure defined by hook\_entity\_info() and can be fieldable, which means that you can add fields to them.

In Drupal 7 Core, Nodes, Users, Comments, Vocabularies and Terms are entities.

In Contrib, there are many more, for example private messages and commerce as like a dozen of them ;)

However, I think job postings are perfectly fine as nodes :) Entities don't automatically have Pathauto (Tokens), Views etc. integration.
> 9 votes

# Answer
**Entities are a meta level above nodes, users, etc.**

Essentially if you look at D6, there are a lot of duplicate modules, and functionality across these types of thing. For example there are modules to attach cck fields to users and to taxonomy terms.

In D7 a decision was made to treat these in the same way, architecturally, so if you have a module which does something to entities, it should work for nodes, terms and users.

In previous versions of Drupal, a module like Commerce would have had two options, to build a custom node type, or to go completely outside of Drupal's internal systems and define their own type of thing. With entities, it is possible to describe a Product as a type of thing, distinct from existing types, but still leverage features like fields in their makeup.

> Assuming you were building a job listing site- a job isn't necessarily like node content, could/would you make that an Entity?

You could. I think you should be careful of making entities of things too quickly. Often custom node types will still do what you want. Is a job listing a different type of thing to a node, or is it a node with some special properties?
> 9 votes

# Answer
I've started using entities in a few of my projects for things that weren't really "content". We use them for things where we don't really care when it was published or who the author was.

The real benefits of defining entities are if you're developing your own custom modules. You get a nice table structure and a bunch of Drupal goodness (Fieldability, Views integration, ...) for free. No more creating your own custom table structures or retrofitting a node type to your needs. Also, I like how lightweight they are so performance-wise entities should be better. If you've done any queries in D6 with nodes you'll understand what I mean.
> 3 votes

# Answer
Nodes, users, taxonomies are examples of Drupal entities. The main feature of an entity is that it can be assigned to other entities: a user is associated with a node, and a taxonomy can be assigned to nodes, and users.

If what you describe as job can be assigned to a user, or a node, then I would make it an entity. If what you can "job" is just a content type, then I would not make it an entity.
> 1 votes

# Answer
If you want to say that in a really few word, you can say that en entity is just a *piece of data that drupal is aware of, and it can be store anywhere.*
> 1 votes

---
Tags: 7, entities
---


# Question
Title: Change the code in the module from the front end of drupal
I have created my custom module. Can i edit my module from the from end of drupal rather then going to backend and editing the module. Is there any module for this purpose?

# Answer
I'm not sure there is a module for this, but this thread begins to touch on how to create your own module admin page. How to add module to admin/config page?
> 1 votes

---
Tags: 7
---


title: CSS Mobile-compatible Theme for Drupal?

text:
# Question
Title: CSS Mobile-compatible Theme for Drupal?
Are there any CSS Mobile-compatible Theme for Drupal?

Example of a CSS mobile-compatible site: http://framelessgrid.com/

# Answer
> 1 votes
"Responsive", as mentioned in your comment, is indeed the buzzword. On a small scale, I have had success using Sky to create a mobile friendly site.

---
Tags: 7, theming
---


title: How to add categories to content

text:
# Question
Title: How to add categories to content
I'm still new to Drupal 7. I've read a couple of things on how Drupal works, but I don't quite get some things though.

How do I create articles for different categories? I would like to make articles that can be listed under graphics, painting, or 3D etc. How can I categorize them in the main menus? How different is this to the blogging module or book module?

I know this may have been posted similarly here, but I would just want a simple explanation not found in long chapters. Thanks guys.

# Answer
You're probably looking for taxonomy. Create a vocabulary and name it something like "categories". Add terms for each category you want like graphics,3D,ect. Then just add links in your navigation menu. Under your content type, add a term reference field and choose your "categories" vocabulary. That way your users can choose a category when they submit something.
> 8 votes

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


# Question
Title: What is the difference between profile and content profile module?
There is a core module called Profile which adds the profile fields; there is also a contributed module called Content Profile that does the same thing (up to my knowledge.)

May anyone clear me the difference between these two modules?
In which case should we go for the Profile module, and in which case for Content Profile module?

# Answer
> 4 votes
Assuming you're in Drupal 6, Content Profile allows you to set up a node type that will act as user profiles. this is more extensible than the core profile module, which essentially just adds basic fields.

Also, because Content Profile profiles are nodes, you get more flexibility with what fields you can have on a user profile. Any core or contrib field will be usable with Content Profile ( e.g. image field, file field, node reference), whereas the core profile module has limited options. You can also use Content Profiles with Views more efficiently.

In short:

Content Profile creates user profiles as nodes, with all the benefits that entails (Views being the big one for me).

Core profile module adds a basic profile to the user that has less customisation/options.

Check out this video for some more help with Content Profile.

---
Tags: users
---


# Question
Title: Drupal 7 - Programmatically create field collection within field collection
Example: Map (node) has unlimited areas (field collection field). Each area has unlimited layers (field collection field). The area fc. have normal fields and the layer fc. The layer fc. only have normal fields.

I can create a field collection on the node, but unable to figure out how to attach another field collection to it. I assume the 2nd fc. should use the 1st fc. id as HostEntity.

The code is running in a custom module, and it should create the Map node.

Any ideas, suggestions?

# Answer
> 3 votes
I just figured this out, please see field collection module issue:

http://drupal.org/node/1393552#comment-5428548

---
Tags: entities
---


# Question
Title: Can a theme name be started with a number?
Can I start a theme name with a number? For example: "123go"

Does Drupal recognize folders & files that start with it?

Does it work in the temple.php as the start of a function?

# Answer
> 4 votes
oh, got it- "A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores."

php.net/manual/en/functions.user-defined.php

That answers that question. Don't start a theme name with a number because it can't be used as a function in template.php

---
Tags: 7, theming
---


# Question
Title: Showing the date of the latest edit, instead of node's posting date
I have some nodes I update frequently, but in content pane I can see the posting date of node.

How can I make Drupal 7 show the date of the latest edit, instead of the posting date?

# Answer
> 4 votes
You can use hook\_node\_view to add the change date content like this:

```
/**
* Implement hook_node_view()
*/
function youmodule_node_view($node, $view_mode, $langcode) {

    $changde_date = date('l jS \of F Y h:i:s A', $node->changed);
    $node->content['body'][0]['#markup'] = "<div class='changed-date'>$changde_date</div>" . $node->content['body'][0]['#markup'];
}

```

# Answer
> 5 votes
I would tackle this in a template\_preprocess\_node, either in a module or in your theme.

```
function mytheme_preprocess_node (&$variables)
{
   $variables['date'] = format_date($variables['node']->changed);
}

```

Depending on your node template, you may also want to do something like

```
function mytheme_preprocess_node (&$variables)
{
   $variables['date'] = format_date($variables['node']->changed);

   if (variable_get('node_submitted_' . $variables['node']->type, TRUE)) {
     $variables['display_submitted'] = TRUE;
     $variables['submitted'] = t('Edited by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $variables['date']));
     $variables['user_picture'] = theme_get_setting('toggle_node_user_picture') ? theme('user_picture', array('account' => $node)) : '';
   } else {
     $variables['display_submitted'] = FALSE;
     $variables['submitted'] = '';
     $variables['user_picture'] = '';
   }
}

```

so that your new `$date` gets used in `$submitted`, due to the preproccess/process order.

You can also play around with variants. For example, you could have both created and last edited dates; you would juust need to set up the variables in the preprocess function, and then use them in your `node.tpl.php`.

---
Tags: 7, datetime, nodes
---


title: Template not being picked up?

text:
# Question
Title: Template not being picked up?
I added a node-product.tpl.php file to my theme and it is completely ignored.

I reset the caches, multiple times, and tested with devel + devel\_themer to see that the name was correct and it is. It says it searches for:

* node-product.tpl.php
* node-product.tpl.php
* node.tpl.php

Why would the core theme() function not find that template?

My only answer would be that somehow the theme path is not yet available in the theme() function at the time the product is being generated.

# Answer
(Assuming you are on Drupal 6, as it seems) you also need to copy the default node.tpl.php (e.g. the one from your base theme) in the same theme directory you are putting the override file (node-product.tpl.php) in order for the theme engine to pick it up:

> If you are implementing a suggestion, rename the file to the suggestion name it should have. Note that some suggestion files will not be recognized unless their base file is also present -- for instance, if you want to make a node content type suggestion file for your content type, you need to have node.tpl.php present in your theme directory order for your node-my\_content\_type.tpl.php file to be recognized. (Beginners guide to overriding themable output)
> 4 votes

---
Tags: nodes, theming, ubercart
---


# Question
Title: Difference between router path and link path?
I have recently started looking into the drupal menu system. I am not able to understand the difference between a `router_path` and the `link_path`. Both point to the same location in my installation.

# Answer
Pro Drupal Development, Second Edition describes them as:

> `menu_links.link_path` is the Drupal path or external path this link points to.
>
> `menu_links.router_path` is for links corresponding to a Drupal path (0 means external), this connects the link to a `menu_router.path` for joins.
> 0 votes

---
Tags: routes, uri
---


# Question
Title: Is there a function to clear the watchdog log inside a module?
I don't want to clear the watchdog log from the UI each time while debugging. It becomes time consuming and tedious.

Is there a Drupal function to clear the watchdog log inside a module?

# Answer
```
db_delete('watchdog')->execute();

```
> 15 votes

# Answer
The best way to do this is via drush:

```
$ drush help watchdog-delete
Delete watchdog messages. Arguments or options must be provided to specify which messages to delete.

Examples:
 drush watchdog-delete all                 Delete all messages.
 drush watchdog-delete 64                  Delete messages with id 64.
 drush watchdog-delete "cron run           Delete messages containing the string "cron run succesful".
 succesful"
 drush watchdog-delete --severity=notice   Delete all messages with a severity of notice.
 drush watchdog-delete --type=cron         Delete all messages of type cron.

Arguments:
 severity                                  Delete messages of a given severity level.
 type                                      Delete messages of a given type.

Aliases: wd-del, wd-delete

```
> 44 votes

---
Tags: 7
---


# Question
Title: Creating testing local site from online production site
I have tried to perform this action several times, only to find that I can never login to the previously created database when I setup my local environment. I have recently picked up the practice to have two sites: development and production, sometimes a third one in between.

Here is my process, maybe I am ommiting a step or two:

* Create fresh local Database (same name as online) with PHPMyAdmin
* Install Drupal 6 using this database
* Setup Drupal installation
* Import online Database backup onto new local installation
* And here is where I get stuck everytime, with the dreaded:

> Access denied for user 'admin'@'localhost' (using password: YES)\*

I have edited settings.php file to work from local to online, so I thought I understood how to do this process in reverse, but apparently I don't.

As a last resource, I have even changed admin's and other user's passwords directly in the database via PHPMyAdmin, and used these in settings.php so I might log in, but it just won't happen.

# Answer
First, try to do the move the project to your server again but DO NOT go through the installation process. Simple add all the files to the proper directory then move in all the data. After that, just try going to the home page.

If that wasn't it I feel like you probably skipped giving 'admin'@'localhost' permission to access your db.

Try checking admin's priviledges in the MySQL console:

```
mysql> SHOW GRANTS FOR 'admin'@'localhost';

```

If admin doesn't have privileges, go into MySQL console and:

1. Create a user(if you don't have one made): `mysql>CREATE USER 'admin'@'localhost' IDENTIFIED BY 'apassword';`
2. Now, give admin priviledges: `mysql>GRANT ALL PRIVILEGES ON *.* TO 'admin'@'localhost'`
3. Lastly, flush! `mysql>FLUSH PRIVILEGES;`

Hope this fixes it!
> 1 votes

---
Tags: 6, database, installation, users
---


# Question
Title: YouTube thumbnails - options for adjusting interface widgets and behaviour when clicked?
I wish to add YouTube videos to my site as links - I want to use a thumbnail of the video. I'm not concerned with which thumbnail used (as discussed here: How to control preview image in Youtube)

What I am concerned with is how the play etc. buttons look on a thumbnail (i.e. everything reduced in size from how it would appear in YouTube).

What options do YouTube themselves offer? And what about 3rd-party solutions?

Facebook for example does this quite well - the thumbnail is not too cluttered and will expand when clicked onto to a usable size to view the video at a reasonable size on the same page (an example of my requirement for behaviour when clicked).

Any examples of such customisations on Drupal sites, please? Thanks in advance :)

# Answer
> 2 votes
I recommend the Video Embed Field module, it's pretty new but under active development. It will just show the thumbnail and when you click it load the video player page.

However, they are working on a lightbox integration (video plays in a popup modal) and you might want to suggest the "Facebook player functionality" as a new feature to them.

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


# Question
Title: Send a context from a panel page to a view integrated in it?
I'm struggling trying to figure out how to do the following :

* I have 3 different views displaying content filtered by different features (content-type, custom boolean field, etc.).
* I want to create 3 panel-pages in which I'll integrate those 3 views. Each of those panel-page will only be displaying the content authored by one different member beetween three specific (named AGS, MM, admin).
* **Thus** I wanted to set up a contextual filter in my view which would be the content author ID. Author wasn't available so I chose `User : Authmap ID` (?). Then, in my panel-page, at `Variants > Panel > Contexts` I've tried to send a User context by selecting "AGS". I also checked "Send Arguments" in the view settings at `Variants > Panel > Content`.

... But it's not working ! :( I'd also love to send other context to my views (boolean, etc). But let's first try to make this thing working out...

Anyone's enlightenment will be greatly appreciated ! Thks.

\[CONFIG : Drupal 7.4 - and most recent Views and Panels\]

# Answer
> 4 votes
First thing to do is fix your view. In order to have author ID as a filter you need to add the "Content: Author" relationship. After adding that you will see a lot more options for User in the fields and filters. You can now chose "User: UID" for your contextual filter.

Next thing to do is to edit your panel. Add a user context to your panel and chose "Select a user" for the context type. Type in the username of the user and check "Reset identifier to username."

Now go to your panels content and edit the view settings. You should see the "User: UID" context at the top. Choose the "User ID" from the drop down.

You should now only see content from the user you chose in the context when viewing that panel page.

# Answer
> 2 votes
I was running into a similar problem, I was trying to display a view inside a panel. The view displayed fine, but contextual filters were not working. The reason being, the contextual filters expect and argument and panels uses contexts. (it's really confusing because now they are calling them contextual filters). What I had to do to get it to work is change the style of the view to view pane (you need this module enabled). You will then get an additional menu called "pane settings". One of the settings is argument input, select from context, and it should work fine.

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


# Question
Title: How can I collapse the *sidebar first* region when the browser width is less than 900 pixels wide?
How can I collapse the *sidebar first* region when the browser width is less than 900 pixels wide? Within the theme's .info file the following is set: settings\[sidebar\_first\_width\] = 4 How can I programatically change the above to 0 so that the *sidebar first* region does not take up any space within the page when the containing browser wide is less than 900 pixels wide? One possible approach is to utilize the media query at the bottom of the themes associated .css file so that the *sidebar first* region is collapsed when less than 900 pixels based on the following link: http://www.alistapart.com/articles/responsive-web-design/ but I am not sure if this is the best approach or what css to put in that would do this as an example from the above link: @media screen and (max-device-width: 480px) { .column { float: none; } }

John

# Answer
A media query, just like the one you list, is indeed the proper way to do this.

1. Obviously you would first need to adjust the width from 480 to 900, but also, you may want to choose "max-width", instead of "max-device-width", as the former will work in a small browser window on a large screen as well. That's really up to you though.
2. You say that you want to *collapse* the sidebar, which means you may also want to "display: none;", instead of "float: none;".
3. Strictly speaking, the "screen and", is not necessary. If you want the rule to apply to all media types, such as print and handheld, you can just omit it.

Example 1, unfloat the sidebar, only on screen media:

```
@media screen and (max-width: 900px) {
  .sidebar-first {
    float: none;
  }
}

```

Example 2, hide the sidebar, all media:

```
@media (max-width: 900px) {
  .sidebar-first {
    display: none;
  }
}

```
> 1 votes

---
Tags: theming
---


# Question
Title: Move Comment form/render out of node.tpl.php (into separate region)
I would like to render the `$content['comments']` part of my nodes outside the node.tpl.php file, and have the comments (form and all) rendered in a separate region of my theme.

I've noticed Commentsblock does something along these lines, but requires a view, and doesn't seem too complete.

Could I do some preprocessing to get the entire comments renderable array into the page.tpl.php template if I'm on a certain node type page, rather than rendering the array inside node.tpl.php? (Something along the lines of this comment).

Also, wouldn't simply not rendering the $content\['comments'\], and then getting the comments via some other method (like a View, how Commentsblock works) cause Drupal to load all the comments *twice* (worse performance, etc.)?

# Answer
You *should* be able to just hide() the comments in the node template and then create a block that calls menu\_get\_object() and then prints them there...
> 6 votes

# Answer
I would suggest you use Panels for this.

1. Activate the Panels module
2. Enable the node override, "node\_view"
3. Add a variant, go through the wizard. Most important part in the wizard is creating a selection rule with "Node:type" being the node type you want to do this on. Or any other selection rule that matches your critera.
4. Click the little cog in a suitable region for the node content -\> Node -\> Node Content.
5. Click the little cog in a suitable region for the comment form -\> Node -\> Comment form.

Other resources: Video introduction to Page Manager and Panels
> 2 votes

---
Tags: 7, theming, comments
---


# Question
Title: Drupal 6 failing to login user in IE7 but forwarding to user account page
We have just updated a Drupal 6 website to Drupal 6.22 for a client. However, the client is now no longer able to login to their account when using IE7. After clicking "Log in" the client is correctly being forwarded to their user account page, but is getting a "You are not authorized to access this page" message and remain unauthenticated. The client has now choice but to use IE7 at work, so switching browser is not an option.

We have tried testing this in various browsers in our office (Chrome, Firefox, IE8 - we don't have access to IE7) and can successfully sign-in to the site every time.

We have tried repairing the sessions table (in case that was corrupted) and still no luck. Our cookie domain is being set in settings.php as: $cookie\_domain = $\_SERVER\["HTTP\_HOST"\];

Any suggestions?

# Answer
I would try the following in order:

1. Ask the user to clear their browser cache.
2. Rebuild permissions - admin/content/node-settings/rebuild
3. Create a test account with the same roles.
4. Manually verify the roles and permissions haven't changed.
> 0 votes

---
Tags: 6, users
---


title: Parsing json with jquery

text:
# Question
Title: Parsing json with jquery
Wrapping one's head around the json/ajax/jquery relationship is quite a battle for someone new to it. But what a fun puzzle! One of the most confusing parts has been how to frame this question.

Using php in my module file, utilizing db\_query function, the database query has been made, and now we're going to loop through the results, create json data and encode it and send it back to jquery for re-inclusion into our website.

$json = array(); foreach ($query as $row) {

```
      $fid = $row->thefid;
      $file = file_load($fid);

      $jsonelement=array(

         'title' => $row->title,
         'path' => $file->uri,
         'style_name' => 'swatch'

        );
          array_push($json,$jsonelement);
    }

        // encode to json
        $jsonstring = drupal_json_encode($json);

        //output the json string
        drupal_json_output($jsonstring);

```

This returns this json string:

\[{"title":"Test Swatch 5","path":"4DS\_AB\_BrittanyBeige\_CAT.jpg","style\_name":"swatch"},{"title":"Test Swatch 6","path":"4DS\_AB\_ArdennesGray\_CAT.jpg","style\_name":"swatch"}\]

Where I am having trouble, is figuring out how to access each element.

A simple side example to illustrate the issue without an array :

var data = jQuery.parseJSON('{"title":"Test Swatch 5","path":"4DS\_AB\_BrittanyBeige\_CAT.jpg","style\_name":"swatch"}');

alert (data.title); data.title returns the string Test Swatch 5, which is what I expect.

However, in the output I have (back at the top of the question) the json object(s) has an extra set of brackets around it suggesting another array that I am not sure how to access, but for now I will call it x.

My question is 2 parts and any one of the solutions will get me to where I need to be.

1) Is there a way to get the key value pairs out of the current output I have already created? Any example would be helpful.

2) Is there a way to frame the output in a way to utilize x as the name of the array so that the values can be accessed via myjson.x.title or myjson.x.path or myjson.x.style\_name, etc..?

I noticed a very similar question here with no answer as well https://stackoverflow.com/questions/1607937/how-to-parse-json-array-in-jquery

# Answer
> 2 votes
You should be able to access the JSON response objects by saying data\[0\] and data\[1\]. These will be the swatches. So instead of namespacing the objects (swatches) by name, as in "myjson.x.path" you will be able to access them by index, as in "myjson\[#\].path". Does it imply any limitation for your setup?

As per getting the key/value pairs, you should be able to use either jQuery.each function, or native js `for (item in coll)` traversal.

# Answer
> 0 votes
I do this un drupal 6 (i'm not sure if this work in D7)

```
//Server side:
//Al your code for generate your json string
drupal_set_header('Content-Type: application/json');
drupal_to_js(array("status","data" => $json));

```

And in the client side should be enough with this:

```
//Client Side:
$.ajax({
  url: Drupal.settings.basePath + 'the/path/to/your/ajax/call',
  dataType: 'json' //this is important jquery parser automatically the response and convert it
  type: 'GET',
  success: function(msg) {
    console.log(msg.data.title);
    console.log(msg.data.path);
    console.log(msg.data.style_name);
  }

});

```

And it's all.

---
Tags: javascript
---


title: Group posts view

text:
# Question
Title: Group posts view
I am struggling to make a view to display the posts of a group. I have done the filter and chosen the fields I want to display, but I am struggling with the arguments. I am not sure what the path would be, if I want the view to be a tab of the group node.

# Answer
> 1 votes
Try this contextual filter:

* "(Organic groups group) Organic groups group: Entity id"

and have these 2 relationships added:

* "Group membership: Node group membership"
* "(group membership) OG membership: Group gid"

This will show the nodes that belong to your group. Sorry, I can't help you on the "tab question".

Make sure to checkout this awesome OG video tutorial.

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


title: Migrating Drupal 6 to pressflow?

text:
# Question
Title: Migrating Drupal 6 to pressflow?
After a lot of mysql tunings, I intend to use Varnish as the last resort to improve my D6 site's performance which has become increasingly sluggish. I realized that Varnish will not work with D6. And due to lack of som contrib modules, I still can not migrate to Drupal 7 which, as I understand, makes migration to Pressflow pretty redundant.

I am using nginx + php-fpm as web server and try to avoid Apache at any cost. This approach has of course its downside, for example I could not make use of Boost module. Now my question is that whether pressflow works with my web server configuration? and whether migration is a good idea performance-wise? And Pressflow suites me, where can I find docs to make a smooth migration on Ubuntu server.

Thanks for your suggestions.

# Answer
> 3 votes
I have a client who takes deliveries in the form of the `sites/` folder and a database backup, and installs them in Pressflow. As long as the Pressflow version isn't older than the Drupal version, we have never had problems.

There is no real migration. Just replace the files, run update.php, and move on. Two minor gotchas, though.

Pressflow error reporting is different, and a lot (and I mean **a lot**) of E\_NOTICE will end up in the dblog. You may want to adust error\_reporting to exclude these.

Pressflow is API compatible with Drupal, but I have run into situations with anonymous sessions. Occasionally, I need to manually call `drupal_start_session`, which is in Pressflow 6, from a custom module before I start doing stuff with `$_SESSION`.

Personally, I would give Zend Server CE a shot, too. The Pressflow 6 site that I am wrapping up really flies in this environment.

---
Tags: performance, 6
---


# Question
Title: How do I filter a view page with contextual filter?
I have an all events views page where I would like to put the links 'All Events', 'Upcoming Events', 'Past Events' in the header.

I would like to link them to the same views page but show filtered results. It seems possible by looking at contextual filters but not sure which way to go.

Thanks,

# Answer
You could use this module to set up the date field for the events: http://drupal.org/project/date.

This video explains how to use arguments with the date module: http://www.drupaltherapy.com/date\_d7

Then create 3 view pages, with the only difference being the arguments of each page view to determine if the date is: 1) in the past 2) in the future 3) doesn't need to be filtered by date

Each view page would get its own path. Then you could create a menu with the different paths as links.

Once you have your menu set up, go to Structure- Blocks - and you can configure the menu to be in the content area, and paste the paths of the 3 pages you've created, separated by commas in the section that says SHow Blocks on Specific Pages.

Hopefully that gets you on the right track.
> 2 votes

---
Tags: views
---


# Question
Title: How do I add a custom field to the image field widget in Drupal 7?
I need to add a custom field (a simple text field) to the image\_field widget in Drupal 7.

The structure is a standard node (called Article) which has zero or more images (related photos or graphics) attached via the image\_field widget. The field I want to add is the source of the image, and is used later to figure out when it needs to be deleted.

I've tried the code from this post, but couldn't get it to work.

# Answer
> 2 votes
1. Attaching metadata to images and other media, is precisely the reason that prompted the creation of the media module. We use the unfortunately "unstable" version ourselves, with good results. Using Media, your images becomes entities, allowing you to attach any field you want to them through the normal means.
2. While the solution to manipulate the existing widget is fully valid, it will require quite a bit of understanding of the Field API, and I believe any such solution would get rather messy.

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


# Question
Title: Change Ubercart shipping/billing layout & logic?
I'm selling some tickets for a concert online with Ubercart, and I give people the option of holding the tickets at Will Call, or mailing them out for $1.

The customer's workflow when they're checking out looks a little wonky right now. The first set of address fields is the Shipping Address, then they can click the checkbox to indicate "My billing information is the same as my delivery information." But for a Will Call person, that feels backwards. They shouldn't need to enter a shipping address at all.

Is there a way to put the Billing Information first, and only expose a Shipping Information block when it's needed?

Seems like the same question would pertain to an electronic delivery situation too - but in that case you'd also be generating download links, etc., which I wouldn't need.

Thanks.

(Note - I also posted this question yesterday on ubercart.org's forums, but it looks like traffic there is very slow, I'm wondering whether this is a better place for it.)

# Answer
> 1 votes
You can change the order here:

admin/store/settings/checkout/edit/panes

But you cannot dynamically determine whether the shipping is required. (at least not without tweaking the code.)

Do you really need to offer both anyway? (how often person A buys tickets that need to be sent to person B?)

---
Tags: ubercart
---


# Question
Title: How to edit every node of a content type on cron run?
On cron runs, I want to edit every node of a certain content type. I think this is implemented through `hook_cron()` but I can't find any documentation about this hook. How can I edit every node of a certain content type on cron runs?

I need this because I update content on nodes based on another website. I want the content to be updated regularly. I need something similar to feeds but the data source is just HTML not xml.

# Answer
> 2 votes
You would need to implement various hooks.

hook\_cron: It will get called on every cron run. Here you could load every node in the system using node\_load(), edit whatever properties of the node you need to edit, and then save each edited node using node\_save().

However, note that both loading and saving a node **is** an expensive process, and if you have a site with many nodes, your site would become very slow, unstable, or even unusable on every cron run (which can sometimes happen as often as every 15-30 minutes). In other words, I would be very cautious with whatever you are trying to accomplish.

# Answer
> 1 votes
Here's the documentation for hook\_cron.

Can you be a little more specific about what you want to do? My first thought is to recommend Views Bulk Operations, but that's more for one-time updates rather than every-cron-run updates.

---
Tags: 7, cron
---


title: Error 500 on accessing update.php

text:
# Question
Title: Error 500 on accessing update.php
Long ago I got a message about updates to my modules. I've updated the modules. But I received a message to update the database.

I want to run the update.php script but I encounter the following error message:

> Server error.
>
> The website encountered an error while retrieving http://MYSITE.COM/update.php. It may be down for maintenance or configured incorrectly. Here are some suggestions: Reload this webpage later.
>
> **HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request.**

I do not remember which modules got updated. Please help me.

# Answer
> 1 votes
First of all, in the future, **always** take backups, of both your code, and your modules, prior to updating, so you can easily revert in this type of situation.

Error 500 means that your webserver attempted to parse the code in your update.php file, but failed. The first thing you need to do, is check your servers error log, and find all error messages that are timestamped with the time of your last attempt to execute the script. If you don't know where the logs are, you need to ask your hosting provider.

Regardless of the error message, it could be worth replacing *the files* in your Drupal install with a fresh set. Download the latest version of your major Drupal version, and copy your sites directory over there. This could fix the problem for example if either your update.php file, or others that it depends upon, has become corrupted somehow.

# Answer
> 2 votes
The errors output to Apache are often somewhat cryptic.

You probably want to check the Drupal Reports page, dblog, and the Apache logs.

This sounds like one of the new updates has a problem in the .install or cannot be loaded (permission problems, although that comes proper from Drupal, I never had that problem on an upgrade.)

To test whether the PHP code is invalid, you can run

```
 php <filename>

```

The update.php will generate some errors, but it should not tell you it cannot parse it. All the module .install should not generate any errors (a very few modules have code outside functions and those will generate errors, but again no syntax error.) Those syntax error are reported by Apache.

# Answer
> 1 votes
* Make sure to be logged in as user 1 before going to update.php.
* Make sure update.php is in the drupal root directory.
* Make sure update.php has correct permissions such as 755. (Credit arjan)

```
chmod 755 update.php

```
* Make sure there aren't any .htaccess rules denying access to update.php

```
grep update .htaccess

```

I usually install drush and run updb in order to run all outstanding updates.

---
Tags: 6, updating
---


# Question
Title: How to move the content of 'Node content' display (Views) to the end of a view?
I installed the Answers module and I am trying to edit the question\_answer view. Basically I would like the answers (which are generated by the 'node content' display) to appear below the question. This is done by default by the module: See Picture.

The problem is that I would like to move 'Post an Answer' link before the list of answers. Now it works as follows
\- Question Header
---List of Answers
---- Question Footer

and I would like to change it to
\- Question Header
---- Question Footer (or just the entire Question node)
----List of Answers.

I know that's because the display is "Node Content", but I don't know how to do it properly. I've tried with Attachement, Blocks and no success. You can find the screenshot of the view settings here (Default view has the same values as Node Content Display) Any advice greatly appreciated.

# Answer
> 1 votes
Have you tried playing with the "Row style" setting ? You could change it to "Fields" and select the node:title, node:body, node:nid and node:answers (?? does that exist ?? I'm guessing that answers are just comments, right ? In that case, node:comments).

Output them in the order that you want, but rewrite the node:nid as a link to the "post answer" url. I don't know this module, but say the answer url is node/xxx/answer, you can rewrite the node:nid field as

```
<a href="/node/[nid]/answer">Post your answer</a>

```

# Answer
> 0 votes
My guess is that the post an answer link is just an add comment button. Since the view is outputting pure node display you should be able to edit the template file and move the $links to anywhere in the HTML.

---
Tags: views, 6, nodes
---


# Question
Title: Pages are not accessible, menu links are not displaying properly
I'm trying to resurrect a Drupal 4 site which stopped working at some unknown point, possibly months ago. I can login as admin and reach the front page. Every link after that returns 'you are not authorized to access this page'. The primary\_links and secondary\_links menus are not being retrieved properly. I have tried switching themes and clearing the cache table. I have also set up a local version for debugging but there are no PHP errors being thrown.

I'm running php 5.2.13, mysql 5.1.44.

# Answer
> 1 votes
As I have noted in the comments of the first answer, the issue was due to a change in versions of PHP. The bug was previously reported here.

# Answer
> 0 votes
Have you rebuild the node permissions? I think the direct link to that in D5 is /admin/content/node-settings/rebuild if it isn't in a menu.

# Answer
> 0 votes
Both PHP and MySQL was on version 4 around this time, I would suggest you start by trying to go back to PHP/MySQL 4, either, or both. If possible ofcourse, the versions the site was built upon. I can see in one of the comments that this conclusion may already have been drawn. I mainly came here to answer the question because community bumped it as an unanswered question.

Accept my answer or the first one, but please accept one. :)

---
Tags: routes, users
---


# Question
Title: Define entity in module and edit existing items
I am trying to create a module which defines an entity (called "didyouknow") with two fields: ID and content.

I have set it up to create new items of this custom entity, but I can't get it to work for editing existing items.

I'm trying to reuse the same form (`didyouknow_item_form()`) for creating and editing, which works fine for creating, but for editing. The "%didyouknow" part in the URL is supposed to mean that the argument of `didyouknow_item_edit()` is a loaded entity object, but it isn't; if I output it within that function using `print_r()`, it outputs as "structure." This results in PHP outputting:

> Notice: Trying to get property of non-object in didyouknow\_item\_form()

The code for the functions is below:

```
function didyouknow_menu() {
    $items['admin/structure/didyouknow/manage/add'] = array(
    'title' => 'Add Did You Know item',
    'page callback' => 'didyouknow_add',
    'access arguments' => array('create didyouknow'),
  );
  $items['admin/structure/didyouknow/manage/%didyouknow/edit'] = array(
    'page callback' => 'didyouknow_item_edit',
    'access arguments' => array('create didyouknow'),
    'page arguments' => array(1),
  );
  return $items;
}

function didyouknow_item_edit($didyouknow){
  return drupal_get_form('didyouknow_item_form', $didyouknow);
}

function didyouknow_add() {
    $didyouknow = (object) array (
    'pid' => '',
    'type' => 'didyouknow',
    'content' => '',
  );

  return drupal_get_form('didyouknow_item_form', $didyouknow);
}

function didyouknow_item_form($form, &$form_state, $didyouknow) {
  $form['content'] = array(
    '#type' => 'textarea',
    '#title' => t('Content'),
    '#default_value' => $didyouknow->content,
    '#required' => TRUE,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );

  field_attach_form('didyouknow', $didyouknow, $form, $form_state);

  return $form;
}

function didyouknow_item_form_validate($form, &$form_state) {
  $didyouknow_submission = (object) $form_state['values'];
  field_attach_form_validate('diyouknow', $didyouknow_submission, $form, $form_state);
}

function didyouknow_item_form_submit($form, &$form_state) {
  $didyouknow_submission = (object) $form_state['values'];
  field_attach_submit('didyouknow', $didyouknow_submission, $form, $form_state);
  $didyouknow = didyouknow_item_save($didyouknow_submission);
  $form_state['redirect'] = "admin/structure/didyouknow/manage/$didyouknow->pid/edit";
}

function didyouknow_item_save(&$didyouknow) {
  return entity_get_controller('didyouknow')->save($didyouknow);
}

```

# Answer
> 1 votes
You have two problems in that code. First of all, you assume that having a didyouknow-id in the URL, is enough for Drupal to know where to get your object, the second problem is that your page argument is off.

This simplified code:

```
$items['admin/structure/didyouknow/manage/%didyouknow/edit'] = array(
  // …
  'page arguments' => array(1),
);

```

will pass on "structure" as an argument, *not* the %didyouknow id, nor a didyouknow-object, which is why you get an error about a "non-object". Argument indexing start with 0 =\> admin, so (as already mentioned by LToomre) you need to have:

```
'page arguments' => array(4),

```

It is also important to note that Drupal will *not* automatically know how to load your entity, you are required to provide the load function yourself.

As an example, look at the epay module, which has a menu hook like this:

```
$items['payment/epay/callback/%epay_hash'] = array();

```

The named argument **%epay\_hash**, is automatically mapped to a \_load function:

```
function epay_hash_load($hash) {}

```

which takes the URL argument as parameter, performs the DB queries necessary to load your object, and then returns it.

# Answer
> 0 votes
The result 'structure' come from the line 'page arguments' =\> array(1).

To pass in the %didyouknow value, you want to use 'page arguments' =\> array(4) instead.

---
Tags: 7, entities
---


# Question
Title: Session values are getting populated only when the page is refreshed
I have a webform. I provide default values to these webform using session token variables. These session variables are set using `hook_form_alter()`. The problem is that when users log in, and see the form, it is not populated. When they refresh the form, only the values get populated.

How can I solve this issue?

/\** updates \**/

I have custom module like

```
webform_options_form_alter(&$form, &$form_state, $form_id){
//here i set some values for session variables like.
$_SESSION['name']  = 'pradeep';
}

```

so in webform default value i put like %session\['name'\]. This takes the value when page is refreshed.

I have the login form as block on the same page of the webform. As soon as the user logs in the webform should be filled with user data. This is not happening. When he refreshes the page after login only he sees his data.

# Answer
> 2 votes
It sounds like your problem is how/when the session variables are set (they are not available on the initial form load). You don't mention how this is done.

Some code example and greater details in your question will allow for a more detailed answer.

---
Tags: 7, webforms, sessions
---


title: Transliteration of Danish characters

text:
# Question
Title: Transliteration of Danish characters
I have a site running with these modules (among others):

My problem comes with danish characters. Normally they would be replaced like this:

* Æ = Ae
* æ = ae
* Ø = Oe
* ø = oe
* Å = Aa
* å = aa

However, the Transliteration module isn't working like I would expect; it replaces:

* Æ = ae
* æ = ae (correct)
* Ø = o
* ø = o
* Å = a
* å = a

So "ÆØÅ - æøå" becomes "aeoa-aeoa".

The "lower case issue" might be caused by the Pathauto module, and it is not neccesarily a problem with the transliteration. Still it's not correctly replaced.

This is a file from the Transliteration module that I think it does the replacement of Danish characters, but I can't figure out how to make it work correctly.

**x00.php**

```
<?php

$base = array(
  // Note: to save memory plain ASCII mappings have been left out.
  0x80 => '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  0x90 => '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  0xA0 => ' ', '!', 'C/', 'PS', '$?', 'Y=', '|', 'SS', '"', '(c)', 'a', '<<', '!', '', '(r)', '-',
  0xB0 => 'deg', '+-', '2', '3', '\'', 'u', 'P', '*', ',', '1', 'o', '>>', '1/4', '1/2', '3/4', '?',
  0xC0 => 'A', 'A', 'A', 'A', 'A', 'A', 'AE', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I',
  0xD0 => 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'x', 'O', 'U', 'U', 'U', 'U', 'U', 'Th', 'ss',
  0xE0 => 'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i',
  0xF0 => 'd', 'n', 'o', 'o', 'o', 'o', 'o', '/', 'o', 'u', 'u', 'u', 'u', 'y', 'th', 'y',
);

// Overrides for Danish input.
$variant['da'] = array(
  0xC5 => 'Aa',
  0xD8 => 'Oe',
  0xE5 => 'aa',
  0xF8 => 'oe',
);

// Overrides for German input.
$variant['de'] = array(
  0xC4 => 'Ae',
  0xD6 => 'Oe',
  0xDC => 'Ue',
  0xE4 => 'ae',
  0xF6 => 'oe',
  0xFC => 'ue',
  0xDF => 'ss',
);

```

**SOLUTION**

When developing I had the language set to English; it needs to be set to Danish, in order to get this to work.

# Answer
SOLUTION

When developing I had the language set to English; it needs to be set to Danish, in order to get this to work.
> 2 votes

---
Tags: 7, path-aliases
---


title: How to change design in comments list

text:
# Question
Title: How to change design in comments list
I am listing all the comments in a page.

For example, suppose the comments are listed using a design similar to the following one:

> Comment Title 1
>
> Comment Description 1
>
> ---
>
> Comment Title 2
>
> Comment Description 2
>
> ---
>
> Comment Title 3
>
> Comment Description 3
>
> ---

If the third comment is the last comment, I should not print the line for that comment.

How can this be done?

# Answer
**EDIT:** Updated to use a preprocess function. This still might not be pretty, but works fine. In your template.php file in your theme, add this function (replacing YOURTHEME with the name of your current theme):

```
function YOURTHEME_preprocess_comment(&$variables) {
  $display_order = _comment_get_display_setting('sort', $variables['node']);
  if ($display_order == 1) {
    $variables['end_comment'] = db_result(db_query('SELECT MIN(cid) AS cid FROM {comments} WHERE status = 0 AND pid = 0 AND nid = %d', $variables['node']->nid));
  }
  else if ($display_order == 2) {
    $variables['end_comment'] = db_result(db_query('SELECT MAX(cid) AS cid FROM {comments} WHERE status = 0 AND pid = 0 AND nid = %d', $variables['node']->nid));
  }
}

```

Now copy comment.tpl.php from `modules/comment` and place it in your theme folder. Add this code

```
print $end_comment == $comment->cid ? ' last' : '';

```

to the class area of the div html. It should look something like:

```
<div class="comment<?php print ($comment->new) ? ' comment-new' : ''; print ' '. $status; print $end_comment == $comment->cid ? ' last' : ''; ?> clear-block">

```

You now have a class of `last` on the bottom comment, no matter which way they are sorted. Now simply add some simple CSS to your stylesheet:

```
div.comment.last {
  border-bottom: none;
}

```

---

You can also use jQuery or CSS to remove the bottom border from the last comment, but they are less reliable depending on a user's browser, browser settings, etc.

jQuery:

```
// Remove border from last comment
$('#comments div.comment:last').css('borderBottom', 'none');

```

CSS (Works in IE9, but unfortunately will not work with IE8 and below):

```
div.comment:last-child {
  border-bottom: none;
}

```
> 2 votes

# Answer
If you work on D7 :

* There's no last class attributed to the last comment of a node. So normally you can't. Maybe you can do some tricky CSS attribution :

Let say your line is a `border-bottom : 1px solid #ccc;` attributed to each `div.comment`, then you may replace it by a `border-top : 1px solid #ccc;` and "erase" it for the first comment wrapper But once again, the comment ID doesn't appear in the class...

If you don't have any title for all the comments, try something like `div.comment-wrapper { border-top : none; }`.

I don't see much solution, except the dirty one : rewrite partially the comment core module to add first and last class to the first and last comments for each node... :(

**EDIT :** Actually, I've looked at Heihachi's answer and I think I found the solution :

* create a custom comment.tpl.php (copy paste it from the core original files).
* add a div with a specified class to wrap `<?php print $content ?>` something like `<div class="comments-content"><?php print $content ?></div>`
* add the following css : .comment { border-top: 1px solid #D1D1D1; } .comments-content { margin : 0 ; padding : 0; border-top: 1px solid #fff; /\* This border will normally hide the first comment line. Make it the same color as your background \*/ }
> 0 votes

# Answer
Is this on a node's page... displaying the comments for the node? Or is this a custom page you created that displays all the comments?

If this is a node displaying the comments for that node, then D6 does have have `last` CSS class on the last comment. You can use that in your CSS to remove the bottom border on the last comment.
> 0 votes

# Answer
If you want to remove the bottom line of the last comment:

1. Add the preprocess\_comment function in you *template.php* file:

```
function *YOUR TEMPLATE*_preprocess_comment(&$vars){
  if($vars['id'] == $vars['node']->comment_count){
    $vars['classes_array'][] = 'last';
  }
}

```
2. Add in your CSS file:

```
div.comment-item.last { border-bottom: 0 none; }

```
> 0 votes

# Answer
If you use a D6: In a **comment.tpl.php** delete all previous code and paste this:

```
<h3><?php print $title ?></h3>
<div class="commentz"><?php print $content ?></div>

```

and in css:

```
.commentz { border-bottom:1px solid #000; }

```
> -1 votes

---
Tags: comments
---


title: Creating hyperlinks in wysiwyg editor

text:
# Question
Title: Creating hyperlinks in wysiwyg editor
I installed the tinymce wysiwyg editor and it converts hyperlinks into \[url= tags. How do I convert this to html i.e. `<a href="`

# Answer
Maybe in your formats, there is no `<a>` allowed? You can find it under /admin/config/content/formats Or you checked that HTML will be rendered as text.
> 0 votes

# Answer
tinyMCE is most likely not the source of the problem. There's something not ok with your Input filters. Try to create a new set with no filtering at all. Rhis should fix the problem. If you need some of your filters, switch them on one by one to find the one causing the problem.
> 0 votes

---
Tags: wysiwyg
---


# Question
Title: Search settings: Indexing status stuck on 0%
When I click Re-index site, and confirm, I get a message that the index *will* be indexed but it never does.

# Answer
Run cron. (example.com/cron.php or go to Admin \>\> Reports \>\> Status and click "run cron")
> 2 votes

# Answer
You can also do it via drush to get around limit on the number of items that get indexed per cron run.

```
$ drush help search-index
Index the remaining search items without wiping the index.

```

and/or

```
$ drush help search-reindex
Force the search index to be rebuilt.

Options:
 --immediate                               Rebuild the index immediately, instead of waiting for cron.

```
> 2 votes

---
Tags: search
---


title: How do I use the GTranslate module?

text:
# Question
Title: How do I use the GTranslate module?
I have installed the GTranslate module, and I am searching for how to use it. In the module page, the language selection drop-down box is there, but when I installed this module the drop-down list didn't appear. How do I use the GTranslate module?

# Answer
Google Translate changed their policy, this module does not work anymore according to the issue queue.

There seems to be a newer version on an external website, which also offers a paid Pro version that seems to require ioncube encoder which means that it is encrypted, which sounds like a violation of the GPL to me.
> 0 votes

---
Tags: 6, i18n-l10n
---


# Question
Title: Taxes is not shown in the cart. Using Drupal Commerce module
I'm using the Drupal Commerce module and I need to add some taxes to be shown in the cart.

Then, I added 2 taxes in admin/commerce/config/taxes following this video directions: video

First one is a VAT tax type which is shown correctly

Second one is a Sales Taxes tax type which is not shown at all in the cart

What am I missing? As far as I can see is not a permission related problem.

# Answer
> 4 votes
Drupal commerce will by default not show taxes on the cart, the cart is more simple minded with focus on products. The review and checkout pages, will however have taxes displayed by default.

The shopping cart is based on views, so it's pretty easy to change how the order total is displayed. Instead of using `Commerce Line Item: Line item summary` area handler you should instead use the `Commerce Order: Total`

---
Tags: 7, commerce
---


# Question
Title: Using hook_form_alter() to prevent free email addresses from registering on a Drupal 6 site
I have been tasked with blocking specific email address domians from registering at our Drupal 6 site (gmail.com, aol.com & yahoo.com). I implemented some JQuery code to do this but the problem was that spammers with javascript disabled in their browser readily bypassed this prevention.

I also cannot use Drupal 6's Access Rules as we already have registered users on the site with those domains so this method blocks them from logging in so it's more of a going forward prevention that we would like to implement.

I found this code on Stack Overflow but the code was somewhat incomplete:

```
function example_data_form_user_register_alter(&$form,&$form_state) {
  $form['mail']['#element_validate'] = 'example_mail_validate';
}

function example_mail_validate($element, &$form_state) {
   if ( -- Whatever condition you like -- ) {
     form_error($element, t('Free email is not allowed.'));
   }
}

```

I thought it would be better to open a new question on this forum since it's Drupal specific.

I think what I need help with is filling in the gap where in the code it says: `-- Whatever condition you like --`

I am not a PHP guru so any help would be appreciated. I assume this is the spot where I would have some code that disallows the domains that I want to block.

# Answer
> 5 votes
A very simple example would be:

```
function example_mail_form_user_register_alter(&$form,&$form_state) {
  $form['mail']['#element_validate'] = array('example_mail_validate');
}

function example_mail_validate($element, &$form_state) {
   //block gmail addresses
   if (stripos($form_state['values']['mail'], 'gmail.com') > 0) {
     form_set_error('mail', t('Free email is not allowed.'));
   }
}

```

However you should lookout for more advanced solutions:

* Simple email verification: email verify
* http:BL
> http:BL can prevent email address harvesters and comment spammers from visiting your site by using a centralized DNS blacklist.
* Mollom which also prevent spam on all your content/comments forms.

---
Tags: forms, 6, hooks, users
---


# Question
Title: How to get user photo to appear in node panel
I'm overriding a node template with panels, I'm trying to add the user photo, but the only thing I can seem to add is the username. Does anyone know how to do this? do I have to do something weird like create a mini-panel that loads the user?

# Answer
Jumped the gun and posted this question before I really messed around with it. All you have to do is add "User From Node" as a relationship in contexts, then it will show up as picture in panels
> 4 votes

---
Tags: users, panels, media
---


# Question
Title: Is it currently possible to have Views respect RSS Display settings on a Content Type?
I have enabled and configured a 'Custom Display Setting' under 'Manage Display' of a content type for RSS

```
 admin/structure/types/manage/{my-type}/display/rss

```

I can't seem to find a way for Views to respect this new Display Setting. The only available options for "Feed: Row style options" under a Feed View are:

```
Full text
Title plus teaser
Title only
Use Default RSS settings

```

None of which follow the Display options I specified for in the Content Type for RSS

Is there not currently a way to do this in D7? Does it require another module?

Thanks in advance.

# Answer
> 1 votes
There is a current bug in views that does not respect any changes you make to the default RSS display settings. See Issue #1301788: RSS Feed - Title plus teaser --- still grabs default node view?. There is a patch but it hasn't been rolled into a release yet.

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


# Question
Title: Show only comments from users with the same role
I am currently analyzing a project and am encountering the following situation, where I'd like to know your point of view.

For a specific content type we would like to allow users to place comments, but they should only see the comments made by users with the same role. Only administrators should be allowed to view them all.

Anyone encountered a similar situation?

# Answer
> 1 votes
Disclaimer: I have not had need for this myself, nor do I posses a database where I could perform suitable testing for this. Despite this, I feel confident I understand the problem enough to provide a useful solution.

While I've been writing this answer, I've been struck by the complexity of it. I've tried to take a step back, and consider if there are other options, but none other come to mind. Perhaps someone else will be able to offer an easier suggestion.

The standard Drupal answer will be use a View, and that is most likely the way I would go about this myself. Even if you require more flexibility than that, the SQL generated by Views would serve as an excellent boilerplate for your own code. It's important to understand, that in my example below, you are required to be able to pass in a "role-id", into the View. This in turn likely requires you to understand and use Page manager + Panels. PM+P can be considered daunting at first, but is a great tool every Drupal site-builder should be familiar with. Tutorial here.

Basic steps to creating such a View:

1. Create a View. It's important to note the "Show" dropdown on the views/add page. It should be set to **comments**, not **content**, that is the default.
2. By default, Views should create a relationship between the comments, and the content they are posted on. If it's missing, add it. (Comment: content).
3. We also want information about the posting users group, we need to add a second relationship, (Comment: Author).
4. Last, we must create a "contextual filter", a filter that asks the currently viewing user "Which role do you have?". Add (User: roles), as a contextual filter. The default settings in on the contextual filter, will likely have the "Relationship" configured to use "Content" for getting the role, but that will give us wrong data, so this needs to be changed to "author" instead.

Done! Test it out by giving the preview a rold-id as argument, and see what results you get back.

Query below, ready to be pasted into a db\_query()-call. This query could also more readily be adapted to take a user-id and "WHERE IN()", the users roles, if necessary.

```
SELECT comment.subject AS comment_subject, comment.cid AS cid, comment.nid AS comment_nid, comment.created AS comment_created
FROM {comment} comment
INNER JOIN {node} node_comment ON comment.nid = node_comment.nid
LEFT JOIN {users} users_comment ON comment.uid = users_comment.uid
INNER JOIN {users_roles} users_comment__users_roles ON users_comment.uid = users_comment__users_roles.uid
WHERE (( (comment.status <> '0') AND (node_comment.status = '1') AND (users_comment__users_roles.rid = '1') ))
ORDER BY comment_created DESC
LIMIT 10 OFFSET 0

```

Below follows a full export of my View:

```
$view = new view;
$view->name = 'rolebasedcomments';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'comment';
$view->human_name = 'tmp';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Comment: Content */
$handler->display->display_options['relationships']['nid']['id'] = 'nid';
$handler->display->display_options['relationships']['nid']['table'] = 'comment';
$handler->display->display_options['relationships']['nid']['field'] = 'nid';
$handler->display->display_options['relationships']['nid']['required'] = 1;
/* Relationship: Comment: Author */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'comment';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
$handler->display->display_options['relationships']['uid']['required'] = 0;
/* Field: Comment: Title */
$handler->display->display_options['fields']['subject']['id'] = 'subject';
$handler->display->display_options['fields']['subject']['table'] = 'comment';
$handler->display->display_options['fields']['subject']['field'] = 'subject';
$handler->display->display_options['fields']['subject']['label'] = '';
$handler->display->display_options['fields']['subject']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['subject']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['subject']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['subject']['alter']['word_boundary'] = 0;
$handler->display->display_options['fields']['subject']['alter']['ellipsis'] = 0;
$handler->display->display_options['fields']['subject']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['subject']['alter']['trim'] = 0;
$handler->display->display_options['fields']['subject']['alter']['html'] = 0;
$handler->display->display_options['fields']['subject']['hide_empty'] = 0;
$handler->display->display_options['fields']['subject']['empty_zero'] = 0;
$handler->display->display_options['fields']['subject']['link_to_comment'] = 1;
/* Sort criterion: Comment: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'comment';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: User: Roles */
$handler->display->display_options['arguments']['rid']['id'] = 'rid';
$handler->display->display_options['arguments']['rid']['table'] = 'users_roles';
$handler->display->display_options['arguments']['rid']['field'] = 'rid';
$handler->display->display_options['arguments']['rid']['relationship'] = 'uid';
$handler->display->display_options['arguments']['rid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['rid']['default_argument_skip_url'] = 0;
$handler->display->display_options['arguments']['rid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['rid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['rid']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['rid']['break_phrase'] = 0;
$handler->display->display_options['arguments']['rid']['add_table'] = 0;
$handler->display->display_options['arguments']['rid']['require_value'] = 0;
$handler->display->display_options['arguments']['rid']['reduce_duplicates'] = 0;
/* Filter criterion: Comment: Approved */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'comment';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 0;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status_node']['id'] = 'status_node';
$handler->display->display_options['filters']['status_node']['table'] = 'node';
$handler->display->display_options['filters']['status_node']['field'] = 'status';
$handler->display->display_options['filters']['status_node']['relationship'] = 'nid';
$handler->display->display_options['filters']['status_node']['value'] = 1;
$handler->display->display_options['filters']['status_node']['group'] = 0;
$handler->display->display_options['filters']['status_node']['expose']['operator'] = FALSE;

```

# Answer
> 1 votes
My proposal:

* Copy the comment template into your theme folder.
* Use `global $user` to access the current logged in user.
* Use `user_load($comment->uid)` to load the user object for the commented user.
* Loop through the roles in `$user` and check using `in_array` if that exists in `$comment->roles`.
* If it's in the array, show the comment, otherwise hide it.

---
Tags: 7, comments, users
---


title: phone field with constraint and format

text:
# Question
Title: phone field with constraint and format
Is there a way to make a phone field that would only accept numbers (no spaces) and will format them as the user types?

Note: I read somewhere that text fields can be configured that way but I could not find how. I also tried integer field but this feels wrong

# Answer
> 2 votes
Try the Masked-Input module. It does exactly what you are looking for.

---
Tags: entities
---


# Question
Title: Best practice when testing module updates
A problem I face on a regular basis is trying to test sites that have recently had a lot of module updates. My usual process is to take each module on a case by case basis and test site features related to that module.

For instance, if the wysiwyg module is updated, I'll find a node that implements it in a field and do exploratory testing. But the reality is that the issues can be more subtle - perhaps certain user roles have lost permissions, allowing them to embed media when they were previously restricted.

Sometimes there are so many factors to bear in mind it is impossible to test them all, and invariably the client, at UAT phase, discovers major issues that I may have been blind to for various reasons.

I would be interested to hear of any advice or approaches towards testing sites that have had comprehensive module updates - what can I do to ensure quality, and even, what kind of line should I take with our clients to prepare them for issues that do invariably arise?

# Answer
> 6 votes
A solution that I would very much *like* to test, but haven't so for, is combining a branching model like this one, not necessarily with git, with selenium automated testing. Every night, a tool like Jenkins pulls the development branch, runs drush make, drush site-install, and runs your selenium test suite.

I also remember reading an empirical study about finding bugs in software, that I unfortunately can not find a link to right now. The findings were, that no single way of finding bugs was "good enough", and that at least two separate models, such as "Test-driven", "User beta testing", "Code review", etc, were necessary to reach a high, +75%, level of found bugs, prior to release.

---
Tags: updating, testing
---


title: International path alias not working

text:
# Question
Title: International path alias not working
I am trying to translate an existing site.

I've used i18n before successfully so I'm not totally new to it. Now to my problem…

I can create content fine in different languages the problem occurs when I try to access languages (other than the default, without path-prefix) with a path-prefix. I keep getting a 404.

Example:

Their system-path counterparts:

Any ideas about what might cause this?

*Please note that this is a Drupal 6 install.*

# Answer
In reply to your fix you posted in language\_initialize. It's very strange that the first arg would be empty.

So now that you've added in your changes, http://www.hillsongconference.co.uk/se/home works. However, this should be exactly the same as http://www.hillsongconference.co.uk/?q=se/home and you will see that this brings in the 404 error (whereas q=/se/home doesn't).

So I'm worndering if the htaccess file has been edited? As this is how Drupal converts the arguments in the url path to `$_GET['q']`. The Drupal .htaccess file also strips out leading slashes, to insure the first argument isn't empty.

You've hacked core now, which is a terrible no-no. Even if you are never going to update this site, it still needs to be fixed out of principle!

If you are running a nginx setup the correct rewrite (to not include the slash) is `rewrite ^/(.*)$ /index.php?q=$1 last;` not `rewrite ^(.*)$ /index.php?q=$1 last;`
> 2 votes

# Answer
As far as I know, in Drupal 6 it is not possible to assign the same alias to two different nodes. When requesting /home the system retrieves the first internal path it encounters (/node/1) in the url alias database table and shows it (works correct for English). However, when requesting /se/home it also retrieves that same internal path (/node/1) and checks if the node's language (en) matches the prefix (se). Because this ain't true, you'll encounter the 404.

I see two possibilities. 1) Change the url alias for swedish home to something else, i.e. "start".

2) Use a view to display the node. Views keep the same url for all languages while you can use a language filter to only show nodes of the current language, i.e. the view at /home shows English nodes while /se/home (as a view) only shows swedish nodes.
> 0 votes

# Answer
Ok everyone. I've had to go into core to figure this out. I'm back and I survived the trip.

I found out what is going wrong, no idea how any multi-lingual site works with this bug in it.

> File: language.inc (function language\_initialize)
>
> The problem is this line and the loop beneath it.
>
> `$prefix = array_shift($args);`
>
> Because `$args` is an array of parts made after imploding `$_GET['q']` the first string in that array is always going to be empty let me explain that with a picture:
>
> That essentially means that the language will never be detected and the path will instead be treated like it's english `"/se/home/"`. Fixed it by adding an extra `$prefix = array_shift($args);` just after it.
> 0 votes

---
Tags: 6, path-aliases, i18n-l10n
---


# Question
Title: Do not translate the admin area / How can I set the language of the admin area to English?
I am building a multilingual site with 3 languages. Lets say English, Italian and German. English is the default language. Is it possible to leave the admin area untranslatable, even I am currently seeing the actual site in different language other than the default one, just for the administrator of the site, using a module or custom code?

# Answer
You could try the Administration Language module. There's only a dev version for the Drupal 7.x branch out currently, but it seems to work well enough (used it in a project myself).
> 4 votes

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


title: Where are Cache settings stored?

text:
# Question
Title: Where are Cache settings stored?
I assumed the settings from the function system\_performance\_settings were stored in variables, but couldn't figure out which.

# Answer
If you trace the code from the system\_performance\_settings, you'll see that is uses system\_settings\_form for form generation, which uses system\_settings\_form\_submit form submit handling, which in turn does

```
foreach ($form_state['values'] as $key => $value) {
  if (is_array($value) && isset($form_state['values']['array_filter'])) {
     $value = array_keys(array_filter($value));
  }
  variable_set($key, $value);
}

```

So to find any individual variable name, your best bet is to

```
drupal_set_message($key);

```

in that function.
> 3 votes

# Answer
```
cache: 0
cache_lifetime: 0
page_cache_maximum_age: 0
block_cache: 0
page_compression: 0
preprocess_css: 0
preprocess_js: 0

```

Those were the results of @Letharion answer, disabling everything in the form.
> 3 votes

---
Tags: 7, configuration
---


# Question
Title: D7 bug with db_select, 'addExpression' and 'having' conditions?
As I asked in the drupal forum http://drupal.org/node/1393748 (no answers..) I have an issue with a db\_select query.

It seems that addExpression "GROUP\_CONCAT" and "HAVING" is causing an issue.

```
PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'ATTO' in 'having clause': SELECT COUNT(*) AS expression FROM (SELECT 1 AS ...

```

```
<?php
$query = db_select("adm_f", "f");
    $query->fields("f", array("F_ID", "F_TIT", "F_TITOR", "F_DES", "F_ANN", "F_PAE", "F_REG", "F_IMG"));
    $query->addExpression("GROUP_CONCAT(t.TAG_DESC separator ', ')", 'ATTO');
    $query->leftJoin('adm_a', 'a', 'a.F_ID = f.F_ID');
    $query->leftJoin('adm_t', 't', 'a.TAG_ID = t.TAG_ID');
    $query->condition('t.TAG_TIP', 'code', '=');
    // other conditions..
    $query->groupBy('f.F_ID');
    $query->groupBy('f.F_TIT');
    $query->groupBy('f.F_TITOR');
    $query->groupBy('f.F_DESC');
    $query->groupBy('f.F_ANN');
    $query->groupBy('f.F_PAE');
    $query->groupBy('f.F_REG');
    $query->groupBy('f.F_IMG');

    // BUG ???
    if(trim($_GET['F_ATTO']) != '')
        $query->havingCondition('ATTO', '%'.trim($_GET['F_ATTO']).'%', 'LIKE');

$query = $query->extend('PagerDefault')->limit(10);
    // echo($query->__toString()); exit;
    // execute
    $rs = $query->execute();
?>

```

I solved the problem with a workaround, but I would like to use HAVING and not a second query...

Many thanks for your help!!

# Answer
Sounds like the problem is the paging, because it's the count query that gives you the error. For debugging, try to disable the paging.

If it works without paging, it means that the automatically generated count query doesn't work and you need to create one manually and then set it with $query-\>setCountQuery() after doing the extend('PagerDefault').

The automatically generated query removes all selected fields, which then causes the error when you are trying to access it in the having condition.
> 6 votes

---
Tags: 7, database
---


# Question
Title: Views random list with different css for result 1
I want to create a random list of pictures with views 3 in Drupal 7 where the first picture is larger than the other ones.

So each time I reload I have a random list and the first result is always bigger.

How do I do this?

# Answer
You can get random results in Views by using the random sort filter. Then there's quite a few ways to target CSS on the first result. If your using a list style, the first list item will have a **views-row-first** class.

However, if you want the image to be larger you really want to use a different image style. This means the field will be different from the rest, and the best way to do that would be to move it to an attachment display. In there, override the fields and edit the image style. Override the pager and limit it to 1.

The next problem would be how to exclude the random image from the attachment in the main view (so that you don't get duplicate results).

You can get a view to exclude a result by adding it is an contextual filter. And in the 'more' options, select 'exclude'.

However, I don't know of a way to pass the result from the attachment into the other display as an argument. They will both inherit the same arguments.

You could generate a random id somehow, and pass this in to your view.

But the tricky bit is how you would generate this random id, it could even be done with another view! And then also how do you pass this into the view. I can't quite think of an elegant solution. If you're in a hurry, here's some quick and dirty php code you could put into a custom modules hook\_menu callback.

```
$random_id = views_embed_view('your_view_name', 'display_that_outputs_random_id');
print views_embed_view('your_view_name', 'main_display_name', $random_id);

```

There's definitley a better way, if I can think of something I'll let you know.

Thanks Leon
> 2 votes

# Answer
**Random sort**

There's a specific random sorter called "Global: Random", which you can add like any other sorter in Views, to get the random sorting.

**Image size**

First of all, since you don't mention imagecache, I want to mention that for controlling sizes in general, need to set up two image styles with the imagecache module. Covering that however is out of scope for this question.

There is actually module, which is capable of much more, but has you exact use-case in it's own description. Dynamic formatters' description says 'A simple use case of this is a field in a view that uses a "large" image preset for the first result row and a "small" preset for the rest of the rows.' While the use-case matches really well, it's also important to note that this requires some amount of coding skills.

Another option is to override the image-fields template. A full book on the theme layer in Drupal could be written, so I can't explain this in full detail here, but I will provide the outline, and you can google and/or open new questions for difficult details.

1. Set up your View to display all your images in the smaller format.
2. In Views, under "Advanced", find the "Theme: Information". Look for the most specific template that matches your requirement, likely something like views-view-field--**\[name\_of\_image\_field\_here\]**.tpl.php
3. In views/theme, find views-view-field.tpl.php, copy it to your themes templates directory, and rename it to the field-specific name from the previous step.
4. In this template file, you can now override the imagecache preset for the very first image, to be the bigger style you desire instead. To have this work only on the very first image, you will need a static variable

Code example:

```
static $firstImage = true;
if ($firstImage) //Use large image cache
$firstImage = false;

```

I realize that if you are new to either coding, or drupal, this can seem very complicated, but as I said, one would need a book to cover all of this in detail.
> 1 votes

---
Tags: views, theming
---


title: Mouseover instead of click

text:
# Question
Title: Mouseover instead of click
Has anyone gotten the Quicktabs module to work on mouseover/hover instead of click?
There was a patch for version 6.x-2 that does not work with the current version.

# Answer
I ended up making a couple of edits to quicktabs.js. At its most basic, in line 24 I changed 'click' to 'mouseenter' and changed the name of the `quicktabsClick()` function to `quicktabsHover()`.

When the user clicked the link in the tab, though, the page refreshed; I added the following at line 25 (below the new call to quicktabsHover):

```
$(this).unbind('click').bind('click', quicktabsClick);

```

I also added a new function:

```
var quicktabsClick = function() {
    return false;
}

```
> 1 votes

---
Tags: 6, blocks
---


# Question
Title: Implement sticky footer for acquia_marina
I've searched for a Drupal-friendly sticky footer solution for the Acquia Marina theme for Drupal 7, but I couldn't find anything.

2 examples are given here for Drupal 6: http://drupal.org/node/554048. The first solution is JavaScript-based and the second is CSS-based.

Will the CSS/JS examples given work for Drupal 7? If not, can anyone suggest a simple solution to get the footer to stick to the bottom of the browser window?

My site is running drupal-7.10, fusion-7.x-1.x-dev and acquia\_marina-7.x-1.x-dev.

# Answer
> 2 votes
The CSS solution should be implemented the same way in Drupal 7.

Here is the javascript code updated to Drupal 7.

```
(function ($) {
Drupal.behaviors.acquia_marinaStickyFooter = {
  attach: function (context, settings) {
    var footer_height = $('#footer').height();
    var footer_pos = $('#footer').position();
    var window_height = $(window).height();
    var page_height = $('#page').height();
    var page_pos = $('#page').position();
    var page_total = page_pos.top + page_height;
    var footer_new_pos = window_height - footer_height - page_total;
    var test = footer_height + page_total;
    if (test <= window_height) {
      if (footer_pos.top < window_height) {
        $('#footer').css('position', 'relative');
        $('#footer').css('margin-top', footer_new_pos);
      }
    }
  }
};
})(jQuery);

```

---
Tags: 7, theming
---


# Question
Title: Respect parent's node access level (Book)
I was wondering if there is a way (using some hooks for example) so the child pages in a book respect their parents access level, meaning if user doesn't have the access to view the parent node, he won't be able to view the child nodes as well?

I use Drupal 6

# Answer
> 1 votes
I had a similar issue where I wanted the book main page's author (aka owner) to be able to edit all the lower level book page's even if they did not create the pages.

My solution was to create a custom module called 'Book author access' (http://drupal.org/sandbox/jrockowitz/1396474), which use the 'ACL' module (http://drupal.org/project/acl) to control a book's pages access levels.

The 'Book author access' module does propagate the view, update, and delete permissions of the main book page to all to lower level pages, so it is possible that if you use the 'Content Access' module (http://drupal.org/project/content\_access) and limited the view access to the book's main page it would solve your problem.

If you are not a developer then my answer might not be that useful...sorry.

---

As noted in my comment, I think the Book access module probably better addresses your requirements, just look at the below screenshot.

---
Tags: users, nodes
---


# Question
Title: Theme user pictures in comments in drupal 7
I'm trying to set a specific style for user pictures in comments in drupal 7, but can't find how to do it. I know there is a module for this (http://drupal.org/project/imagecache\_profiles) but it's really an overkill since I just want pictures to be themed in comments, according to a style I already created in Image\_cache configuration.

In comment.tpl.php, there is a `<?php print $picture; ?>` , but it's directly the html for the image, so I can't apply the theme function of image cache, for instance `theme('imagecache','size32x32', $data->users_picture);` The $author variable is also html.

Is there a way to get the theme function to work in this comment.tpl.php file ? Is there another way to achieve this ? Thanks !

# Answer
To help you understand the syntax, have a look at the `comment.tpl.php` documentation, here you will find the different variables and a link to `template_preprocess_comment()` where they are defined:

```
$variables['picture']   = theme_get_setting('toggle_comment_user_picture') ?
                          theme('user_picture', array('account' => $comment)) : '';

```

So there's a theme function to render this picture: `theme_user_picture()` which state you should have a look a the template file: `user-picture.tpl.php` which finally send you to `template_preprocess_user_picture()`.

There you can override this function copying and pasting the original code and changing the bits and parts you want to suit your needs (put this code in your `template.php` file):

```
function YOURTHEME_preprocess_user_picture(&$variables) {
  //change only the relevant part and leave the rest of the code
  //For Drupal 7 imagecache is in core so I put the correct syntax
  $variables['user_picture'] = theme('image_style', array('style_name' => 'size32x32', 'path' => $filepath, 'alt' => $alt, 'title' => $alt));

  //...
}

```

Have a look at the `$variables` to find a way to target comments or add a class there and use CSS as dkiscool mentionned.

NB: if you don't like browsing all the API documentation, there's a faster way, use theme developer (see this answer).
> 5 votes

# Answer
In your theme's template.php

```
function yourtheme_image($variables) {
        $attributes = $variables['attributes'];
        $attributes['src'] = file_create_url($variables['path']);

        foreach (array('width', 'height', 'alt', 'title') as $key) {

            if (isset($variables[$key])) {
                $attributes[$key] = $variables[$key];
            }
        }

        return '<div class="your_class"><img' . drupal_attributes($attributes) . ' /></div>';
}

```

this will place a "your\_class" around all the images on your site then in your css file you can target it as

```
. comment  .your_class {border: solid 1px red;}

```

so that it targets only images on comments
> 1 votes

---
Tags: theming, comments, media
---


# Question
Title: Validate upload size before starting upload with Filefield?
I'm doing some pretty massive uploads, up to 1gig. Right now if I upload a 1.1 gig file it uploads to the limit then fails.

Is there any way to make it fail before even beginning the upload?

# Answer
> 2 votes
The only easy way to check a file upload's size on the client-side that I know of is with Flash.

You should see if the Uploadify module works for you. I haven't used the module, but I have used Uploadify a lot, and it works great.

# Answer
> 0 votes
I haven't used them, but check out the Webform module and the companion Webform Validation module, together with the patch on comment #4 in this issue.

You may be able to avoid writing your own client-side validation with JavaScript/jQuery.

---
Tags: 6, files, forms
---


# Question
Title: How to get the body trimmed when loading nodes programmatically?
I'm getting my nodes directly using `db_query` (I'm applying some specific conditions), so I can't use the render function allowing me to get the trimmed (or the summary) version of the body that I configured in the `Manage display` tab of my content type.

For perfomance issue I don't want to use the node\_load function on each of my nodes.

Is there a way that I can use a Drupal internal function that would help me to trim the body value?

# Answer
You can get the trimmed summary using `text_summary()` which will allow you to pass the text, input format and choose the text size (length) you want.
> 4 votes

---
Tags: 7, theming
---


# Question
Title: Displaying grouped view of node comments in a view listing nodes
I've created a view that lists a number of nodes. I've added the relationship of "comments on node" and then added the comments as a field in the view. The problem I'm having is that if there are multiple comments on the node, the view lists the node multiple times. For instance currently the view displays likes this

```
Node Title: Title 1
Nid: 1
Node Image: Image
Comment: Comment 1

Node Title: Title 1
Nid: 1
Node Image: Image
Comment: Comment 2

```

I would like it to be displayed like this;

```
Node Title: Title 1
Nid: 1
Node Image: Image
Comment: Comment 1
Comment: Comment 2

```

I know it has something to do with grouping, and that other similar posts have simply recommended grouping by the title field, but this does not achieve the desired results. Am I missing something?

# Answer
> 0 votes
So far I've only found a couple way of doing this, non of them seem very elegant. If you choose the group by option, it does indeed duplicate all of the fields with the exception of the one you are grouping by. If you omit all the fields form the display, then click on the the grouped field and "rewrite the output" you can use tokens to output all of the fields, and they only display once. Unfortunately, this kinds defeats the purpose of using fields in the first place. The other option is to use the node or teaser view, and make alterations to node.tpl.php and comment.tpl.php as needed ....

---
Tags: 7, views
---


# Question
Title: How do I filter a view with a field on a group the current user is in?
The site I'm working on will have many OG groups, each with a list of topics relevant to their members. I would like to show content to the logged in user that is about their group's relevant topics.

I started by creating a vocabulary (Topic) and two content types (Group and Post). Group and Post both have a term reference field that lists Topic terms (groups have topics that are relevant to the group, and posts have topics about which they're written).

How can I create a view that shows only posts with at least one Topic term in common with the logged in user's group's Topic list?

# Answer
> 0 votes
It looks like this may not be possible with the current stable release of OG (7.x-1.3). I think it would require at least the patch from issue #1341990 along with the patch from this comment on issue #1151648, but I'm completely new to Drupal so it's not unlikely that I'm missing something.

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


# Question
Title: Using Panels and Views to override taxonomy listing - which argument to use?
I'm using Panels to override the taxonomy display at taxonomy/term. I just enabled the term\_view page that comes with Panels and it works great.

So going to mysite/colours/blue shows the Panels page no problem.

Now I want to add a View to the panel that lists the returned nodes. I create the view, and add a relationship 'Content: taxonomy terms on node' (selecting the required vocabulary 'colours').

The I add an argument (contextual filter) on 'Taxonomy term: name'. This works great in the view preview if I enter the value 'blue' but not if I enter 'colours/blue' (no results). And it doesn't work in the panel because 'colours/blue' are the arguments being passed to it.

How do I get the view argument to work with this URL?

# Answer
In the Views UI, each Content Pane has "argument settings". In there you have, at least, two options.

1. The easiest to configure, is "From panel argument", and its option in this case, "Second argument". This works fine in your situation.
2. The most flexible, that I always use, require more understanding of the Ctools context.
    1. The argument setting then is "From context" and in this case "Taxonomy Term" -\> "Name".
    2. Save the View, go into the Panels UI, add the View **Pane**, not just a View.
    3. Assuming your Panel Page now has a taxonomy term, which is always the case on the /taxonomy/term page, you will get a dropdown, most of the time with just one option, that lists the available terms that you pass on to the View.

If you for example had a path like /color/red/blue, because you wanted two terms, the second version will allow the re-use of the same View on the same page, with different content.
> 5 votes

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


# Question
Title: What is Calendar Legend block for? enabled but shows nothing
Playing around with Calendar + Date.

There is a block called Calendar Legend, but shows nothing. **What is it for? Where should I configure?**, I checked the block configuration and views setup, no clues.

Thanks.

# Answer
> 4 votes
The Legend is used on the large calendar page view to help denote between content types or taxonomy. You can set the colours of the content types or taxonomy by editing the view at /admin/structure/views/view/calendar/edit and select Format \> Show \> Settings

# Answer
> 2 votes
This block is useful if you have different event types. It should show a color coded legend of the different event types displayed by the calendar.

If you are using it for taxonomy, there are open issues on this module.

Hope that helps, happy coding!

---
Tags: 7, datetime
---


# Question
Title: Redirect all subpages back to the front page
I am trying to redirect everything that is under example.com/pictures back to the front page (i.e. I am hiding picture nodes to be directly viewable).

Neither the Pathauto module nor the Global Redirect module allows me to do this (or I am overlooking something). I cannot simply block users from viewing that particular node type.

Is it possible doing this with a module? Should I hack something up? Would an .htaccess rewrite help me?

I am interested in an answer for Drupal 7.

# Answer
> 5 votes
I assume "pictures", is a content type. If that's not the case, this may not work. Please provide more details about your setup in that case.

1. Install the Chaos tool suite (ctools) module, and enable the Page Manager module
2. Enable the node template
3. Create a variant of type "HTTP response code".
4. Set the response code to 301.
5. Set the path to \<front\>
6. Go to "Selection rules" in the left menu
7. Add "Node:type == 'pictures'"
8. Save

# Answer
> 3 votes
I belive you search for this module redirect.

Or you could use this example of an .htaccess 301 redirect, make sure your apache servers mod\_rewrite is enable

```
# Redirect "dir/*" to "/"
RewriteRule ^dir/ http://example.com/ [R=301,L]
#
# no-www please
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule (.*) http://example.com/$1 [R=301,L]

# 301 Permanent Redirects
Redirect 301 /dir http://example.com/

```

---
Tags: redirection, path-aliases
---


# Question
Title: Drupal 7 "Panel Nodes" Content Pane Contextual Filter
Does anyone know how to set up a taxonomy-based contextual filter (argument) for a Views Content Pane that is going to be displayed in a "Panel Node" (from the "Panel Node" module that comes with Panels) tagged with the same taxonomy term?

I think I am missing something about how "Panel Nodes" works. I don't get the option for a term ID unless I add a "Relationship" to the taxonomy field in Views. Then I can set the Contextual Filter to the term ID, but it does not work consistently. If I set the "Argument Input" for the pane to "From Context", it works in Views preview with an argument, but it's blank on the actual Panel Node (if the Pane even shows up to be added). If I set it to anything other than "No Argument", it doesn't work at all.

When I use an argument to preview the Content Pane in Views, it works as it should. But on the "Panel Node" page, it's blank. I don't think the argument is making it to the pane.

Some background: "Panel Nodes" is a module that comes with Panels and it creates this Panel-ified content type, but I'm finding very little documentation on how to use it. Panel Nodes are not in Page Manager and so you cannot set a context for them there.

I have a client that could use Panels in their Drupal 7 site just for one particular kind of content type. For this particular use case, the the "Panel Nodes" way of generating the content is the most intuitive for the client (enter a title, body, an image into a node add form, and then click on the Panels Layout and Panels Content tabs right from the node form; I believe this is a similar model to the way http://drupal.org/project/panelizer is supposed to work).

# Answer
I urge you **not** to use Panel Nodes. Panel Nodes are being deprecated in favor of Panelizer. The largest hurdle to getting rid of them is that I need to complete the upgrade path. I suggest that you

1. Move to Panelizer, following the upgrade path issue if you already have Panel Nodes.
2. If necessary, repost a new question with regard to Panelizer.
> 1 votes

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