# Question
Title: How do I create a contant managed list of linked images and display it as a block?
On the homepage of the site I'm making I need to have a few CTAs (calls to action) linking to products in the shop, which is running Drupal Commerce. The CTAs comprise of:

* An image
* A link title
* A URL to a product display node
* A limit of 2 CTAs

Is there any way I can do this using Views 3 (I'm guessing that would be the best way, please correct me otherwise) without writing my own module? I only have a very basic understanding of writing modules.

# Answer
I would go down the views route as it will be the simplest. Just set the filters to only return products that have images and limit the view to output 2 items max. You could add an extra field onto the product content type that you then check for in views to allow the admin to control which products get sent to this block.
> 2 votes

---
Tags: views, blocks
---


# Question
Title: How do I make a $node object properties available in my views--template?
I have a node--type and view--type templates. In view--type I cannot access `$node`, for example with `$node->nid`.

How can I inject `$node` inside view type templates?

I have a views-view-field--mypage--page--body.tpl.php file; this is a field template of the body of teasers where I inserted a *Read more* link. I need the URL for that link.

# Answer
> 1 votes
Views doesn't load the complete `$node` object for performance reason. Instead, it build, or attempt to build, an optimized query to only load the fields configured in the Views.

When editing the views, you should have a *Fields* block. In this block, use its *Add fields* links to add the additional fields you want to use in your template. If you don't want to display these fields using Views itself, be sure to configure them to be excluded from display.

# Answer
> 0 votes
You can add the properties you need in the view and exclude them from display. This will make them available in templates, but won't effect the markup.

Alternatively you can load the node with `node_load`, but to do this, you need to nid (node id) from somewhere. One way would be to use the above technique.

# Answer
> 0 votes
What kind of information do you need from the `$node` object that you can't get from views standard options?

If you enable views\_customfield you can add a PHP code field into the Views UI. Just add the node NID as a normal field and then add a custom PHP field, then use:

`print var_export($data, TRUE);`

in this new PHP code field to show you what items you can call from the views result.

One of them will be the nid so you could use `node_load($data->nid);`

Remember you need to add the PHP opening and closing tags around your code in the Views customfield.

You could do the same in a template or preprocess function too and if you have some complex logic that is what I would recommend.

---
Tags: views, theming
---


title: Outputting node fields individually

text:
# Question
Title: Outputting node fields individually
I have a node template but instead of outputting $content, I want to have more control over what the template displays by printing each field individually.

Below are the fields I want to include:

`$title` `field_img` `$body`

What code would I replace with? Also, are there any significant disadvantages to using this method?

# Answer
> 2 votes
If you already have a custom node template (tpl file) to theme your node then you're halfway there. You can use `<?php print_r($node); ?>` to see the node structure and find out how to print your fields.

For example, to print those 3 fields, you can use something similar to:
`<?php print $title; ?>`
`<?php print $node-field_img['view']; ?>`
`<?php print $node->content['body']['#value']; ?>`

Remember to use the `print_r($node)` to check the structure and print the fields similarly as above while including the HTML for the layout.

# Answer
> 1 votes
First install and enable the devel module as it makes the process of looking at the $node object a lot easier.

Make sure you have a node.tpl.php in your theme (You can create your own node-my-content-type-name.tpl.php also but in D6 you need to have a node.tpl.php to make this work).

At the top of the node.tpl or your own tpl file add.

`kpr($node);`

you can then easily traverse the object/array. you can also use dpm($node). Remember if you exclude the $content variable any new fields that are added to your content type won't be output unless you specifically output them in your tpl. In D7 this has changed as you can use:

`print render($content['field_example'])`

and

`print hide($content['field_example'])`

---
Tags: theming, nodes, entities
---


title: Exposed field in view not showing

text:
# Question
Title: Exposed field in view not showing
I'm trying to build me a search function using the exposed fields in a view. But for some reason, the exposed fields don't show up...

My main search module is enabled, my D7-website is indexed and I have a module called `Better Exposed Filters` enabled. But still, no exposed fields are popping up. What do I do wrong not to get any exposed fields?

# Answer
> 2 votes
OK, I found it myself. The trick was to turn on AJAX (for some weird reason).

---
Tags: views, search
---


title: Where do I declare a global variable?

text:
# Question
Title: Where do I declare a global variable?
I need to define a global variable. Where should I define it?

1. I will not use the global variable in template files
2. I should not use settings.php
3. I will only use the global variable in all the custom module files

# Answer
Personally, I would either write module that abstracts away the need for a global variable, or at least has a getter function for retrieving it. Something like

```
function foo_get_the_service ()
{
  static $service;

  if (! isset($service)) {
    $service = foo_init_the_service();
  }

  return $service;
}

```

Several Drupal API functions do something similar (eg, menu\_get\_active\_trail() and menu\_set\_active\_trail());

And then preferably, your module would also have helper functions so you don't need to access the global directly. If something really does need the global, then you would use the getter.

If your global is an instance of a proper PHP class, then you could look into using a real singleton.
> 8 votes

# Answer
I think what you're looking for is making use of Drupal's variables using variable\_set() to create it and variable\_get() to retrieve it for use in your modules.

To use variable\_set() just provide the variable name and value: `variable_set(name, value)`.

To use variable\_get() you just need to provide the variable name and default value (to be used if not yet set): `variable_get(name, default_value)`.
> 3 votes

---
Tags: 7
---


# Question
Title: How do I require the user submitted content to be approved before it is published?
I need to have content that is submitted by users of a certain role to be approved by an administrator before it is published. I thought this functionality was build in already, but I just can't seem to find where it is.

# Answer
> 7 votes
You may be interested in the Workbench module combined with Workbench Moderation.

From the Workbench project page:

> Workbench provides overall improvements for managing content that Drupal does not provide out of the box. Workbench gives us three important solutions:
>
> * a unified and simplified user interface for users who ONLY have to work with content. This decreases training and support time.
> * the ability to control who has access to edit any content based on an organization's structure not the web site structure
> * a customizable editorial workflow that integrates with the access control feature described above or works independently on its own

From the Workbench Moderation project page:

> Workbench Moderation adds arbitrary moderation states to Drupal core's "unpublished" and "published" node states, and affects the behavior of node revisions when nodes are published. Moderation states are tracked per-revision; rather than moderating nodes, Workbench Moderation moderates revisions.

# Answer
> 2 votes
You could use the Rules module to setup a workflow.

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


# Question
Title: Difference Between render($content['body']) and print $body[0]['value']; in node.tpl.php
What is the difference between `render($content['body']);` and `print $body[0]['value'];` in node.tpl.php?

`render($content['body']);` seems to include all the fields while `print $body[0]['value'];` includes just the body field.

# Answer
You kind of answered your own question. `$content['body']` contains everything in a structure in which the render function can turn it into display. This includes all your fields.

`print $body[0]['value']` simply prints the value of that one field bypassing any rendering functionality such as "weight".

Rendering is a fun thing in Drupal, especially when you get to Drupal 7. Think of what you're passing into "render" as instructions on how to output, whereas the `value` is simply... a string... a value.
> 5 votes

---
Tags: nodes
---


# Question
Title: Using Fields as Attributes in Node Templates
What is the best practice for using a field as an "attribute" in a node template with Drupal 7? I am using the term "attribute" loosely here to mean something that can't be concretely rendered as an HTML fragment; rather, it gets rendered inside an HTML fragment somewhere in a template.

The field API makes it very easy to wrap a "content" field with HTML so it can be rendered in a template, many times with out needing to edit the node template at all, due to the way render trees work.

Consider a content type such as

* Title (title)
* Body (body)
* Extra (field\_extra)

Where field\_extra is just something that I want to tack onto the node title, eg

```
<?php if (!$page && $title): ?>
<h2><?php print $title ?> — <?php print $extra; ?></h2>
<?php endif; ?>
print render($content);

```

This is a very, very simplified example to illustrate what I am talking about.

I could just access

```
$extra = trim($field_extra[0]["safe_value"]);

```

but I would have to go through some show()/hide() logic depending on how things where configured, and directly accessing fields is discouraged.

I could make a theme\_field(), such as

```
function mytheme_field__field_extra ($variables)
{
  $items = $variables["items"];
  return count($items) == 0 ? "" : trim(drupal_render($items[0]));
}

```

and then use render(), but I would still have to go through the show()/hide() shenanigans and I am not really rendering the field, just trying to get a plain version of it to use somewhere.

Or, should this really be handled by a template\_preprocess\_node(), eg

```
function mytheme_preprocess_node (&$variables)
{
  $node = $variables["node"];
  $language = $node->language;

  if (isset($variables["field_extra"])
      && isset($variables["field_extra"][$language])
      && isset($variables["field_extra"][$language][0])) {
        $variables["extra"] = trim($variables["field_extra"][$language][0]["safe_value"]);
  }
}

```

I know all of these will work. I am really interested in what is the best practice here. I suspect that the template\_preprocess\_node() is the best way to handle this, but I have not seen anything definitive about this case.

Thanks.

# Answer
Is there a reason to not just set the format to `"<hidden>"` in the content type's "manage display"? Then it will never render but you still have it if you want it.

If you really want to do this programatically, the best practice, for me, is to use a module not your theme. Why? Because if your theme changes... do you want extra to show? Nope, so make it independent of the theme by putting it in a module.
> 1 votes

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


# Question
Title: Change the content of a node programmatically with hook_node_view
I need to append some text programmatically before the text on the home page. But when I use `hook_node_view()`, I can't seem to do this with the following:

```
function general_node_view(&$node, $view_mode, $langcode) {
    if ($node->nid == 1) {
      //echo '<pre>' . print_r($node->body['und'][0]['value'],1) . '</pre>';
      $node->body['und'][0]['value'] = 'fdsf' .  $node->body['und'][0]['value'];
   }
 }

```

Am I going about this the wrong way?

# Answer
> 1 votes
If you are trying for home page then your node should be set as front page content. Otherwise this hook would not do any thing for your home page.

However any node view can be expanded by this hook:

```
$node->content['additional-text'] = array(
   '#markup' => 'TEXT TO GO BEFORE NODE VIEW',
   '#weight' => -10, // Set as lower as to bring this markup upper
);

```

# Answer
> 1 votes
As reported by the documentation for `hook_node_view()`:

> The module may add elements to `$node->content` prior to rendering. This hook will be called after `hook_view()`. The structure of `$node->content` is a renderable array as expected by `drupal_render()`.

You are not supposed to change `$node->body`, but the content of `$node->content`.

---
Tags: 7, nodes, hooks
---


# Question
Title: How to create Country, State, City and Zip Code field in D6
I am having a registration page which contains the field Country, State, City and Zip Code Which needs to be hierarchical select.

My question may be very basic. But kindly clear it.

I have used content profile module to create all the registration fields.

**My question is what field type i need to give for the above fields what i mentioned (Country, State, City and Zip Code). Which needs to be hierarchical select.**

**Is there any examples or tutorials related to this topic will help a lot for me.**

Any help will be thankful and grateful.

thanks in advance..

# Answer
> 1 votes
Try the Hierarchical Select Module which works with Taxonomy Terms, Menus, User Profile Fields, Generic Lists and External APIs. The field types you use for storage would not matter.

There are demos available on the module developer's blog.

Warning: In the case of City Names and Zip Codes there is no hierarchy (at least in the States). Many Zip Codes have multiple city names, many cities have multiple Zip Codes. For any hope of keeping this all current you'd have to use an external API.

---
Tags: 6, nodes
---


# Question
Title: How to generate a downloadable CSV file from a View table?
Is there any way to generate a downloadable CSV file from a View table? If not, how can I generate a CSV file in Drupal 7?

# Answer
> 8 votes
You can create/export CSV files from Views in Drupal 7 with the Views Data Export module. The module is currently in Beta.

---
Tags: 7, views, importing-exporting
---


# Question
Title: Presenting a menu within page content with associated descriptions and images
Currently, I have a drupal project where I have two levels of menus. (So for example, the top menu has "home" "about us" "faq" etc.) each top level menu has a secondary menu.

I'm trying to create a node for each top level menu item that is an 'overview' of that category. One of the things that I'd like to do on each overview page is provide an expanded version of that secondary menu in the content area, where instead of just having links, we would also have a description and an image associated with each menu item. (So on the "About Us" page, there would be a link to the "About Us-\> History" page, and this link would have an icon and a description). Ideally, I'd like to lay these out as a set of horizontally spaced squares below the content area.

Currently, I'm managing this by creating a custom block for each link/image/description combination, and using Context to toggle the appropriate blocks on and off, but this seems really inefficient and error prone. Can someone recommend a 'correct' way to do this?

# Answer
I'm not positive I entirely understand what you envision, but one possibility might be to use the Menu Trails Module to handle the submenu.

For the section of blocks you are currently toggling on and off contextually, I might consider instead authoring a block in Views that is queried off a default argument passed through the url. This argument would be the same value from the Main Menu which is configuring the Menu Trails and could be configured to display the node teaser (or a cck/field value called Overview) for the active Main Menu Item.

Or what you may be describing is something more like a list of submenu items as teasers,:

```
[Some Photo] | [Some Photo] | [Some Photo]
[Menu Title] | [Menu Title] | [Menu Title]
 [Overview]  |  [Overview]  |  [Overview]

```

In that case, I'd still use Menus to organize the content hierarchy, but don't check expand in the menu options. Instead, use the method described above to construct a block in Views that displays all the submenu items. You won't need Menu Trails for this type of display.
> 0 votes

---
Tags: routes, blocks, navigation
---


# Question
Title: How to configure relationships created by the User relationships module
I've managed to get my UR module setup. My users can now add each other. However, the only problem am faced with is that when Alice adds Bob and Bob accepts the friend request, only Bob can see Alice's name in their current relationship list; in Alice's current relationship list Bob does not appear.

Furthermore, Alice does not get a confirmation when their friend request is accepted. How can i go about fixing this problem?

I am using Drupal 7 and the zen sub theme.

# Answer
> 4 votes
User Relationships supports bi-directional relationships unless you have checked the "This is a one-way relationship" checkbox.

However, there is a bug in the current 7.x-1.0-alpha2 version, make sure you use 7.x-1.x-dev instead.

If the Relations module works for you, fine. But the main thing that UR provides is various user interfaces to request relationships, see/administer them in listings, approve them, see your relationships with other users when visiting their profile and tons of additional modules like integration with Privatemsg.

In fact, we plan on making UR just a fancy UI on top of the Relations project, but that's quite a way to go.

# Answer
> 0 votes
For building Social Networking-style User Relationships the Relation Module may be more appropriate than a user reference because it natively allows bi-directional joins. A User Reference is natively one-way as you have discovered.

Johan Falk has a pretty good video of the Relation module explaining its use that would help get you started.

As for friend request confirmations, I would look at use the Rules module to trigger that acceptance on the friend request and have an Action of send Email where you can use tokens to build a custom message.

---
Tags: 7, users
---


title: Custom view with selective PDF output

text:
# Question
Title: Custom view with selective PDF output
I'm hitting a blank, I need to be able to offer a print option on some views (a pdf) and not on others.

Does anyone have an elegant way of doing this?

Thanks for looking, I appreciate your time.

# Answer
> 2 votes
Take a look at the Views PDF module. It will allow you to add a "PDF" display to the views you choose. From the project page:

> With this module you can output a view as a PDF document. Each field of the view can be placed on the PDF page directly in the administration interface. Therefore a new display called "PDF" is added.

---
Tags: views, files
---


# Question
Title: Drupal Module - Mailing List, cannot export list, get browser error
I've just started using the mailing list module, but when I put it on my live site I get an error when I try to export the list of entries. I did get an actual Drupal error which is

```
    Error
The website encountered an unexpected error. Please try again later.

```

this put an entry in my Log which I followed up on the net and found this page http://drupal.org/node/1206916 entry #11 led me to a link which should fix this, I tried this, but now I just get a Browser failure saying it cannot locate the file.

any ideas? or is there a better mail module?

# Answer
If you are having trouble with the module you are using, there are other mail-type modules available.

* MailChimp \- Module to utilize subscriptions/emails with mailchimp.com
* Simplenews \- Publishes and sends newsletters to lists of subscribers (still in Alpha)
* Notifications \- Complete Subscriptions/Notifications Framework aiming at extendability and scalability (still in Alpha)
> 0 votes

---
Tags: emails
---


# Question
Title: How can I alter the contents of a form before they are submitted?
I'd like to do something like the following:

Let's say that I intended to allow users to input their Social Security Number, in the format 123-45-6789, which is a field in a "Person" content type. When saving to the DB though, I'd like to store this SSN as an integer. So, before the form gets saved, I want to remove the dashes. How can I do this? I can't find an appropriate hook that will allow me to alter the data BEFORE it is submitted. Adding a submit handler would not work, I believe, since this additional handler would trigger after the data is already saved.

EDIT: I'd now like to change this value before the individual element's #element\_validate function is used. I tried changing the callback of this element's #element\_validate function, but then the actual value isn't being changed before being submitted to the database, and I get an insertion error.

EDIT2: I'm attempting to use value\_callback, but still having the same issue - either I'm using this incorrectly, or this is not firing before the element's validator. Either way, the result is that rather than attempting to insert "123456789" into the database, "123-45-6789" is attempted, and since this is an integer field, insertion fails.

# Answer
> 3 votes
You may be interested in form\_set\_value(). You would use this within the form validation function. There are examples of its use posted below the API documentation in the comments if you need further clarification.

For help creating a validation function, see the Form API Quickstart Guide (D6) or How to use the Form API (D7).

# Answer
> 1 votes
Technically, to alter it before it is *submitted*, you'd need to do that in the client with JavaScript. However, what you are looking for I think is altering it before it is *saved*.

For nodes, you can implement `hook_node_presave($node)` where you can change any properties of the node object right before it is saved.

Form fields also support a #value\_callback, which allows you to alter the actually submitted value and return something else/changed.

---
Tags: forms, nodes
---


# Question
Title: Content type with multiple users - create a view of all users that relate to content of that type
Suppose you have a content type called political party. Political parties can have members that are users. A user can be a member of multiple political parties.

I am trying to create a view where I list every user that is a member of a political party, and list them each only once. I don't need to see what party they are in, and this should just be a newest user sorted list of users that are listed in at least one political party's member field.

So these are the content types that need to be related:

```
party
   |-members (user reference list)
user

```

How would you construct a view for this using the views module? I am a little lost on how to tackle this.

(note: I am using political parties, but actual content type name is different. It just is easier to explain this way)

# Answer
I'm not entirely positive this is the type of relationship you want for this data. If you use a node\_reference field on the user rather than a user\_reference on the node it would be pretty straightforward to create a view of Users who party.

Query all users and then add a Relationship to the field\_party node reference. Require the relationship with a Delta of 1.

This type of reference would seem to make more sense for your use case as well, since this would enable any user to administer their own party affiliations rather than the party manage the list (but then this is an analogy and I don't know the particulars).

Either way you are hitting up against the boundaries of what is possible using references. I'd encourage you to take a look at the Relation Module which is designed to handle these kinds of bi-directional relationships, e.g. Display the members of the Party, Display the parties an individual is a member.
> 1 votes

# Answer
If the users are actual people that are going to be adding themselves to these groups then it sounds like you might have better luck with the Flag Module.

This will allow uses to 'join' any political party node by flagging it, and you can setup a view that will show only users that have flagged the particular node.
> 1 votes

---
Tags: views
---


# Question
Title: How does POST action work on a drupal login form?
I was looking at the login form tag of Drupal and was surprised that it does not reference any specific page to handle login. Example:

```
<form action="/node?destination=node" .....>

```

Or if I go to the login page directly:

```
<form action="/user/login" .....>

```

or

```
<form action="/user" .....>

```

So how does this work? How does the browser know which page to submit the POST data to?

# Answer
Drupal uses the Form API to handle this. It doesn't need a specific page to handle the POST data because of the way its structured. Also see user\_login to get an idea of how it's implemented. You can see that it sets specific validation functions to be called when the form is submitted, and then it moves on to `user_login_submit` (this part happens due to the default naming conventions of the Form API). There's other magic in there that makes this all work, but it usually isn't necessary to understand it in order to develop with Drupal.
> 1 votes

---
Tags: 7, users
---


# Question
Title: How to add a menu tab to a node to link to an information page to be used by author?
I just need some direction from module developers. I would like every node to have an 'information page' that the author can easily view. When they are logged in and viewing the node, I'd like it to appear as a link right along side that node menu bar (where it says "Edit, Revisions, Devel" etc.), called menu tabs.

I'm not very familiar with custom modules, but I'm simply looking for the basic framework, or an example module, that will add that menu link, and also allow me the place to begin adding my code.

I'm basically trying to display Google Analytics data for each node.

# Answer
Check out the Examples for Developers module, particularly the menu\_example sub-module. You are looking to create a MENU\_LOCAL\_TASK-type menu. This should get you started.
> 1 votes

---
Tags: 7, theming, routes
---


# Question
Title: Place or attach permanent file to the node edit form
I want to make an attachment available for download to the user who is filling out a node edit form. This attachment will be a file template that they will fill out, save, then upload to the filefield field at some point, so I want the attachment to ALWAYS be available on the node edit form.

I realize I could do this by placing a block on the page via the block admin ui, but I would like to accomplish this using `hook_form_alter`, because the file that is attach will be specific to certain field within that form having certain values when a user is editing the form. I've provided a visual mock-up for further clarification.

# Answer
If it's a PDF, you might also want to look into Fill PDF.
> 1 votes

---
Tags: forms
---


# Question
Title: Printing to a strict template (multipage invoices / multiple delivery labels per sheet etc)
I would like to be able to print out hard copies of some strict templates.

Primarily I would like to eliminate the web browsers header and footer garbage that plagues printing from the web. I am prepared to be locked into a specific web browser for the purposes of printing such documents, as I understand this is a source of variability.

Specific examples of documents to be printed are:

* Full page / multipage invoices that would require line breaks in specific places (and the ability to provide a custom page header for each individual page)
* Printing to label paper (6/8 labels per A4), which would require fairly decent precision in order to print to the correct regions of the paper, as well as being able to specify page breaks for printing a multitude of labels across a many pages.

Is there a Drupal specific method for achieving this, preferably directly from browser to printer, although alternatively via PDF or some other means?

I understand that I might need to settle for something less-than-perfect, but anything available that is either Drupal specific would be greatly appreciated. For non-Drupal solutions, I have posted a similar question here at StackOverflow.

# Answer
> 1 votes
You can look into Fill PDF as an option. For this, you'd have to pre-create the templates with fillable form fields and would probably need a bit of programmatic glue to deal with page breaks, number of pages, etc. Fill PDf basically lets you use tokens from nodes and webforms to populate fillable PDF fields.

It would probably make achieving your template easiser.

---
Tags: 7
---


# Question
Title: How can we output unfiltered HTML in a CCK field
This seems like the simplest thing but for some reason we just cannot get this to work.

We have create 4 additional CCK fields for our "product" content type.

We enter simple HTML in to these fields and want to display these, as is, unfiltered on the node output.

Whatever we do, it always outputs as plain text, stripped of all html. Weve seen numerous references to the "Text Processing" options within the field settings, but they dont appear for us.

Ive even gone in and changed the text\_processing value within the database for the field, Ive tried manually setting the filter type within the text.module code, weve spent days on what seems to be a simple and fundamental task.

How can we achieve this?

# Answer
> 1 votes
OK after searching high and wide for a solution, I finally came across this article: http://drupal.org/node/1100430

Basically the CCK component module "Text or Node Reference" causes an issues that hides the "Text Processing" options, disabling this module allowed us to change the input filter format!

---
Tags: 6, entities
---


title: Per user language selection

text:
# Question
Title: Per user language selection
I need to do the following on my Drupal 7 site:

1. Anonymous users should see the website in Ukrainian (I mean not the content, but the elements like "Login", "Register" etc.)
2. Administrator (the user with all permissions) should see the admin panel in English.
3. Editor (custom created user that can create pages) should see his admin interface in Russian.

I suppose it can be done with a per-user language setting, but I cannot find how to do this. I already have all the translations installed.

# Answer
"Follow the user's language preference" option in Drupal language preferences does the trick.
> 4 votes

---
Tags: i18n-l10n
---


# Question
Title: How to only allow specific users to edit certain "fields" when creating content?
I want to be able to hide specific fields form users on the create content form. For example, I might let any authenticated user create an article but only the editors can use the upload a picture field and the category field.

# Answer
Use the Field Permission Module. This will provide the functionality you're looking for.
> 3 votes

---
Tags: 7, users
---


# Question
Title: Drupal7+Omega Theme: How to narrow the 20px gutter between columns in 960 grid?
Is it possible to alter the allmighty 20px gutter in 960px grid especially when using with Drupal 7 Omega subtheme?

# Answer
> 3 votes
If you search Google for "Drupal Omega custom grid", you find links like:

Hope that helps.

---
Tags: theming
---


# Question
Title: A view with exposed sort: can i turn off 'grouping field' for different sort criteria?
My Views list of events is grouped by the date (using the Grouping Field checkbox in the Style settings).

*But* my exposed Sort Criteria can sort the list by either date or by name.

**An alphabetical list of events grouped by date really doesn't make any sense.**

What would make sense is for the Grouping Field to turn off when the Sort Criteria is by name.

I'm thinking either i do two views, and my template decides which view to embed depending on the URL query. Or perhaps a views hook like **hook\_views\_query\_alter()** could turn off the Grouping Field depending on the circumstances?

# Answer
> 2 votes
Ok, i think i've managed it with a Views hook. Took an hour's worth of tinkering. I plopped this into my template.php...

```
/** Find out what the sort criterion is.
    @return The sort criterion fieldname. IMPORTANT: this isn't sanitised!
*/
function MYTHEME_get_sort_by() {
    if (isset($_GET['sort_by']))
        return $_GET['sort_by'];
}

/** Turn off Views grouping-field when sorting by title.
*/
function MYTHEME_views_pre_build(&$view) {
    if ($view->name=='event_programme') {
        if (MYTHEME_get_sort_by()=='title')
            $view->display_handler->options['style_options']['grouping']='';
    }
}

```

---
Tags: views
---


title: How to disable comments in node.tpl?

text:
# Question
Title: How to disable comments in node.tpl?
I decided to programatically print comments un Views using PHP footer. The problem is that they now appears twice (my code + default). When I disable comments in content type settings, both ddisappear. How can I disable the default comments and keep my comments printed by php code? I tried to edit node.tpl file. but there is no section responsible for showing comments there (I use Garland). Any advice appreciated.

# Answer
Have you tried looking into the comment.tpl.php file?

You should be able to hide the 'real' db driven comments there and only display your printed comments.
> 1 votes

---
Tags: 6, theming, comments
---


# Question
Title: Alternative to Simplenews, or a way to send formatted mailing lists to subscribers?
I have installed simplenews on Drupal 7 but it seems all the related modules: Simplenews Content Selection (to build up the newsletter using nodes or views) and Simplenews Template are outdated (Drupal6).

Is there another way to use the nodes in the sites or at least creating a template to reuse with this module?

Or is there a way using other mailing list modules or custom code to build up newsletters from nodes?

br. onirio

# Answer
Check out the new Newsletter module.

```
Features

Multiple newsletters lists configurable on terms, not vocabularies
Plain text or HTML out of the box
Multiple schedules Each newsletter can have more than one schedule, e.g. Daily, Monthly, Weekly, manually or even custom, eg after 10 new posts for this term.
Centralized administration and configuration on single page.
Users can customize the terms in the list they subscribe to
Custom template per list
Statistics (CTR and Open-Rate)
Drupal 7 only

```
> 1 votes

# Answer
This method (or something similar) worked in D6, I guess you can still do it in D7: Add a reference field to your newsletter, load the referenced nodes in the preprocess function for your template using node\_load\_multiple, and render them using as a list of teasers using node\_view\_multiple.

Another approach would be to build a view and attach it to a newsletter node using Entity View Attachment. However that's just a thought - I haven't tried the combination of Simplenews and EVA myself.
> 0 votes

---
Tags: emails
---


# Question
Title: How can I add to the class name of a form element?
I'm trying to add an additional class to a form element using the following code:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function grant_opportunity_form_grant_opportunity_node_form_alter(&$form, &$form_state, $form_id) {

    $form['grant_opportunity_end_date']['#attributes']['class'][] = 'datepicker';

}

```

But the additional class is not being added. Am I doing this incorrectly? This is a very simple thing I'm trying to do, so I'd prefer not to go through the trouble of overriding the theme, or anything more involved like that.

EDIT: To be clear, a class is being added to the parent div of this element, but not the element itself.

# Answer
> 3 votes
I think it needs to be an array.

Try this:

```
$form['grant_opportunity_end_date']['#attributes'] = array('class' => array('datepicker'));

```

You can also call it directly from hook\_form\_alter(). For example in your themes template.php you could add:

```
function YOURTHEME_form_alter(&$form, $form_state, $form_id)   {
  if($form_id == 'YOUR_FORM_ID') {
    $form['grant_opportunity_end_date']['#attributes'] = array('class' => array('datepicker'));
  }
  // this displays some general info so you can check
  drupal_set_message("Form ID is : " . $form_id);
  drupal_set_message(dprint_r($form, TRUE));
}

```

---
Tags: forms
---


title: Give a CCK field a non-editable value?

text:
# Question
Title: Give a CCK field a non-editable value?
Is it possible, not only to give a CCK field a default value, but also make it non-editable by the user?

# Answer
I used jquery to do just that.

```
(function($) {

$(document).ready(function() {

// make the number field uneditable!
$('#edit-field-entry-custom-id-und-0-value').attr("disabled", "true");
});

}(jQuery));

```

to be safer however, in case someone disables javascript you could add this to your themes template.php

```
function YOURTHEME_form_alter(&$form, $form_state, $form_id) {
 if($form_id == 'YOUR_FORM_ID') {
  $form['FIELD_NAME']['#disabled'] = TRUE;

  // YOU CAN UNCOMMENT THE BELOW FOR EXTRA HELPFUL DETAILS
  // GET FORM ID UNCOMMENT BELOW
  // drupal_set_message("Form ID is : " . $form_id);
  // GET ALL FORM ELEMENTS UNCOMMENT BELOW
  // drupal_set_message(dprint_r($form, TRUE));
 }
}

```
> 2 votes

---
Tags: 6, entities
---


# Question
Title: How to display add node form with node reference?
I have a very similar functionality to stackoverflow - i.e. I have a a view that display question and below it there are answers (seperate nodes references).

Currently, in order to add new answer to the question, the user has to click on a link, which takes him to add node form. But I need to display the form below the view, so the user can answer without being redirected to add node form on a seperate page. I guess it can be done programatically using `drupal_get_form()` function, but I have no idea how to start. Can anyone give me any suggestion or tutorial? Or maybe there is module for that..? Any advice is greatly appreciated.

# Answer
Don't worry, there's a module for that! http://drupal.org/project/formblock I believe this can work with node-references with a bit of configuration. If not, you can use this tutorial to populate the node reference: http://grayside.org/comment/830 which should get carried over by the FormBlock module.
> 2 votes

# Answer
I'm using the following code to load an empty node creation form:

```
//create empty node and build node edit form
    module_load_include('inc', 'node', 'node.pages');
    $node = (object) array('uid' => $user->uid, 'name' => (isset($user->name) ? $user->name : ''), 'type' => 'player', 'language' => LANGUAGE_NONE, 'title' => '');
    $player_form = drupal_get_form('player_node_form', $node);

```
> 1 votes

---
Tags: 6, forms, nodes
---


title: Private messages problem

text:
# Question
Title: Private messages problem
In Drupal 6.22, after installing 'User Relationships', APK , Content Profile and some related social modules. Then upgrading the server (Ubuntu), ans saw that private messages stopped being received by the users.

I have disabled UR, APK et al. and updated the database, but it had not fixed the problem. I even dropped the whole database and used a backup from a time prior to adding social modules. No curing effect.

The server still sends out emails and I am pretty sure that privatemsg permissions are set correctly, so that users should be able to send/receive privatemsges.

This might be clue: The users can receive privatemsg from debug (privatemsg test module), but not from other users. Not sure what does this imply.

I have really ran out of ideas and appreciate your hints.

# Answer
Ok, it had nothing to do with the modules that I thought were culprit. Infact after a lot of experimentation I realized that the issue is caused by Spam module: 6.x-1.3 silently prevents all private messages from being sent

After downgrading to the previous version of Spam, the problem was gone.
> 1 votes

# Answer
So u upgraded Ubuntu, anything else? Php, apache etc? First verify using VMware it is in fact Ubuntu upgrade only that is causing the issue. You say you redeployed an older version of the db. I would be tempted to do a full deploy just to try to reproduce including Drupal code. It's an odd problem, my instinct says possibly a difference in php version could potentially cause this.
> 1 votes

---
Tags: privatemsg
---


title: How to create a basic page

text:
# Question
Title: How to create a basic page
This is a really dumb question, but I simply want to create a basic page with it's own path, (i.e. mysite.com/contact) so far I've only had to use Views to display node data. Views have the option of specifying a path, but I'm assuming I don't have to create a view to display a regular page?

The Drupal docs say the default installation comes with the "Basic page" content type, so I tried creating that content type, but I can't see an option to specify a path...

I feel very silly \>.\<

# Answer
> 4 votes
You don't set the path when creating a content type. Once you create a "basic page" content type (or use the one that comes with the "standard Install" of Drupal core), you can then create a basic page by going to node/add. Then in the vertical tabs at the bottom of the node creation page, you will find a tab called, "URL path settings". In there you can manually specify a path. If you wish to avoid having to manually adding a path for every node, use the Pathauto module.

---
Tags: 7
---


# Question
Title: Modal windows module for Drupal 7 content?
I have looked at a bunch of modal window modules but they all seem to only apply to media such as images or videos.

Do any of the modal window modules (lightbox, shadowbox etc) for drupal 7 allow drupal content to be displayed within, for example blocks / webforms etc?

# Answer
checkout this post, it recommends the shadowbox.
> 0 votes

# Answer
I've used the colorbox module for this purpose for a couple of recent D7 projects. It works well and seems to fit your use case.

You might also want to checkout the overlay module in D7 core, but it generally involves more effort to make it work for the non core use cases.
> 0 votes

# Answer
If you want to use the Overlay module in core this post explains how to implement it quite well. Another useful reference is the User Modal module which contains examples.

The limitations include the requirement to assign the 'Access the administrative overlay' and 'View the administration theme' permissions to your users and the need to declare your paths in hook\_admin\_paths() as administration paths.

So while Overlay might seem like a good idea it is in fact aimed at administrating Drupal rather than being a modal framework for general use. Unfortunately the other candidate modules for this functionality aren't there yet with a D7 release so it may be the only alternative to ctools' modals or the various lightbox modules at this point. I guess it depends on what you want to put in there and how much dev work you are interested in doing.
> 0 votes

---
Tags: 7
---


title: Drupal 7 and MongoDB module howto

text:
# Question
Title: Drupal 7 and MongoDB module howto
Just installed 7.x-1.0-beta1 to Drupal 7rc1.

Should I see some new option in the configuration? Where should I set the connection settings? I have no idea how to use this module...

# Answer
I (and my team) wrote most of that module and -- as Jeremy says, it's only needed for extreme scalability. Because of that, it's supposed you know what you are doing (otherwise you will have no chance of scaling to the levels where MongoDB is necessary) and so no UI is provided, just use $conf overrides.

There's a DBTNG driver too but it's more in a proof-of-concept stage so it's in a separate project.
> 5 votes

# Answer
This is not a module that you should use unless you have a need to. It can support mongoDB in a number of cases, but doesn’t look like it will totally replace mysql.

Generally you should be looking to use something like mongoDB if you are starting to have scalability problems.

What are you actually trying to do?
> 2 votes

---
Tags: database
---


# Question
Title: How do I add attibution links to 'teaser thumbnails' in Drupal blog posts?
I'm running a professional blog on, I believe, Drupal 6.17. It allows me to include a 'teaser thumbnail' of an image with each blog post. However, many times I want to use free stock photos from sites such as flickr and freedigitalphotos.net as that teaser. However, these sites require you to include a link back to the photographer's page along with an attritbution on the same page as the photo. I'm not sure how to do that with Drupal's 'teaser thumbnail' option.

# Answer
> 1 votes
For D6, use the ImageField Extended module. It provides a very simple admin interface to give you a way of adding textfields, textareas, WYSIWYG textareas and checkboxes.

---
Tags: media, nodes
---


title: Theming simplenews

text:
# Question
Title: Theming simplenews
I am finally starting to figure out how to theme Simplenews and it seems to be working. Kind of. However, I have yet to figure out how to change the structure of the document. For now, the nodes I include in my newsletter are sent as a title in a paragraph tag, a teaser also in a paragraph tag and a 'read more' link. I need the title to be in an H2 tag... where can I change this?

# Answer
So basically to achieve the desired result (for a Drupal 6 site), I used the following modules:

* Simplenews (for the very basic newsletter functionality but very little else)
* Simplenews Content Selection (so you can select the nodes you want to include in your newsletter)
* Mime Mail (helped me with some theming and styling issues)

In simplenews' directory, there is a sub-directory called themes which contains several template files including a body template which allows you to theme around the newsletter content.

Also, for each node, simplenews content selection's default output is a title, teaser and 'read more' link. I just want to add that to change simplenews content selection's default format, there is a file in the module directory called scs.theme.inc and under 'function theme\_scs\_node\_output' you can list which fields to use. This was one of the most critical issues to me because my client wanted the information to display in a specific way.

Finally, just a quick reminder: theming for email newsletters should be done in table layout for best results, and all styles should be inline.

If anyone has a more complete or accurate answer, I'm happy to select theirs instead.
> 1 votes

---
Tags: theming, 6, emails
---


# Question
Title: What is right way to modify a node field in a multilanguage system (LANGUAGE_NONE or $node->language or ...)
Let's say we want to modify the body field.

```
$node->body[LANGUAGE_NONE][0]['value'] = "test";

```

This will work if the node is language neutral (?)

```
$node->body[$node->language][0]['value'] = "test";

```

This will work if the node has the same langauge as the field.

But is this always the case? I found nodes where this is not the case:

```
(Object) stdClass
...
language (String, 2 characters ) **de**
...
body (Array, 1 element)
  **und** (Array, 1 element)
        0 (Array, 5 elements)
            value (String, 4 characters ) test

```

So if this is a correct node, how can we access the body field value?

# Answer
> 6 votes
field\_language() returns the field's display language. You should use code similar to the following one:

```
$language = field_language('node', $node, 'body');
do_something_with($node->body[$language][0]);

```

Of course, note that `field_language()` will determine the right display language ('en' or LANGUAGE\_NONE or whatever); if you're modifying fields you might want to modify more than one language.

# Answer
> 5 votes
What's about getting the field value with `field_get_items()`? Really prefer this solution ...

```
if ($body = field_get_items('node', $node, 'body')) {
  $my_rendered_content = strip_tags(drupal_render(field_view_value('node', $node, 'body', $body[0])));
}

```

---
Tags: 7, nodes, entities, i18n-l10n
---


# Question
Title: Is access control necessary upon form submission if I've controlled access to the page containing the form?
Let's say a malicious user has no access to some path (e.g. path/element/1) based on 'access callback' as set in `hook_menu()` or altered in `hook_menu_alter()`. What happens if he has access to path/element/2?

Could he simply not change the values that are POSTed in the form submission to the server? I thought they can (even though there are form tokens). If I do several access checks to determine who can view a page, and that page contains a form that can be submitted by anyone who has access to that page, do I need to do those same access checks in the #submit or #validate handler or anything like that? Or can I rely on Drupal's form API security to keep me from having to tediously duplicate all that access code twice for pretty much every custom form!

I know Drupal has some form tokens and whatnot, but doesn't this depend on the developer who output that form (assume a contrib or custom module) setting things up right? I remember a while back I created a custom form and tried changing the POSTed values of one of the elements, and the altered value is what got picked up by Drupal! There was no rejection of the form based on altered values! So clearly I did something wrong there (what might it have been?) - and if I did, then a developer of a contrib module could do the same. So what's the best practice here?

# Answer
It is not necessary to control if the user has access to a form in its submission handler.

Drupal protects its forms from form forgery, and verifies the values contained in the submitted form. The first control is done in drupal\_validate\_form(), where the form token (which is automatically assigned to every form built through the form API) is verified; if the value of `$form_state['values']['form_token']` is different from the value of `drupal_hmac_base64($form['#token'], session_id() . drupal_get_private_key() . drupal_get_hash_salt())`, the form is rejected. The submitted values are also validated in \_form\_validate(), where the length of the entered value is checked against the maximum length reported for the form field, and the value entered for a "checkboxes," or a "tableselect" form field is checked against its acceptable values. In both the cases, the value used to verify the submitted values is not taken from the submitted values.

To be more sure, you should not pass sensible data, such as the ID of the node being edited as hidden field; it is preferable to set it inside the `$form` variable, using an array index that starts with "#" and that is unique for that form (such as "#nid"), or use a "value" form field; in that way, the value will not be passed to the HTML form rendered in the browser, and a forged form would not be able to alter that value to effectuate an operation on an entity for which the user doesn't have access. For example, this is the code used for a confirmation form that allows to delete a node:

```
function node_delete_confirm($form, &$form_state, $node) {
  $form['#node'] = $node;
  // Always provide entity id in the same form key as in the entity edit form.
  $form['nid'] = array(
    '#type' => 'value',
    '#value' => $node->nid,
  );
  return confirm_form($form,
    t('Are you sure you want to delete %title?', array('%title' => $node->title)),
    'node/' . $node->nid,
    t('This action cannot be undone.'),
    t('Delete'),
    t('Cancel')
  );
}

```

Both `$form['#node']` and `$form['nid']` are not contained in the form passed to the browser.

The submission handler for that form builder is the following one:

```
function node_delete_confirm_submit($form, &$form_state) {
  if ($form_state['values']['confirm']) {
    $node = node_load($form_state['values']['nid']);
    node_delete($form_state['values']['nid']);
    watchdog('content', '@type: deleted %title.', array('@type' => $node->type, '%title' => $node->title));
    drupal_set_message(t('@type %title has been deleted.', array('@type' => node_type_get_name($node), '%title' => $node->title)));
  }

  $form_state['redirect'] = '<front>';
}

```

The value of `$form` passed to the form handlers is not passed to the browser, but it is retrieved in the Drupal cache from drupal\_build\_form(), which calls form\_get\_cache() when the form has been submitted. The documentation of `drupal_build_form()` contains the following sentence:

> The form may also be retrieved from the cache if the form was built in a previous page-load. The form is then passed on for processing, validation and submission if there is proper input.

If you look at Drupal code, you will notice that none of the core modules check if the user has the permission of accessing the form in the form submission; the only code you will find is the code that checks if an error message must be output, in the case that error message should be visible to a group of users that is smaller than the group of users that has access to the form.

As side note, Drupal.org has a security team that investigates on security issues reported for Drupal core code, and any third-party modules hosted on Drupal.org; for third-party modules, they don't investigate on reports for non official releases of the modules (e.g. alpha, beta, and development snapshots). If you find a security issue in Drupal, you should report it in the project queue for Drupal core.
> 1 votes

# Answer
The user has total control of what he sends to your server; always. That's the nature of client-server computing.

It is the responsibility of the access callback, to determine if the user has access to the URL. The access callback does usually not look at the posted values for this, although such an access callback could be implemented.

It is the responsibility of the validation and submit handlers to not update entities that the user is not allowed to update if that is so desired. This can be achieved in two ways, depending on where the entity that is to be updated comes from.

1. The entity can be determined from the drupal path and passed to the submit handler from the menu system. In this case the submit handler should not update the primary key.
2. The entity can be determined by the form values. In this case the submit handler must determine whether the user is allowed to update the entity.
> 0 votes

---
Tags: forms, security
---


# Question
Title: How to remove a menu path defined in hook_menu from naviagtion
I've added two paths for use my my module (for OAuth authentication), but I don't want them to appear as links in menus. I tried defining their 'type' as `MENU_CALLBACK` but they still appear.

Is there a better way to define paths which aren't necessarily pages.

# Answer
> 0 votes
Don't add `type` to the array in `hook_menu`, it will not be displayed as a menu, but still will be accessible (by code)

```
$items['menu/%/link1'] = array(
   'title' => 'Link1',
// 'type' => MENU_LOCAL_TASK,
   'page callback' => 'link1()',
   'page arguments' => array(1),
   'access callback' => TRUE, //'has_access',
);

```

---
Tags: routes
---


# Question
Title: How to make the Edit User Profile to have all tabs in one page?
If I load this page http://domain.com/user/1/edit

I have on top more tabs that I have to unify into one page

I've added some custom fields to the user profile that adds some more tabs when I go into

http://domain.com/admin/user/profile

so that adds the tabs that I need to appear in the same page as http://domain.com/user/1/edit

how can I do that?

note that I'm using Drupal 6.19

# Answer
> 0 votes
The One page profile module should do this if you're using the core Profile module.

---
Tags: users, routes
---


# Question
Title: How to create a log in and register link in the secondary menu
I am trying to configure my login block on the front page such as that it appears on a separate page. I want the links to this page (that is, login and register) to appear in the secondary menu. I am using Zen with Drupal 7.

# Answer
Create a new entry in the secondary menu and point it to `/user` or `/?q=user`.
> 1 votes

---
Tags: users
---


# Question
Title: Block page is not affecting with custom theme
i am using custome module in my moduleThe code is as follows.

```
function mymodule_init() {
    global $custom_theme;
    $custom_theme = 'bluemarine';
    init_theme();
}

```

And this works fine for all other pages except the block page(admin/build/block). The block page takes the default theme only. I want the custome theme assigned from mymodule to the block page. How can i do this?

# Answer
> 2 votes
There's a module for that: ThemeKey

> ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules.

---
Tags: 7, hooks
---


# Question
Title: Drupal views override stopped working for no reason
I have a normal website, where I override the views templates for one view. When I go into the views UI, and check Other-\>Theme , it clearly indicates it is using the custom templates. But when I check the website, the templates are not used.

I think this happened when activating cache. (Yes, I cleared it already, and many times).

I saw that suddenly, altough the theme still worked, it got deactivated. So I reactivated it, but still the views templates are not used in frontend.

Can anyone please shed a light on this?

It is only one template file that doesn't work anymore.

# Answer
> 2 votes
I have not experienced this, but have a theory. The default views that come with the module can be restored to their original condition so your problem may relate to the "special' nature of these views. Try cloning the view and making your modifications to the clone.

---
Tags: views, theming
---


# Question
Title: How do I hide the AJAX Cart block when cart is empty?
How can I **hide Ubercart AJAX Cart block when the user's shopping cart is empty**?

I know I could hide it with some jQuery tricks (for example, looking for the "cart-empty" class under my AJAX cart block (which has the class "block-uc\_ajax\_cart"), and hide the whole block if I found it), but this way I also would have to solve if cart is updated... Too messy.

I haven't found any opportunities to hide the block in this case under block settings, nor under the AJAX Cart Settings (`http://<mysite>/admin/store/settings/uc_ajax_cart`).

Thanks for your help in advance!

# Answer
> 0 votes
OK, in the meantime I found the solution.

1.) Set **"Block title"** in the appropriate block configuration to **`<none>`**. (`http://<mysite>/admin/build/block/configure/uc_ajax_cart/0`) (you'll see later why)

Block title:
`<none>`

2.) **Copy the UC AJAX Cart template files** (`uc_ajax_cart_block_content.tpl.php`, `uc_ajax_cart_block_content_empty.tpl.php`) from `http://<mysite>/sites/all/modules/uc_ajax_cart/templates/`
to your own theme's `templates` directory (`http://<mysite>//sites/all/themes/<mytheme>/templates/`).

3.) After that, **open both copied files** (which are now in your template directory) **in a text editor**.

4.) **Delete** (or put in a comment) the content of `uc_ajax_cart_block_content_empty.tpl.php`, and upload the edited file to the server.

5.) **Prepend** the following to `uc_ajax_cart_block_content.tpl.php` to have the block title back:

```
<h2 class="title">
    <span class="title block-title" id="ajax-cart-headline">
        <a href="#" id="ajaxCartToggleView" class="ajax-cart-processed"><?php print t('Shopping cart')?></a>
    </span>
</h2>

```

(The rest should stay intact!!)

6.) **Clear the theme registry cache** (`http://<mysite>/admin_menu/flush-cache/theme`), and you're done.

---

UPDATE:
the method above breaks the toggling opportunity of the shopping cart content (if the following is checked in the settings: *"Make the shopping cart block collapsible by clicking the name or arrow."*) when clicking on the block title (*"Shopping Cart"*), because the title part is also updated with AJAX from the `uc_ajax_cart_block_content.tpl.php` file, BUT there IS a solution in jQuery, which you have to put in your own JavaScript-file (which is e.g. put in your theme's .info file), and it looks like this:

```
$(document).ready( function(){
    if( $('#ajaxCartToggleView').length > 0 ){
        // live: "Attach an event handler for all elements which match the current selector, now and in the future." (http://api.jquery.com/live/)
        $("#ajaxCartToggleView").live("click", function(){
            ajaxCartToggleView();
            return false;
        });
    }
}

```

---
Tags: 6, blocks, ajax, ubercart
---


title: Custom content translation links

text:
# Question
Title: Custom content translation links
I have a multilingual Drupal site in english & french. At the bottom of every page is the content translation link, however I want to place this in a custom location on page.tpl.php. So if I hide the content translation links in the configuration, how do I call it via a function on the page template?

# Answer
> 0 votes
This worked for me. Incase there was no translation node, I send the user to the homepage.

```
$tpath = translation_path_get_translations($_GET['q']);
if ($language->language == 'en') {
    if (array_key_exists('fr', $tpath)) {
        $tlink = "<a href='/fr/" . drupal_lookup_path('alias', $tpath['fr'], 'fr') . "'>Français</a>";
    } else {
        $tlink = "<a href='/fr/'>Français</a>";
    }
} else {
    if (array_key_exists('en', $tpath)) {
        $tlink = "<a href='/" . drupal_lookup_path('alias', $tpath['en'], 'en') . "'>English</a>";
    } else {
        $tlink = "<a href='/'>English</a>";
    }
}

print $tlink;

```

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


# Question
Title: Allow a role to edit a specific taxonomy list of terms
We have a blog that needs to be categorized by topics. I want to allow a blog administrator to add/edit/delete blog topics that are listed in a taxonomy vocabulary. But I don't want to give him add/edit/delete access to other taxonomy lists. Is there a permission that I am missing? Is there a D7 module that handles this? Or can someone point me in the right direction for writing my old module?

# Answer
> 2 votes
Taxonomy Access Control provides this functionality. Workbench does as well, though it is slightly more complex and from my limited experience performs better when only a single term is used per node to control access. Workbench (access + moderation) includes a nice set of tools for content moderation and workflow not found in Taxonomy Access Control. Both are worth a look before you decide for your use case.

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


# Question
Title: Disable the overlay for admin using a feature?
Every time i spawn a new website the first thing i need to do is disable the very slow overlay in /user/1/edit?destination=admin/people

Is there a way to export admin user settings each time after an install?

# Answer
> 1 votes
You can use a feature for this, but IMO it makes more sense to do this in an install profile, because you are just setting this once. One way or the other, you will need to add some code to the .install file of your install profile or feature, in the form of a hook\_install implementation.

This is untested code but I believe it should work:

```
<?php
/**
 * Implement hook_install().
 */
function PROFILENAME_install() {
  user_save(user_load(1), array('data' => array('overlay' => 0)));
}
?>

```

Of course you need to replace 'PROFILENAME' with the name of your install profile or the name of your feature.

---
Tags: users, importing-exporting
---


# Question
Title: How do you change the title of a field collection edit form?
Here is an example edit URL for a field collection I have field-photo-block:

> /field-collection/field-photo-block/65/edit

The title of this page is being set to the title of the field collection. How do I change it to something descriptive?

# Answer
> 3 votes
In a custom module (or even theme), you can add this function. Replace `YOURMODULE` with the name of your module or theme.

```
<?php
function YOURMODULE_form_field_collection_item_form_alter(&$form, &$form_state, $form_id) {
  drupal_set_title(t('Your title'));
}

```

---
Tags: 7, theming, hooks
---


# Question
Title: How do you create a variable from hook_preprocess_page() that will be available to a node template?
I have this in my module "spot":

```
function spot_preprocess_page(&$vars) {
  $vars['social'] = 'hi';
}

```

Other things I set in this function come through fine. But my node--spot.tpl.php template is complaining that the variable does not exist:

> Notice: Undefined variable: social

I have cleared the cache.

What am I doing wrong?

# Answer
> 3 votes
> How do you create a variable from hook\_preprocess\_page() that will be available to a node template?

You cannot.
The parameter passed to `hook_preprocess_page()` (what you define as `&$vars`) is not the same parameter passed to `hook_preprocess_node()`, which means that if you set `$vars['social']` in the first, it is not passed to the latter. If you need to pass a value to the node template file, you need to set it in `hook_preprocess_node()`, or `hook_process_node()`.

# Answer
> 1 votes
That hook is for page.tpl.php. Put your code in a `hook_preprocess_node()`.

---
Tags: 7, hooks, theming
---


# Question
Title: Creating a token for the image field file path with node reference nid
Since there is not support for fields in Drupal 7 tokens, how do I create the code to replace a token in an image field file path?

**EDIT**: First, this is with the Node Reference URL widget so the NID of the referenced node is loaded into the form array as long as the link was clicked on the referenced node.

I realize that there isn't any context to load the information to pass to the token module because there isn't any information about the node by the time token\_replace() is called. This is before the NID of the referenced node is added to the form.

Adding the file path by using `hook_form_FORM_ID_form_alter()` works, but it's not very safe. The user might not use the Node Reference URL widget to access the page in which case the node is saved with a reference while the image path didn't have access at any point for know about the NID of the referenced node. And, if the node is then edited it will change the path on creation as it will then know about the referenced node making a mess of the place.

Here is the simple code which isn't very safe. I wouldn't mind a better solution.

**Update:**

It turns out that the node reference URL widget can be set to return a page not found if the referenced node's URL is not in the URL, which would make this function a little safer as it forces the user to only be able to create the node if they clicked the create node link on the referenced page.

```
/**
*  Implements hook_form_FORM_ID_form_alter\
*/
function HOOK_form_photo_node_form_alter(&$form, &$form_state) {
  $lang = $form['language']['#value'];
  $form['field_business_photo'][$lang][0]['#upload_location'] = 'public://photo/' . $form['field_reference_business'][$lang][0]['nid']['#default_value'];
}

```

# Answer
> 1 votes
The answer is using the Fieldfield Paths module.

> The FileField Paths module extends the default functionality of Drupals core Upload module, the FileField module and many other File Upload modules by adding the ability to use **node** tokens in destination paths and filenames.

---
Tags: 7, nodes, tokens
---


# Question
Title: How can I access language currently viewed in Views Customfield: PHP Code?
I'm looking for a way to display some text in a view—information about who posted an article, and a link to read more—in a specific language based on which language for the site the user has selected.

I thought I'd do this with a "Customfield: PHP Code" to make an if statement echoing a string depending on the language.

How do I access this variable, or how do I solve the problem in another way?

# Answer
> 1 votes
The standard way to display text strings in Drupal is using the t() function. You should enter your text in English and it will be translated to the corresponding string in the current user's language.

If you still want to know the current user's language, you can load the user like this:

```
$user = user_load(uid);

```

and the language will be available on

```
$user->language

```

---
Tags: views, 6
---


# Question
Title: advantages of drush bam vs. drush sql-dump / drush sql-connect
Is there any comparative advantage in terms of best practice, ease of use, or speed in terms of using the drush back up and migrate command (`drush bam`) or is it just preference?

I'm often using just a simple `drush sql-dump > exportdb.sql` and a `$(drush sql-connect) < importdb.sql` to backup a database. I find it pretty easy to use.

# Answer
> 12 votes
There aren't giant differences between the two approaches. Here are a few small differences:

drush sql-dump uses mysqldump program in the background and so is must faster than the pure PHP approach taken by BAM.

You can easily skip tables with sql-dump as well. See the help for this command.

Finally, some folks might want to use sql-sync which does all of these steps in one command. It works faster than sql-dump+sql\_connect when one of the machines is remote. It also includes optional data sanitization.

# Answer
> 3 votes
I think the biggest advantages of bam-backup is that you can choose a profile. With this you can do a bunch of different things. The most useful is the ability to exclude the rows from the cache and watchdog tables. I also think (though I have never confirmed it), that taking a backup this way will use maintenance mode just like via the UI, if you have it configured. This can result in better backups if you have active traffic.

When I am doing normal backups as safeties, I just use bam-backup. When I am doing a neuritic backup, or sending a db to a client for deployment, I also take a full backup with MySQL Administrator, which will properly lock tables.

---
Tags: drush, backups
---


# Question
Title: How can I implement 3-way relationship (reference) between entities?
I have 3 entities: A,B — node types, C — user. Node A has 2 reference fields, one to B and one to C. What I need is to show in a view all B nodes for a certain C, which has a relation A-B=A-C

# Answer
The Relation module should be ideal for that. It allows you to create a single relation entity that links 3 (or more) entities together. It's in beta and you may have to do some work to get the user interface you need (I say that based on the Relation session at DrupalCon London), but it's flexibility is superior to any other relation/reference module out there.
> 1 votes

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


# Question
Title: Module Dev: How to attach a button to a field?
I would like to build a module whereby a user can enable a button per field, and when the user clicks on it, it gets the field contents and posts it to a service.

If there are any modules like this that would be great as well as an example.

# Answer
This example comes close: Publishing to Facebook Wall. It shows how to post a facebook message when a node or comment form is submitted, and provide an option to opt-out on the node or comment form.
> 1 votes

---
Tags: 7, entities
---


# Question
Title: Alter a Views query to use "OR" through the user interface
I have a view with a few different displays, each of them with slightly overridden filters, like this one used in a panel.

How do you add this pseudocode via the UI?

```
AND (node.type='story' OR node.comment_count >=1)

```

I found an article (Better WHERE's for your Drupal forums with hook\_views\_query\_alter), but I still don't know what to do.

What does the following code do, and what is "advf\_filter"?

```
if ($view->name == 'YOURVIEW') {
  $view->query->add_where('advf_filter',"(node.type='%s' OR node_comment_statistics.comment_count >= %d)",'forum',1);
  $view->query->set_group_operator('AND');
}

```

# Answer
> 6 votes
In Drupal 7 (Views 3), it's pretty simple, for regular filters at least:

* For regular **Filters**, open the 'rearrange' (or "and/or, rearrange") window by clicking on the arrow next to 'Add'. From here it's simple and self-explanatory - you put your filters into Filter Groups, and can set each filter group to be 'OR' or 'AND'.
* For **Contextual Filters**, it's a little bit stranger and is currently undergoing development work. Keep an eye on this issue: Document that contextual filters are included in the first 'and/or' filter group . As the title of that link suggests, all your contextual filters are treated as being part of whatever your first Filter Group is, so make sure there is at least one, and edit that as above.

There's talk in that issue of changing this to something more flexible (watch above link), but that'll take time.

(note - talking about contextual filters is relevant to this question because someone closed a question about setting 'OR' on contextual filters as a duplicate and pointed it to this one)

-----UPDATE-----------

That issue closed with just a documentation change, here's a couple of relevant ongoing issues to follow...

# Answer
> 2 votes
Even though it's a dev version, I have never had problems with the Views OR module.

---
Tags: 7, views
---


title: best reference to theming

text:
# Question
Title: best reference to theming
I'm completely new to drupal and am starting to take interest in the process of theming. I was wondering if anyone could suggest a reference or perhaps even just insert a snippet of code explaining the basic template.

I have some PHP experience but nothing too complex. I'd really like to learn how to apply javascript into my themes and what the best approaches would in terms of that. I attempted the other day to insert some HTML via the regular "create content" section and then wrote a stylesheet to correspond to said HTML, I linked via the template.info file, but it didn't work because Drupal had renamed all of my div's. Is that normal?

Sorry if my question seems to be too broad in scope, I guess I just need a direction or map and I'd be fine. Thanks in advance, and looking forward to becoming a contributing member of this community.

# Answer
> 1 votes
I recommend the theming chapter by @jacine in Definitive Guide to Drupal 7 - http://definitivedrupal.org/. Not free but well worth it.

---
Tags: theming, nodes
---


# Question
Title: How to comment out code in a .tpl.php template
If I want to remove parts of .tpl.php file what are my options other than removing them permanently? HTML comments \< !-- --\> work but print the part in the HTML source. PHP // comments or /\* \*/ don't work.

For example, how could I comment out a block like:

```
    <?php if ($logo): ?>
      <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo">
      <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />
      </a>
    <?php endif; ?>

```

# Answer
I actually prefer to use this way

```
<?php if (FALSE): ?>
<div class="meta">
  <?php if ($submitted): ?>
    <span class="submitted"><?php print $submitted ?></span>
  <?php endif; ?>

  <?php if ($terms): ?>
    <span class="terms"><?php print $terms ?></span>
  <?php endif;?>
</div>
<?php endif; ?>

```

This make it easier to put the block back in (change FALSE to TRUE), or attach a variable to the conditional.

EDIT:

To address your example, I would do it one of two ways

```
<?php if (FALSE): ?>
<?php if ($logo): ?>
  <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo">
  <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />
  </a>
<?php endif; ?>
<?php endif; ?>

```

or

```
<?php if (FALSE && $logo): ?>
  <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo">
  <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />
  </a>
<?php endif; ?>

```

I would normally lean towards using the second in my daily work.
> 5 votes

---
Tags: 7, theming
---


title: Author handling node view access?

text:
# Question
Title: Author handling node view access?
First post here! ;) I'm not getting any help from the Drupal forums on this, maybe someone can help me out...Does anyone know of a module that I can use so that an Author can allow access to a user requesting access to the Author's node. The setup would be like this: 1. An Author would create a private node, but viewable in teaser form. 2. Any Authenticated user could then request access to the node/full view. 3. The Author would then have a queue, say in their own user environment, where he/she could approve or deny access to the node/full view for the requesting user. Thank you very much!

# Answer
I was thinking about building a simple access system, but that would be like re-inventing the wheel.

Take a look at content\_access in combination with ACL. The flexiaccess might be another option.
> 0 votes

---
Tags: views, users
---


# Question
Title: having problem with db_or() and LIKE clause in drupal 7
I am trying to retrieve data from db with INNER JOIN.

I need the following query executed from drupal's `db_select()`, query is in normal format :

```
SELECT uo.* , uop.data FROM `uc_orders` AS uo
INNER JOIN `uc_order_products` AS uop ON uo.order_id = uop.order_id
WHERE (
  (
     uop.data LIKE '%mfp_donation%'
  )
  OR (
     uop.data LIKE '%scholar_donation%'
  )
  OR (
     uop.data LIKE '%reunion%'
  )
)

```

I already tried in drupal, the process is following :

```
$query = db_select('uc_orders', 'uo')
    ->fields('uo')
    ->fields('uop', array('data'));

$alias = $query->join('uc_order_products', 'uop', "uo.order_id = uop.order_id");

$order = $query->condition(db_or()
       ->condition($alias . '.data', '%mfp_donaiton%', 'LIKE')
       ->condition($alias . '.data', '%scholar_donaiton%', 'LIKE')
       ->condition($alias . '.data', '%reunion%', 'LIKE')
    )
    ->execute()
    ->fetchObject();

```

All the process is working fine, but the problem is when i execute/fetch the results then i only get the output for `->condition($alias . '.data', '%reunion%', 'LIKE')` . I mean i only get the `%reunion%` part. The first two conditions is not executing i think.

Any suggestion?

# Answer
> 2 votes
You can use `dpq()` to inspect your query.
Your query looks good, but I suspect that there's a small error in your condition. You put `donaiton`, shouldn't it be `donation` ?

---
Tags: database
---


# Question
Title: How can I programmatically disable the "Preview" button in a content type?
I have a content-type that has been created via hook\_install. I want to set the "Preview" option to disabled. Currently it defaults to "optional". How can I change this in hook\_install when I create the content type?

# Answer
> 9 votes
For programming disabling use special variable:

```
variable_set('node_preview_' . $content_type, '0');

```

For default node options "Published" (`status`), "Promoted" (`promote`), "Sticky" (`sticky`) and "New revision" (`revision`) use variable `"node_options_" . $content_type`, which takes array as a value.
Example can be found in standard installation profile:

```
// Default "Basic page" to not be promoted and have comments disabled.
variable_set('node_options_page', array('status'));

```

# Answer
> 5 votes
If you want more control over when the preview button is disabled you can use hook\_form\_alter() and then `unset($form['actions']['preview']);`

Should give you the ability to enable and disable on the fly instead of setting globally.

# Answer
> 2 votes
Go to the Content Type in the Administration bar and click Edit on the content type you want to adjust. Then at the bottom under Submission Settings change "Preview before Submitting" to disabled.

---
Tags: 7
---


# Question
Title: Does the SimpleTest method drupalGetMails() prevent actual emails from being sent?
During a SimpleTest, does the data intercepted by drupalGetMails() continue to your systems mail transport agent or is the actual send suppressed?

# Answer
That is only the getter.

```
// Use the test mail class instead of the default mail handler class.
variable_set('mail_system', array('default-system' => 'TestingMailSystem'));

```

in `DrupalWebTestCase::setUp` stops mails being sent. `TestingMailSystem` does nothing else but collect emails in the `drupal_test_email_collector` variable.
> 4 votes

---
Tags: testing
---


# Question
Title: How to creat graphs/plots in Drupal, using python library matplotlib, updated in real time if possible?
I would like to display plots and graphs in Drupal nodes.

Can somebody point out a good workflow to get this done?

Ideally, I would like to use the graphical python library **matplotlib**. But a solution that is more Drupalish would be fine too.

Ideally, I would like to enter numeric values in an interface, and see a graph updated in **real time**. I have not been able to discover any module(s) for this.

Jakob

# Answer
I don't think there is an out-of-the-box solution for this. You probably already found the Charts module, but that does not seem to support on the fly updates.

So you would need to create your own module. You could then send your data with an ajax call and redraw the graph using that data (the form api in Drupal 7 has excellent support for this; create a fieldset with its own div in which you put the graph). I'm working with Highcharts (which I really like) in my own modules and do something similar.
> 1 votes

---
Tags: views, charts
---


title: Bug/Issue tracker for Drupal 7?

text:
# Question
Title: Bug/Issue tracker for Drupal 7?
I would really like to port my website to Drupal 7, but my site requires an issue tracker. I tried the support module, but it seems heavily orientated towards support tickets (you must add clients, all users can't view eachothers tickets).

With the project issues module still working on complete Drupal 6 support, I really don't think I should be holding my breath.

What options are there, If I want a bug tracker on Drupal 7?

# Answer
**Solution 1: Do It Yourself**

Add taxonomy terms

1. **Status** (Open, In Progress, Pending, Resolved, Closed) ,
2. **Priority** (Low, Normal, High)

Create content type ***Issue***,

* add fields title, body, status, priority.

Set roles

* Allow anonymous users to create content Issue
* Allow administrators to edit and delete content Issue

Extras:

Use Views for issue reporting

Use Workbench for managing issues

Use Workflow for setting issue management workflow

**Solution 2: Use an external issue management solution**

Comparison of issue-tracking systems

I prefer an external solution because of its independency I can still handle issues even if my site is down.
> 1 votes

# Answer
Project for D7 is http://3281d.com/2011/10/26/report-from-project-7-sprint coming. It's going to be a while so holding your breath is not advised... but it's coming.
> 0 votes

---
Tags: 7
---


# Question
Title: How can I theme "Error generating image." error 500's in Drupal 7?
I wish to theme the error pages generated by the image module in drupal 7, I'm not sure it can be done as this is the code that runs when imagecache fails to generate a style:

```
else {
    watchdog('image', 'Unable to generate the derived image located at %path.', array('%path' => $derivative_uri));
    drupal_add_http_header('Status', '500 Internal Server Error');
    print t('Error generating image.');
    drupal_exit();
}

```

I'm not intending on having a whole themed page, but something that isn't quite as ghastly as white screen with just "Error generating image." on it. Rather at least some way for a visiting to navigate away from it and remain on the site if they wish. It would be even better if I could return a 404 instead.

This is of course, without hacking core. So anyone have any ideas or have I missed something?

# Answer
> 3 votes
You can't.

This is hardcoded in http://api.drupal.org/api/drupal/modules--image--image.module/function/image\_style\_deliver/7.

You would need to completely override this page callback to change what it does. You could do this with hook\_menu\_alter() but that means that you would need to make sure that you also apply any upstream changes to that function to your own copy.

Can't you just leave the images there instead of deleting them? And if they are just a temporary resource, maybe exclude them from search with robots.txt?

---
Tags: 7, theming, media
---


# Question
Title: URL encoding in admin overlays - breaks overlay
I have a fresh install of Drupal 7 with no content, and a few extra modules installed. Recently as I've navigated on the admin side, the URLs for the overlays have escaped HTML in them, like this:

```
http://mywebsite.com/#overlay=%3Fq%3Dadmin/config

```

Which of course is supposed to mean

```
http://mywebsite.com/#overlay=?q=admin/config

```

But still, the overlay doesn't show up properly.

I've found a few reports of this, but no fixes, other than to disable overlays. Can anyone offer anything?

What's tricky about this is that I can't get to administrative features *because the overlays can't show up*.

# Answer
I'm reasonably sure that the Overlay module doesn't work without clean URLs.

If `http://mywebsite.com/#overlay=admin/config` doesn't work, make sure that clean URLs are working properly.
> 0 votes

# Answer
Apparently this error is not related to **URL encoding**, but the lack of overlay module support when mod\_rewrite is not properly configured in the Apache web server.

See http://drupal.org/node/1337420#comment-5238454.
> 2 votes

---
Tags: 7, modal-dialogs, debugging
---


# Question
Title: How can I support product prices which have a precision greater than the currency's minor unit in Drupal Commerce?
Any idea how to support prices which have more decimal places than a currency supports in Drupal Commerce?

Use case is that I'm trying to build a website which has some very small parts, whose unit price can have factions of cents ie a small bearing which has a unit price of $0.05742.

Typical users would order 1000s at a time and price is rounded to nearest cent at payment time.

But a commerce\_price (in USD) only supports 'whole' cents (to reflect the minor unit format). Entering 0.05472 in the price field causes rounding to 0.05 and this rounded value is also the value written out to the db.

Any suggestions?

Thanks

# Answer
Commerce allows to define the amount of decimals per currency in hook\_commerce\_currency\_info, defaulting to 2. So you could implement hook\_commerce\_currency\_info\_alter and change that for USD.

However, due to the way prices are stored (with decimals set to 2, $5.00 is stored as 500), this will affect all existing prices, so when you change it e.g to 4 decimals, then $5.00 will now just be $0.05.

So, maybe you could instead set up a virtual currency with the same name and as many decimals as you want and then let Commerce automatically handle the conversion to USD during payment.
> 2 votes

---
Tags: entities, commerce
---


# Question
Title: How to use URL-based AJAX in Drupal 7 to serve all pages?
I know this can be done through jQuery alone, but I'm interested in knowing if there any Drupal 7 ways of achieving this:

I want to use AJAX to serve all non-admin pages on my site. Also I don't want it to just replace parts of a page, but load entire pages over AJAX. The AJAX Framework allows loading partial contents over AJAX based on various triggers. But I want to make a URL based navigation system.

Here are the things I want to accomplish:

* Redirect http://example.com/node/1 to http://example.com/#!/node/1. So search engines can index the node normally.
* Drupal reads the string from URL (node/1) and fetches the relevant string in json format.
* Insert the resulting data into page and replace existing content.
* Refreshes blocks that should appear on the corresponding page.
* Refreshes title in browser (optional).
* Needs to work with Panels.

If I create a new module, what functions and/or frameworks in Drupal can I use to make this work?

Thanks.

-Kaustav

# Answer
> 1 votes
I'm searching also a solution to do that. I would like to allow users to choose witch content type is displaying in a region.

I started by create one block by region and inside I put different functions like the following one to get different content.

```
node_view_multiple(array($node->nid => $node), $display_type); // To get a node.
module_invoke($module, 'block_view',$delta); // To get a block.
panels_mini_block_view($minipanel_name); // To get a mini panel.

```

Now, with the CSS ID of the block, I will try to refresh them using AJAX link. I think I will have to override all the links of Drupal to somethings like main/nojs/#div\_region\_id/\[drupal-url\] (e.g. main/nojs/block-content/node/1) and add them a `class="use-ajax"`.

The management what is refresh will be in `ajax_callback_response()`.

```
$commands[] = ajax_command_html('#block-content', $output );
$page = array('#type' => 'ajax', '#commands' => $commands);
ajax_deliver($page);

```

Another way may be also with the Content page module.

---
Tags: 7, ajax, javascript, uri
---


# Question
Title: Module that will display certain facebook content?
I realize there are quite a bit of facebook possibilities main having to do with facebook account connections. What I'm interested though, is content (especially videos!) that is being put up in a facebook group that was created and having that display on the drupal site. Is there a module out there that does that?

# Answer
> 0 votes
Facebook API requires you to "make an application" so it can assign you an API key you can use to connect things, like a drupal module, to your Facebook account. That is how it knows what content to pull from the Wall and let you manipulate it.

You might want to check out Drupal for Facebook Module as it has a lot of facebook functionality you might be looking for.

# Answer
> 0 votes
I think that you can use this jquery plugin http://www.neosmart.de/social-media/facebook-wall to put an specific wall inside a block or node, and then you can improve the javascript code (I guess in *Parse feed data / wall* section of `jquery.neosmart.fb.wall.js` file) to show only items with specific content, in this case, for example, a content using `uiVideoThumb` class (according my review `uiVideoThumb` is one class used to thumbns that link to videos).

specifically, in the js, in the section *Parse feed data / wall* line 81:

```
for(var k=0;k<max;k++){

```

you can add some lines to detect the specific content, for example:

```
var pattern=/uiVideoThumb/g;
var stringContent = JSON.stringify(data[k]);
if(stringContent.match(pattern)){

```

do not forget close this new `IF` declaration (near line 162).

Acording my test, only content with these condition is displayed.

one note: seems that the code has a Drupal´s module version http://drupal.org/project/fb\_walls but not was clear to me how this module works over Drupal.

---
Tags: 6, social-network
---


# Question
Title: Custom arrangement for fields with multiple values in Drupal 7
In Drupal 6 I used to make every sort of customised markup for CCK fields with multiple values. Usually this happened when I wanted to lay out thumnails for a gallery inside a table: I used to go into the relevant tpl.php file, grab the relevant $field\_fieldname variable, loop through it, and print out the 'view' key for it, which contained the styled thumbnail, often linked to the original image and whatever.

Now, I'm a bit confused on how this should be done in Drupal 7. For now, I set up a suboptimal solution that goes like

```
<section class="gallery">
    <div class="row first">
    <?php foreach($content['field_gallery'] as $k => $v) : ?>
        <?php if(is_numeric($k)) : ?>
            <?php echo render($v) ?>
            <?php if((($k+1) % 4) == 0) : ?>
    </div><div class="row">
            <?php endif ?>
        <?php endif ?>
    <?php endforeach ?>
    </div>
</section>

```

but it's obviously wrong. I can't seem to get my head around this, even after having read lots of docs about the Field API and theming for D7. Ideas?

# Answer
You've got an explanation on how field\_view\_field and rendering api for fields work in this blog.

Here you've got an example (extracted from the link above):

```
$node = node_load($nid);
$field = field_get_items('node', $node, 'field_name');
$output = field_view_value('node', $node, 'field_name', $field[$delta]);

```

You just need to loop over the $delta value for the fields to render them in a multiple valued field.
> 2 votes

---
Tags: 7, entities
---


# Question
Title: How do I show an image in a Drupal 7 module?
I'm creating a module and need to add some images to the admin part of it. I've created an images folder in my module folder but I'm not sure how to get the exact path to the images to echo them in my module.

# Answer
The following code example presents how to get the full path to an *image-test.jpg* image included in a *simpletest* module.

```
$image = theme('image', array('path' => drupal_get_path('module', 'simpletest') . '/image-test.jpg'));

```
> 2 votes

---
Tags: 7
---


# Question
Title: Hide form fields unless 'add node image (etc) link is clicked
I have content type with many fields. I'd like to simplify the form as best I can and hide un-needed text boxes/checkboxes/options whenever possible. Is there a module you know of which will replace an entire field with an 'add this field' hyperlink. When clicked that field would obviously become visible.

# Answer
> 2 votes
Try the Conditional Fields module. It's still in -dev state for D7 but maybe it works for your case.

# Answer
> 0 votes
I use css to hide fields in my edit forms. You can add some custom css that will "unhide" certain fields when a link is clicked.

The css\_injector module is great to inject css on certain pages.

---
Tags: theming
---


# Question
Title: How do I programmatically create a new content type?
I'm building a module (my\_module) in Drupal 7. It has some functionality and also will create a new content type. In my\_module.install, I implemented `hook_install()` (`my_module_install()`).

Can I use more `hook_install()` to create a new content type (`my_module_install()`) in this module? If the answer is *yes*, how should I do this? Otherwise, should I do this in another module?

# Answer
If I were you, I would consider using the Features module. The module enables exporting a subset of websites structure into a single feature to facilitate re-using this feature elsewhere.

Also, Features module enabled exporting content types/fields easily, you would just tick a certain content type and Voila! The Features module will generate Drupal hooks for you, and also export the code into a module.
> 1 votes

---
Tags: nodes
---


# Question
Title: How do i do some search feature like this
I have a requirement like this show in image

Like left hand side i need to show some fields data and when i click on the links i should filter out the data in content area. and its should be like a AND operation ? I need to use VIEWS and what else modules are needed for this thing to be completed?

# Answer
> 2 votes
This is related to the issue on D7 Faceted Search module here.

Using specialized search systems (**Solr**, Sphinx, Xapian, or others) is the way to go.

You can get results with Solr, the Apache Solr Search Integration module, and customizations.

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


title: Update node from comment form

text:
# Question
Title: Update node from comment form
Is there a way in drupal 7 where you can change a value of a field from the comment form of that node you are commenting on? At the moment I have a comment form within a node which has the same field as that node. When I change that value, it does not update the nodes field but only changes the comment form's field.

Thanks for your help in advance!

# Answer
> 2 votes
I wrote a module to do this, you can probably modify it to suit your needs. http://drupal.org/sandbox/jrowny/1281972 I was using this for 'casetracker' type functionality.

Basically you install this and check for each field "this field is editable by comments."

---
Tags: comments
---


# Question
Title: Trying to enter an argument with multiple words into a Views argument
I'm using Organic Groups with Views in Drupal 7 with OG Tokens to create a view which returns all content with a type associated with it, so groups/foo/article would return all articles where the content type is article and the group is foo. This works fine for a group audience where the audience is one word, such as foo, or two run together without spaces, such as FooBar. However when I create a group like foo-bar, the view returns the no content page even when there is content attached the group. The contextual filter that I am using is OG Group: Label.

I've tried putting PHP to explode the results in the 'WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED', following the posts that I've seen but although I can see it printing out the "foo bar", it is not calling the types attached to the group. Is there somewhere else that I can explode this data and remove the spaces so that the group details can be presented in the view, or even look at the query to see what is being passed into it by the argument?

Thanks for your help and time.

UPDATE: Having run a slightly orthogonal search, i came across the following code:

```
    $handler->argument = str_replace('_', ' ', $argument);
    return TRUE;

```

Having replaced the underscore with a dash, the multi-worded OG audience type can be used as I outlined above. Put the code into the "PHP Validate" code on the specify validation code and apply. The original came from PixelClever . I'll mark as answered when the site allows me to do so as I don't have enough user points to do so immediately.

# Answer
1. If the arguments are not in a taxonomy term then add a vocabulary to contain them
2. Under the contextual filter section for `When the filter value is in the URL` check validation, set it to a Taxonomy term and pick the vocabulary.
3. Select the Filter type or term name from the term ID
4. Check the box for Transform Dashes.

The view should now read the name from the URL and access the term id.
> -1 votes

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