# Question
Title: varnish + multiple webheads = files/(css/*.css|js/*.js) missing
I have this weird issue and I'm not sure if it's me who's doing something wrong or I'm just missing something but maybe some of you can guide me a little bit here...

i setup a varnish server, within varnish itself i created 2 backends and using director i'm able to do round robin to my webheads. That parts seems to be working fine as I'm able to bring one of my webheads down and the other one can serve content to varnish and vice verse.

but here is a kicker... i noticed that sometimes page doesn't load properly so i start looking into why and I noticed some of the files are 304 or 404, so turns out somehow some of files in (files/css/.css or files/js/.js are missing), so I rsync them so now they all appears to have same content in those directories, but when i go to another page it seems like drupal generates more of those and since varnish goes to a round robin for any hit it serves some of page from one webhead and another part from another, so even though css,js file has been generated on first webhead it not generated on second and hence shows 304 or 404.

please advise

# Answer
> 8 votes
This is happening when you have optimization for CSS/JS turned on. These files are generated regarding the context (the page visited by the browser) and so the visitor won't be served some files when the round robin changed the targeted server.

You can configure the round robin to stay on the same server on a per-session basis (see: Pure VCL cookie-based sticky sessions in Varnish 2.1), but generally you should set up a NFS share between your server where you'll put the `sites/default/files` folder.

**Source:** Drupal's optimize CSS and JavaScript setting causing problems in multiple server environments.

# Answer
> 1 votes
The session thing is called "Sticky session", here is the first result when googling for "varnish sticky session": http://monolight.cc/2011/01/pure-vcl-cookie-based-sticky-sessions-in-varnish-2-1/.

However, this doesn't help, if have multiple web servers, you *need* to share the files directory between them. Not just for css/js aggregration, but also uploaded files and so on. NFS is one option, but you need to keep in mind that you introduce a new single point of failure which you need to make redundant again, if you need high availability.

Pantheon, a high performance hosting platform for Drupal, recently published an interesting article on how they invented a completely new file system to share the files directory between multiple web servers where they also outline the advantages and disadvantages of the existing solutions: https://getpantheon.com/news/inside-pantheon-valhalla-filesystem.

---
Tags: 6, proxies
---


# Question
Title: How to copy Location Country field value from Parent object to Child object field default value?
I use Parent and Child content types with a Field used in both types.

I would like Drupal to automatically propagate the Field value from Parent value to the Child field default value.

How to do this ? I am interested specificaly in an example for Location\>Country field.

I use node reference or organic groups modules to set up Parent\<-\>Child relationships.

# Answer
Guess you want this to take place, when you create (aka save to db) a new node. You could do this in hook\_node\_presave.
> 3 votes

# Answer
There is a contributed module nodelocation\_relationship that helps with this but it is currently available for Drupal 6 only.
> 0 votes

# Answer
In Drupal 7 use node reference url http://drupal.org/project/nodereference\_url

When a new child is created it will reference-back to the parent. The parent is passed in the URL.
> 0 votes

---
Tags: 7, location
---


# Question
Title: How to add page "Contact us"/"Terms of usage" using a link in the footer but page's content to be in the main content(middle region)?
This seems to be a very newbie question. This is what I want to do:

I 'd like to have a link of type "Terms of usage"/"contact us" in the footer, and when the user clicks on it, a page to be appeared in the main region. How that could be done? Is it possible? Because from what I 've already seen, the page appears in the same theme region with its parent menu.

# Answer
> 1 votes
Do not know the version your using., search for 'overlay' in modules there are many.

In Drupal 7. Grab the following for direction

http://drupal.org/project/admin\_path

http://drupal.org/project/context\_overlay

# Answer
> 0 votes
I can't comment yet so I'm posting this as an answer. Seems like what you are asking for is default Drupal behaviour. If you create a new 'Basic page' called Terms of Usage, and link to that page, it will appear in the main region.

Can you clarify what you meant by 'the page appears in the same theme region with its parent menu'? Providing a link would also be helpful.

# Answer
> 0 votes
You could try using Ajax/jQuery to make your T&C/Contact form. Here is a good tutorial

---
Tags: navigation
---


# Question
Title: Facebook for drupal throws errors on install.
I have Drupal 7.9 installed with Facebook for Drupal module version 7.x-3.x dev.

Here are the errors given after turning on FB API & FBCONNECT:

> Warning: include(/src/facebook.php) \[function.include\]: failed to open stream: No such file or directory in fb\_requirements() (line 66 of C:\xampp\htdocs\drupal\phswap\sites\all\modules\fb\fb.install).
>
> Warning: include() \[function.include\]: Failed opening '/src/facebook.php' for inclusion (include\_path='.;C:\xampp\php\PEAR') in fb\_requirements() (line 66 of C:\xampp\htdocs\drupal\phswap\sites\all\modules\fb\fb.install).

reverting to a 6.x install for functionality is not an option. I hope someone can help.

# Answer
> 4 votes
Have you read the powerful **README.txt** file inside the module. It says you have to install the `facebook-php-sdk`. The instructions in the readme are pretty clear. The error is thrown because it can't find the file.

---
Tags: 7, social-network
---


# Question
Title: Build a dynamic form based on user input
I am looking on how to build a dynamic form in Drupal 6.
Users enter the number of people attended the meeting, and the form should present a text box for each of the people attending the meeting, and containing the contact information. I would love to use webforms to do this.

What would you suggest as best way to do this?

# Answer
If I understand well, one user need to enter informations for X persons who has to attend to your future meeting right?

To do it, I think the better way is to create a content type and use CCK with multiple field. If you need a group of fields, you can install CCK 3.X that include multiple\_group module. It's a module very useful that allow you create a group of fields and the user can multiple it at infinite or as you wish.
> 1 votes

# Answer
Can you safely assume that the number of needed fields will never exceed a certain value, for instance 20? In that case, I think I would create a webform with 20 fields, put a select box above it with the values 1-20 in it, and add some javascript to hide the form fields that are not needed, based on the value of the select box.
> 0 votes

---
Tags: 6, forms, webforms
---


# Question
Title: How to add "new" icon on node view page for predefined time frame
I would like to add "new" icon on node view page of some content type for a predefined time frame after the node content is created or updated. For example, I would like to display "new" icon on the top of node view page for 2 weeks after the node content was saved. I found this for Views but need it for node page. Is there anyway to achieve this?

# Answer
You can do this at least two ways:

1) Edit your theme's node.tpl.php to include some PHP code that compares the current date and the node creation or modification date, and, if it's within the predefined timeframe, prints that "new" icon wherever you want it, or,

2) Create a preprocess\_node() hook in either a custom module or in your theme that sets a variable that can be used in your node.tpl.php file for the same purpose.

SNIPPET ADDITION:

A quick (but verbose for self-commenting purposes) preprocess() hook in your template.php file could look something like this:

```
function phptemplate_preprocess_node(&$vars) {

  $node=$vars['node'];

  $two_weeks_ago = time() - (14 * 24 * 60 * 60);

  $node_creation_time=$node->created;
  $node_changed_time=$node->changed;

  if ($node_creation_time >= $two_weeks_ago || $node_changed_time >= $two_weeks_ago) {
    $this_node_is_new="THIS NODE IS NEW!";
  }

  $vars['this_node_is_new']=$this_node_is_new;

}

```

This would provide a $this\_node\_is\_new variable in your node.tpl.php template file(s) when the node was created or modified within the last two weeks.
> 1 votes

---
Tags: entities, datetime, nodes
---


# Question
Title: dynamic options list based on the previous select box value
I have a webform. I want the second select box values to be loaded based on the 1st select box value. And these values should be loaded from DB table. Please let me know which hook i need to use and how to do it.

# Answer
Try the Hierarchical Select module.
> 1 votes

---
Tags: 7, webforms
---


# Question
Title: Extending the content administration pages
I have a lot of different content-types and many of them refer to other content-types.

In the administration it's becoming harder and harder to find a specific node, so I was thinking of writing my own theme and possible a module to make the administration easier.

It would be nice to have a free text search box in the administration, that would let one search for nodes of specific types. Also in the listing of found nodes it would be great to be able to add specific fields so that you could see the relation between different content-types and so on.

Right now I'm using `hook_menu` to add a new page with a link link for each content-type, then in the callback I collect information about all nodes using a simple `db_query` call and then display the result using `theme('table',...)`.

Can anyone point me to some tutorials on how to achive this?

# Answer
> 10 votes
I would recommend you to have a look at the Views Bulk Operations module. With VBO you can create custom views with any exposed filters and criteria you need. VBO adds to every row a checkbox which can fire different operations which you also can define on the view itself.

# Answer
> 4 votes
In the Administration Menu project there is an add on module that allows you to replace all the admin pages with views pages. It relies on Views Bulk Operations. I imagine that it would be just a matter of changing the views that are added.

# Answer
> 2 votes
Beside VBO mentioned here, The module Content Type Overview might also be useful in your case.

http://drupal.org/project/content\_type\_overview

# Answer
> 1 votes
I would start with learning Views module. You can find a lot of learning materials on this module, for example http://dev.nodeone.se/node/701, some can be in Swedish (http://dev.nodeone.se/sv/learning-library-0).

---
Tags: 7, theming
---


title: Menu permission/visibility control

text:
# Question
Title: Menu permission/visibility control
I am in involved in developing a site builder using Drupal 7. Since it is a site builder, I need a user to be able to create menu items based on their needs, and then edit those menu items - but not any other users.

Also, is it possible to create a sub-domain during sign-up (along the lines of Drupal Gardens)?

# Answer
For the Drupal Garden's style setup, you should definitely look at Aegir. It requires a bit of setting up, but there are loads of tutorials and screncasts - there are a couple of good ones here and here.

With regards to your menu question, that seems like a simple permissions question. When you deploy your new sites, you'll obviously have to set up a user for the owner of said site. If you ensure that user has a particular user role, you can set permissions at "/admin/people/permissions" for the core menu module. Look under Menu around halfway down the page and check the box for `Administer menus and menu items` for your site owner's user role.
> 1 votes

---
Tags: 7, routes, users, aegir
---


# Question
Title: How can I generate a Report from database table? and how can I show it in page
I want to generate a report from values of a database table. I tried table wizard and views to generate reports. It shows it. But how I show this to a perticular Page/form.

# Answer
Create a page view, and see your report in that page.
> 2 votes

---
Tags: views
---


# Question
Title: What is the equivalent of sess_count in Drupal 7
As Converting 6.x modules to 7.x explained:

> All session functions starting with `sess_*`, as well as `session_save_session()`, are now renamed to `drupal_session_*` or `_drupal_session_*`

I have to use `sess_count()` in my D7 module and naturally I used `drupal_session_count()` but I ended up having `Call to undefined function drupal_session_count()` fatal error. I also tried `_drupal_session_count()` with no luck.
User session handling functions page for Drupal 7 didn't mention about this function neither.
Which function should I use in order to count how many users have sessions?

# Answer
`drupal_session_count()` was removed from Drupal 7. I'm not sure what an equivalent would be other than writing your own function.

Looks like the user block has it's own query. And admin menu had to replace it too.
> 3 votes

# Answer
The `drupal_session_count()` was removed in drupal 7, but I suppose you could do a simple `db_query` like this:

```
 $session_count = db_query("SELECT COUNT(*) FROM {sessions}")->fetchColumn();

```

You could also look at the `drupal_session_count()` function and use something similar:

```
function drupal_session_count($timestamp = 0, $anonymous = TRUE) {
   $query = db_select('sessions');
   $query->addExpression('COUNT(sid)', 'count');
   $query->condition('timestamp', $timestamp, '>=');
   $query->condition('uid', 0, $anonymous ? '=' : '>');
   return $query->execute()->fetchField();
}

```
> 1 votes

---
Tags: 7, sessions
---


# Question
Title: Is there any alternative way to add CCK field for Drupal 6
I am adding the amount of 2xx of fields to a content type at `/admin/content/node-type/product/fields`, is there any alternative way such as SQL statement to add these fields?

Thanks

# Answer
Do you mean you're adding over 200 fields to a content type?! Yikes!

If so, I'd *strongly* recommend you look into:

* Breaking the content type up into several smaller ones and using Node References to join them.
* Making sure you're using multi-value fields where at all possible.
* Using one or two 'Extra specification'-style free text/WYSIWYG fields to store unimportant data from many fields, provided you don't need to filter on those fields.

The issue comes down to practicality and future development... Imagine the size of your edit forms! Huge forms can actually cause problems for people's computers due to memory limitations. Imagine trying to debug or style such forms...

By breaking up the content type into groupings of fields, and collapsing discrete fields into text areas you can better normalise the data and, for a little extra work up front, save yourself a *lot* of pain later.

Drupal fields have entries in several tables and need many settings created, so I'd avoid using SQL to do it as it'd probably be much more work than just manually adding them.
> 1 votes

---
Tags: 6, entities
---


title: Drupal security measures

text:
# Question
Title: Drupal security measures
I have got a list of security violations for my website from security team. It says

> Cookie without HttpOnly flag set
>
> Autocomplete Password Enabled

So, what is this basically? Can I overcome this in my Drupal 7 site?

# Answer
> 6 votes
Ask for the actual security report. They often contain explanations about what the problem really is, as well as offering a solution.

I believe this will take care of the password autocomplete issue; I have a client who requires this and have it deployed on a few sites.

```
function mymodule_form_alter (&$form, &$form_state, $form_id)
{
  // http://www.midwesternmac.com/blogs/jeff-geerling/disabling-autocomplete-forms

  if ($form['#id'] == 'user-login') {
    $form['#attributes']['autocomplete'] = 'off';
  }
}

```

# Answer
> 4 votes
From the documentation for `session.cookie_httponly` (you should set this flag to true in your `php.ini` file):

> Marks the cookie as accessible only through the HTTP protocol. This means that the cookie won't be accessible by scripting languages, such as JavaScript. This setting can effectively help to reduce identity theft through XSS attacks (although it is not supported by all browsers).

Check out the documentation for `session.cookie_httponly`.

---
Tags: 7, security
---


title: Front page link token in full HTML?

text:
# Question
Title: Front page link token in full HTML?
When Im using the full html input format. Is there a way I can use some code to print the url of the front page of my site, so If I were to migrate the site it would still work?

I could do this with pathlogic but im wondering if there is a php type value that full html would use?

Thanks

# Answer
```
<a href="/">Front page</a>

```

But this doesn't respect the base folder. E.g. if your Drupal installation path looks like http://example.com/drupal\_site/, this won't help you, because link will lead to http://example.com/.
> 3 votes

---
Tags: tokens, uri
---


# Question
Title: Change "Passwords match" and "Password Strength" text on signup
How do I change the "Password Strength:Weak" and "Passwords Match:no" text on the sign up page. Are there drupal settings for this?

# Answer
> 5 votes
The two sentences are set by Javascript (/modules/user/user.js) so for this you have to use JS too..

```
$(".password-strength-title").val("Test");

```

can replace the first one, but for the other it is more complicate. I have to look deeper.

EDIT

The info are here now I don't know if it is possible to do an alter

EDIT

Ok so for doing what you want 2 steps:

```
function your_module_element_info_alter(&$type){
  $type['password_confirm']['#process'][] = 'your_module_form_process_password_confirm';
}

```

Then alter the data:

```
function your_module_form_process_password_confirm($element){
  $element['#attached']['js'][1]['data']['password']['strengthTitle'] = t("Test Title");
  $element['#attached']['js'][1]['data']['password']['confirmTitle'] = t("Test confirm");

  return $element;
}

```

# Answer
> 3 votes
If you take a look at the source for user\_form\_process\_password\_confirm, you will see the strings defined and that they are wrapped in a t(). This means they can be translated and/or overridden.

There are a few ways to do string overrides.

The easiest way is with the String Overrides module. This lets you do everything from the UI.

You can also do it with your `settings.php` file. If you search for "String overrides:" in that file, you will see an example, but you could do something like:

```
$conf['locale_custom_strings_en'][''] = array(
  'Password strength:' => 'Your password security is ',
  'Weak' => 'horrible.',
  'Fair' => 'pitiful.',
  'Good' => 'tolerable.',
  'Strong' => 'awesome.',
);

```

---
Tags: 7, users
---


# Question
Title: Fatal error: Call to undefined function quiz_type_access_load()
Getting the following error after switching servers. The setup is multisite on a linux box. The troublemaker is on subdomain. So far: disabled quiz and quiz submodules, cleared the cache, nothing really works.

```
Fatal error: Call to undefined function quiz_type_access_load() in /path/to/drupal/includes/menu.inc on line 411

```

# Answer
> 3 votes
Try to find and delete records in "menu\_links" and "menu\_router" tables of your database which have "quiz\_type\_access\_load" occurrences.

Be careful: backup the database first!

---
Tags: 7, routes
---


# Question
Title: How can I override the node edit in Drupal 6?
I'm trying to override the "node edit"(using a "page-node-CONTENT-TYPE-edit.tpl.php") in drupal 6, and I'm stuck with the fact that I can't choose which field I want to publish in a specific edit page. I have to publish the whole $content or nothing ! I tried with drupal\_render, $form etc... but nothing.

Does anyone have some clues on how I would be able to display the fields I want so I could design my edit page by content type?

I finally got it! It is quite simple; in fact, I just had to make a hook form filter, some "if" on `user_access()`, and rock and roll!

# Answer
> 1 votes
I am not exactly sure what you are asking here, but if you are trying to change the layout of the node edit form, you might check out the http://drupal.org/project/nodeformcols module that allows you to change the node edit/create form with a pretty straightforward drag and drop interface within CCK.

---
Tags: 6, theming
---


title: How can I disallow spaces in usernames?

text:
# Question
Title: How can I disallow spaces in usernames?
Drupal allows spaces in usernames, is there an easy way to stop this?

Also, where is the documentation on the username specs? What are the min/max lengths and which characters are allowed?

# Answer
The best way to handle this is to implement hook\_form\_FORM\_ID\_alter for the user sign up and edit forms and append your own validator to check for spaces in the username field.

As for the length of a username, the minimum is 1 character and the maximum is 60 - as per the db schema.
> 8 votes

# Answer
A quick alternative is using Access rules, in drupal 6 you'll find them at yoursite.com/admin/user/rules for Drupal 7 I believe it was spun of to contrib as User restrictions

All you need to do to disallow spaces in usernames is create a rule like this: `% %`
> 4 votes

---
Tags: users, database
---


# Question
Title: Redirect user/register to external user creation
I have a secondary system handling user authentication, but I would like to use the user creation code from that system instead of Drupal. I want to redirect the Drupal user creation to the secondary system instead.

I already have my own user creation page, so I don't want to do a form\_alter on Drupals user creation, I'd rather just send the user to my creation page instead.

How do I redirect user/register to my code instead of Drupal?

# Answer
> 1 votes
Roling your own user registration and authentication requires a number of steps. I try to eyplain them.

Calling `yourmodule_form_user_register_form_alter(&$form, &$form_state, $form_id)` would be a good idea. Actually you have to alter only the submission call back and may be the validation call back. You can have a look at the last lines of user\_register\_form how this is done in drupal core.

To make sure the users can login. It's possible to include an external authentication service. Have a look at user\_login\_default\_validators for this.

What is most important for you, that at the end of the login procedure you have to have a valid drupal user object. I'd recommend to have parallel external and drupal users. Probably do the authentication on your external service but let drupal load the corresponding drupal user once this was successful.

This gives you basic working system. Next steps would be to handle password change and one time password recovery links in a correct way.

# Answer
> 0 votes
This might work:

```
function yourmodule_menu() {
  $items["user/register"] = array(
    "type" => MENU_CALLBACK,
    "page callback" => "yourmodule_user_register_override"
  );
  return $items;
}

function yourmodule_user_register_override() {
  drupal_goto("path/to/your/custom/registration/form");
}

```

Also, you can create a preprocess function in your theme's template.php file like this:

```
function YOURTHEME_preprocess_page(&$vars) {
  if(arg(0) == "user" && arg(1) == "register") {
    drupal_goto("path/to/your/custom/registration/form");
  }
}

```

Or, as @BetaRide said:

```
function yourmodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form["#action"] = "path/to/your/custom/registration/form";
}

```

---
Tags: 7, redirection, users
---


title: Access on a Field

text:
# Question
Title: Access on a Field
I have a content type with some fields I've created and I also have 2 roles: A Client and A Technician.

I want the client to be able to fill in this new content type which is a support ticket, but I don't want them to have access to a field for assigning the job. How can I stop access to this field for the client, but make it visible and usable for the technician role? What I think I'm looking for is the Access Control Module but with the ability to grant access per field rather than node.

Thanks

Kieran

# Answer
I think you are looking for Field Permissions.
> 1 votes

---
Tags: 7, users
---


title: Show text in a page as popup

text:
# Question
Title: Show text in a page as popup
I have some text in my page. and a read more link. When i click on the link, it should open the text in a pop up window. Is there any module to do this? i need to just open the text in pop up not some URL /Html Page.

# Answer
> 2 votes
I use Colorbox for this; it's not a Drupal module but it's simple to create. Look at "Inline HTML" in the examples.

# Answer
> 3 votes
Check out the Popup module, which may be useful.

# Answer
> 0 votes
Shadowbox is another candidate for Drupal 7.

---
Tags: 7
---


# Question
Title: How to fetch X random entities of a given type using rules?
I have a custom content type "project" with several CCK fields. One of them is named "field\_old\_intranet\_url". No i want to assign a (random) user to every node of type "project". The author field or any other user\_reference would be fine.

My first thought was to create a rule which is triggered when a user logs in. Fetch X random "projects" without an author and save the current user as the nodes author.

The problem is, that you can either fetch nodes by id or property. nid is not working, since i dont know the id. When fetching by property one can only compare the property with data from the current user or the current page. In my opinion it is not possible to fetch X random nodes.

Another solution would be, to trigger the rule by content creation or when content ist saved or whatever and then assign a random user. But this isnt possible either, because you cant fetch X user without a property to compare.

I hope my problem is clear and you can come up with quite different solutions!

**Edit:** It is possible to fetch every possible combination of X nodes of whatever type with Views Bulk Operations. This part of the problem is solved. Now the remaining challenge is to assign one entity of one of the lists (users / nodes) to a random one from the other, is this possible?

One solution would be to fetch a random node using views, is this possible?

# Answer
> 2 votes
It is possible to fetch every possible combination of X nodes of whatever type with Views Bulk Operations.

To create the desired behaviour you can follow this set of steps:

1. In the actions part of a rule you fetch a list of nodes (list\_projects) using VBO, to which a random user should be assigned.
2. Using the sorting option "Global: Random" you can fetch one random user inside a loop and assign him to the other list of nodes.

# Answer
> 2 votes
Investigate the Views Module. It can create lists of nodes for you. Investigate node\_load() and node\_save(). They will allow you to modify those nodes.

# Answer
> 1 votes
I don't know pf a pure config solution. However this can easily be done with a few lines of code in hook\_node\_api (D6) or hook\_node (D7).

---
Tags: rules, views
---


title: Custom search paths

text:
# Question
Title: Custom search paths
I want "random/search/node/keywords" be the same as "search/node/keywords", or to be more precise, I need the "random/" at some part of the URL, so I can enable certain blocs on a certain search page. How can I achieve this?

I'm using Drupal 7

# Answer
You could rebuild the search page using views under any custom path. Have a look at http://drupal.org/project/search\_api for more possibilities.

Regarding the block visibility: you can use `*/search/node/keyword`.
> 1 votes

---
Tags: search, uri
---


title: How to create an Audio playlist

text:
# Question
Title: How to create an Audio playlist
Are there **any opportunities to create "classic" playlists** with Audio or any other similar modules? I primarily would like to let mp3-files be played, but in a way that it cannot be easily directly downloaded (considering the fact that as it's written on Audio module's admin interface, *"You should be aware that even when audio is not marked as downloadable, clever users can still download it, this just makes the work harder."*)

After uploading some separate Audio nodes, Audio players can be displayed via Views module like this (with some randomly uploaded tracks):

But **this is NOT a good solution for me as it's not like a normal playlist**, as **these are separate audio players**...
There is support in Audio module for the little bit ugly-looking XSPF Web Music Player - Extended, but I didn't find any opportunities to create a playlist with it either.

Any suggestions with Audio or any other suitable modules?
Thanks!

# Answer
The http://drupal.org/project/jplayer module allows for playlists and so forth, but unless you are up for some obfuscated javascript and a whole bunch of other coding (that in the end is nevertheless subvertible \[sp?\]) the mp3s will still be downloadable by most advanced users. (Or perhaps investigate the private file serving methods drupal offers, but then you have to balance the overhead there)
> 3 votes

# Answer
Go old school: Revert to flash.

Set it up in any of the multiple free flash media players out there, crate a view block for it, and call it whenever you need it, via panels or what else you may use.

Really, no matter what, people are going to be able to download the music. That is what they do when it streams, after all. If you're worried about DRM/copyright infringements, perhaps you shouldn't be tackling this with commercialized music.

If you just want to have a hotlist of sorts to use for yourself, I wouldn't worry about it too much; if you are creating a portal, or other site, for the streaming of media openly to the internet public, think about lowering the quality considerably, or something else.
> 0 votes

# Answer
We have done this here with CCK and AudioField. We are using views to show the list of the individual nodes. Every entry with it's own player. You can even start them in parallel :-).

Originally we were using the audio module. But we had all sorts of problems with this module. Since development has been stopped 2 years ago we went for the CCK & AudioField solution which works great.
> -1 votes

---
Tags: views, 6, files, media
---


title: Point to directory with .htaccess

text:
# Question
Title: Point to directory with .htaccess
mydomain.com currently points to public\_html/. I want to use .htaccess to direct it to public\_html/live/mysite.com/ . How can I do this?

I believe I need to add a directory to one of these lines (line 102-105 of .htaccess):

```
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]

```

# Answer
You probably wouldn't use .htaccess for this. If your webserver is Apache, your apache virtual host configuration is what points your domain to a directory on the server. On an ubuntu linux server your virtual host file would normally be in /etc/apache2/sites-enabled/mysite.com

If you are using a shared webhosting service (like Dreamhost) that uses an account configuration tool like Cpanel you can usually change your web directory using that tool. Look under options for "Domain Names" or DNS.

Don't mess with .htaccess unless you really need to--you can mess up your site or render it insecure. If you do edit .htaccess, make a backup of the original file.
> 2 votes

---
Tags: 7, redirection, .htaccess
---


# Question
Title: Caching interfering with jQuery and drupal behaviors?
I'm on the new side to coding so this is mysterious to me:

On several sites that I'm working on the jQuery library stops being added through drupal behaviors spontaneously as javascript and module files and page templates are altered. Once the site cache is cleared through drush the behaviors properly call jQuery again.

I work with 3 others, and though our database is centralized our file trees are local. We use git for version control.

Any information as to why this caching incident keeps happening would be very helpful. I'm trying to learn more about the caching process but so far I haven't found anything that clears this up.

# Answer
> 1 votes
Just like when you add a menu item or some theme elements, you need to clear the cache when you add new javascript.

For a site in development mode you can simply turn off caching so that you don't have to remember to clear the cache every time ('drush cc all' is handy):

Drupal 6: /admin/settings/performance: Caching mode set to disabled

Drupal 7: /admin/config/development/performance: Uncheck cache pages for anonymous users

Disabling "aggregate javascript", will make it much easier to debug your js with chrome or firebug.

---
Tags: 7, javascript, caching
---


title: How to create colored World maps?

text:
# Question
Title: How to create colored World maps?
I would like my users to be able to select the countries they have visited and then highlight those countries on a world map.

I've come across a few commercial flash solutions with XML config files but would rather like to avoid flash and have jpgs or pngs generated.

This site is a good example of what it should look like.

# Answer
You can probably use OpenLayers, with MapBox to create custom map layers with MapBox.com
> 3 votes

---
Tags: 7
---


# Question
Title: Views exposed filter autocomplete weird function() code
Should one worry when a Views exposed filter autocompletes a function for certain words?

1. Type `fbn` on the exposed filter field for Users. This is an autocomplete field.
RESULT: The autocomplete list offers two options starting with `function(..)`. See image.
2. Choose the first option, `function (E, F) ...`
RESULT: The word `filter` is filled in.
3. Type again `fbn` in the field, then choose the secons option, `function (B, C) ...`
RESULT: The word `indexOf` is entered.

Inspecting the elements doesn't work very well, as soon as the focus leaves the field the autocomplete vanishes. I'll try some more with a network sniffer or Firefox instead of WebKit, maybe I'll have more luck.

This could be an XSS injection attempt. Should I worry?

# Answer
> 1 votes
I do not think it is a major problem. I had a similar problem a while back ( I don't remember how I cleaned it up :( ). I would recommend you do check on another browser, but also try running update in the URL (example.com/update.php) this script makes certain that all DB updates of modules are completed. If it persists, you may want to visit the Views issues site at Drupal.org.

Please post back on this page with what worked.

---
Tags: views, forms, security
---


# Question
Title: How do I get rid of the "Review payment" form after PayPal Express checkout?
Can I somehow disable "Review payment" site after paying with "*Express Checkout*" method on PayPal?

Why is it even needed? Why do we assume that our customers who pay via PayPal "*Express Checkout*" do have a company? (There is the field "Company".)

Here's a screenshot:

# Answer
I got the answer and the solution on Ubercart's forum.

Quoting the user *longwave*:

> "In **Drupal 6/Ubercart 2** go to **`/admin/store/settings/payment/edit/gateways`** and expand PayPal Website Payments Pro then Express Checkout.
> In **Drupal 7/Ubercart 3** go to **`/admin/store/settings/payment/method/paypal_ec`** and look towards the bottom of the page."

I'm using D6. Then I mentioned that I see the following message on that page:

> "**You must enable the Credit Card module** to use PayPal Website Payments Pro."

... and that I didn't want to enable Credit card module while I don't need it. He said I have to, if I would like to reach "Review payment" settings:

> "**The settings are hidden here, this is a known bug.** Enable the credit card module; you don't have to use it - or you should be able to disable it again after changing the Express Checkout settings."

That's true, everything related to *"Review payment"* form could be set there!
I made a screenshot for others who are also struggling with this problem:

Problem solved. No more unnecessary questions before purchasing. :)
> 2 votes

---
Tags: 6, ubercart, payment-gateways
---


# Question
Title: Force `<li>` to scale to text field in the views-ticker module
The Views Ticker module can create a vertical scrolling feed of content. There is an assigned height to each `<li>` based on the content item that takes up the most space. In my case, it sets the height of each `<li>` to 72px. Instead of assigning it a definite value, I want the size of each `<li>` height to scale to the size of the content as opposed to a fixed content.

I've attempted to overwrite it with CSS by setting the height to AUTO but it doesn't work.

If you have a recommendation for another module to use that will scroll content like the ticker does, please post.

# Answer
> 0 votes
Views Slideshows has an option for forcing equal heights, failing that I would suggest using a jQuery plugin like equal heights

**Views Slideshows:**

> Views Slideshow can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.

# Answer
> 0 votes
You might want to try setting height AND overflow to auto. If that (maybe with a !important) doesn't work, take a look at http://archive.plugins.jquery.com/project/vTicker, which is where this comes from. There appears to be a way to disable the vertical sizing via js there.

ADDITION: I misinterpreted the documentation on the plugin page that stated:

```
height - set vTicker container height. Also disables all items auto height calculation. It is usable to remove space gaps between items. (default 0 - it means off)

```

thinking that setting to 0 (the default) would do nothing but setting it to a set number actually does that. Anyway, looking at the code, if it's set to 0, it does exactly what you don't want it to do:

```
       if (b.height == 0) {
            f.children("ul").children("li").each(function () {
                if (a(this).height() > e) {
                    e = a(this).height()
                }
            });
            f.children("ul").children("li").each(function () {
                a(this).height(e)
            });
            f.height(e * b.showItems)
        } else {
            f.height(b.height)
        }

```

So now what to do? Dull axe approach would be to remove all the height logic from the js if you want this site wide since CSS doesn't seem to be doing what you want. (Or keep hacking away at CSS, trying tricks like min-height: 1px !important; overflow: auto !important; etc etc but with jQuery adding style="XXXX" as it's way of doing things, these can be a bear to track down)

---
Tags: views
---


title: Panels on frontpage

text:
# Question
Title: Panels on frontpage
I'm trying to use Panels module on my drupal's frontpage.

I've created view called `front_page` with path set to *front*, proper node panel, set selection rules to URL (i've tried both *front* and `<front>`) but no matter what i'll set in Panel variant settings, i'm allways getting the default front page provided by drupal (or the one set in *Site Information*). When i'll change my variant's URL to i.e. *node/\**, it works fine. I simply can't just set a selection rule for front page.

Do you have any idea what am i possibly doing wrong ?
thanks in advance.

# Answer
in panels there is a option for set the panel as homepage.

that checkbox the only thing to do is set here: http://yoursite/admin/settings/site-information

the path of your panel as homepage.

So, if the url of your panel is "home-page" then just in the site-information section put that path as a homepage.
> 0 votes

---
Tags: 6, panels
---


title: Multiple account profiles

text:
# Question
Title: Multiple account profiles
I just started using **profile2** module to implement 2 types of profile for my site visitors (*sellers*, *buyers* for example). Both type of users can post content (say articles). I know whenever someone posts an article, a relationship is created in the db between that user and article. What I want to do is to show a user's articles under that user's profile page (the page that the **profile2** module creates). With drupal 6 and **content profile**, this was easily done with a few modules since profiles were nodes back then. I'm guessing I'll have to code up a module to do this since **profile2** profiles aren't nodes anymore. Can you guys give me some pointers on how you'd/you've gone about accomplishing this? Much thanks!

# Answer
Views is the way to go. Create a view with a block that lists articles, add a contextual filter to the user id and configure it to provide a default argument from the url. Then add that block to the user profile page, you should be set.
> 2 votes

---
Tags: 7
---


title: Change $form_state in AJAX callback

text:
# Question
Title: Change $form_state in AJAX callback
I am creating a form which uses the form API `'#ajax'` attribute, and I need to make changes to `$form_state` when the AJAX-enabled button is pressed. Here's what I've got:

Inside my form builder function:

```
...
$form['some_fieldset']['add_more'] = array(
      '#type' => 'button',
      '#value' => t('Add more rows'),
      '#ajax' => array(
        'wrapper' => 'some-fieldset',
        'callback' => 'my_module_settings_ajax',
        'method' => 'replace',
        'effect' => 'fade',
      ),
    );

...

```

And here's the callback function:

```
function my_module_settings_ajax($form, $form_state) {
  // Make a change to $form_state
  if ($form_state['some_fieldset']['add_more']) {
    $form_state['values']['some_fieldset']['table'][] = array('first_field' => '',
                                                                'second_field' => '');
  }

  return $form['some_fieldset'];
}

```

The change I've made to `$form_state` seem to be lost once the callback has finished. Is there any way to make a change to `$form_state` in this function, or there any other function I should use for this instead?

**EDIT**

As it turns out, the callback is the wrong place to do this logic. Instead, at the top of the form builder function, I added this:

```
// Respond to AJAX-triggger:
// Add new row
if ($form_state['triggering_element']['#name'] == 'add_more') {
  $form_state['values']['some_fieldset']['table'][] = array('first_field' => '',
                                                                'second_field' => '');
}

```

Of course, I had to give the button the name:

```
$form['some_fieldset']['add_more'] = array(
  '#type' => 'button',
  '#name' => 'add_more', // <-- Right here
  '#value' => t('Add more rows'),
  '#ajax' => array(
    'wrapper' => 'some-fieldset',
    'callback' => 'my_module_settings_ajax',
    'method' => 'replace',
    'effect' => 'fade',
  ),
);

```

And now it works!

# Answer
You need to pass `$form_state` as reference; the AJAX function needs to be defined as in the following example:

```
function mymodule_settings_ajax($form, &$form_state) { /* … */ }

```
> 3 votes

# Answer
I'm not sure that it's a direct answer to your question, but it may work for you use case: Instead of changing the $form\_state add values to your $form. If you don't want them to show just use `#hidden`.
> 0 votes

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


# Question
Title: Problem with Views 7.x-3.0 - Column not found
I just updated the views from 7.x-3.0-rc1 to version 7.x-3.0 and now I'm getting the following error when executing my view:

`SQLSTATE[42S22]: Column not found: 1054 Unknown column 'field_data_field_category.nid' in 'on clause'`

The generated query looks like this:

```
SELECT node.title AS node_title,
       node.nid AS nid,
       node_field_data_field_category.title AS node_field_data_field_category_title,
      'node' AS field_data_field_color_node_entity_type,
      'node' AS field_data_field_image_node_entity_type,
      'node' AS field_data_field_sale_node_entity_type
FROM {node} node
LEFT JOIN {field_data_field_category} field_data_field_category ON node.nid =
                                      field_data_field_category.entity_id AND
                                      (field_data_field_category.entity_type = 'node' AND
                                      field_data_field_category.deleted = '0')
LEFT JOIN {node} node_field_data_field_category ON field_data_field_category.nid =
                 node_field_data_field_category.nid
LEFT JOIN {field_data_field_gender} field_data_field_gender ON node.nid =
                                    field_data_field_gender.entity_id AND
                                    (field_data_field_gender.entity_type = 'node' AND
                                    field_data_field_gender.deleted = '0')
WHERE (((node.type IN  ('product')) AND (node.status = '1') AND
        (field_data_field_gender.field_gender_value IN  ('0', '1'))));

```

I see that the `field_data_field_category.nid` should be `field_data_field_category.field_category_nid`, but how do I solve this without using something like `hook_query_alter`?

# Answer
> 1 votes
The problem was in the `references` module, I found this patch wich solved the problem.

# Answer
> 0 votes
Most likely the data for the field is wrong or incomplete. You can fix this with hook\_views\_data\_alter. Not knowing anything about the field, it's hard to say what to do exactly. At worse, you need to create a custom handler.

---
Tags: 7, views
---


title: need sql assistance

text:
# Question
Title: need sql assistance
```
$otvet = db_query("
SELECT {node}.title, {content_type_answer}.field_question_nid, {content_type_answer}.nid
FROM {node}, {content_type_answer}
WHERE {node}.nid = {content_type_answer}.field_question_nid
LIMIT %d, %d", 0, 3);
while($ref = db_fetch_object($otvet)) {
   $otvets[] = array($ref->field_question_nid, $ref->nid, $ref->title);
}
print '<pre>'; print_r($otvets); print '</pre>';

```

Is there a mistake after WHERE... ?

`{content_type_answer}.field_question_nid` has the same id as `{node}.nid`, and i have these nodes in my database. Why it doesnt works? I need to select `{node}.title`, `{content_type_answer}.field_question_nid`, {content\_type\_answer}.nid with condition that `{node}.nid == {content_type_answer}.field_question_nid`

# Answer
```
$otvet = db_query("
    SELECT n.title AS title, cta.field_question_nid AS nid
    FROM {node} n
    INNER JOIN {content_type_answer} AS cta ON cta.nid = n.nid
    LIMIT 0, 3
    ");

while($ref = db_fetch_object($otvet)) {
   $otvets[] = array($ref->nid, $ref->title);
}

print '<pre>';
print_r($otvets);
print '</pre>';

```

Surely something like this would be a better option?

Your query also has the data for 3 placeholders, but it only actually has two placeholders in it. You have `%d, %d` as limit placeholders, but there is no `'%s'` to place the `'article'` anywhere. This means that your query is going to try and place `'article'` when it's expecting an integer (which will make it fall over).

**EDIT**

Changed query as per comment.
> 4 votes

# Answer
```
$otvet = db_query("
  SELECT node.title, content_type_answer.field_question_nid, content_type_answer.nid
  FROM {node}, {content_type_answer}
  WHERE node.nid = content_type_answer.field_question_nid
  LIMIT %d, %d", 'answer', 0, 3);
while($ref = db_fetch_object($otvet)) {
   $otvets[] = array($ref->field_question_nid, $ref->nid, $ref->title);
}
print '<pre>'; print_r($otvets); print '</pre>';

```

Install Devel to replate `print '<pre>'; print_r($otvets); print '</pre>';` by `dpm($otvets);` and debug easily
> 1 votes

---
Tags: database
---


title: Paginate by date

text:
# Question
Title: Paginate by date
This is for Drupal 7.

I Have a content type which includes a date field. Is there a way I can configure the view to perform the pagination based on month.

E.g page 1 =\> all results for current month, page 2 =\> all result for month before, etc...

Any and all help appreciated.

# Answer
Probably not directly with a pager. But you could do an exposed filter in views for the year. This will create a dropdown with the values found on the nodes.
> 0 votes

---
Tags: 7, views, datetime, paging
---


title: Pager for multivalued node field

text:
# Question
Title: Pager for multivalued node field
There is a plenty of plugins for building all kinds of sliders and carousels with Views.

But frequently I find myself in a situation, when I need to make some kind of slider not for a whole node but only for one particular field with multiple values. Of course, I can attach a view using the EVA module and use it to output just one field of current node.

But is it a recommended way? Are there better solutions?

# Answer
You can use the CCK Pager module.
> 1 votes

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


# Question
Title: Views aren't respecting the ?destination=xxx in the URL
Using Drupal 7/Views 3, I created an admin page for a custom content type. When I click on a node edit link on a row, I'm directed to node/33/edit?destination=admin-mycontent ,where I can edit the node.

If I perform an operation like adding a field, the "destination=" in the URL is ignored, and when I save my changes, I'm directed to the node view, instead of back to my admin page.

If I cancel instead of save, I'm directed back to my view.

How can I have the expected redirect when I save the node?

# Answer
> 1 votes
It's not views, is the Drupal core. When creating/saving a node, you are automatically redirected to that node. You could create a module that hooks into node saving form and redirect you to the url destination path.

you should also check the rules modules. It seems that could do the job for you.

---
Tags: 7, views, redirection
---


# Question
Title: display question content type and a referenced node answer
I have a content type - question (its used for questions) AND content type - answer (it has a field -\> nodereference to questions with select list)

How to display in a view block question title and below to each question - referenced node title of content type answer?

What i did: i'v created a view block, and filtering it by content type - question, now im displaying all question titles, but how to display answers below these question (Each answer below referenced question)

Something like:

Do you smoke cigarettes?

Yes, i do.

What's your name?

My name's Jack.

# Answer
> 4 votes
You will have to create a relationship.

1. Click the \[+\] next to Relationships in Views, and select the field that contains your node reference
2. Make sure your Row Style is set to fields
3. Select Node: Title - do not use the relationship yet.
4. Next, select Node title again, but this time tell it to use the relationship (the field should be listed in your field listing as (Relatioship name) Node: Title).
5. Filters should be set to whatever your content type for questions is called.

# Answer
> 1 votes
You will need to add a views relationship for the node reference, then it will become available as a field.

---
Tags: views, 6
---


title: Drupal Views: Passing a Variable

text:
# Question
Title: Drupal Views: Passing a Variable
Here's my intention...
I have one view to output my Downloads (Downloads is set up a content type). As a field in the content type for Downloads, I have Product. The user can choose a product for which this download applies. For example, a product brochure for product A would then have Product A as it's product field.

I wouldn't want the content editor (my client) to be able to edit and control the views, I fear it'll blow her mind. So I want to create a single view, and have this view (as a block) display on every Product page. I only want the downloads for the relevant products being displayed, not every single product.

The Downloads view is set up, but at the moment it just lists every download for every product. Is there a way to try and match \[field\_download\_product\] replacement pattern with the page's title?

Could you suggest an alternative set-up to achieve this?

# Answer
> 3 votes
First of all, instead of using taxonomy, I would recommend a module like Entity Reference or References to create links between 'download' and 'product' nodes. I think Entity reference is your best bet in this case, because the module page explicitly says it supports "Integration with Views (for both forward and backward references)".

Once you have defined the download-product relations, you can build your view. The key to your solution is the concept of "contextual filters". A contextual filter is a filter with a variable filter value. You will find the settings for it in the right column when editing a view. I can't give you detailed instructions because I don't have a test site with entity reference here, but you'll need to take the following steps:

* create a view, listing nodes of type 'download' in a block
* add a contextual filter on the entity reference field in your download nodes
* when configuring the contextual filter, under "When the filter value is NOT available" choose "Provide default value" -\> "Content ID from URL".

So what does this all mean? You now have created a view that will only display download-nodes where the entity reference value is equal to the content ID detected in the URL.

Now, try if it works by enabling the block on product pages. Good luck - I hope this helps.

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


title: Drop down menu without any module

text:
# Question
Title: Drop down menu without any module
Hello is it possible to create drop down menu without using any plugins at all? In general the structure of menu is as follows for drop down.

```
<ul>
  <li><a href="#">Top1</a>
    <ul>
      <li><a href="#">drop1</a></li>
      <li><a href="#">drop2</a></li>
    </ul>
  </li>

```

I have create new menu and placed menu parents and children accordingly. Now I need to know if it is possible to show the menu in structure as above without using third-party modules.

# Answer
> 1 votes
You can do it with pure CSS, here is a tutorial: http://csswizardry.com/2011/02/creating-a-pure-css-dropdown-menu/ You can find several more if you google for CSS dropdown menu.

You will need to set up your menu, clicking on the "expanded" checkbox for any submenus you want to render.

# Answer
> 0 votes
You have two options:

1. As "Shoaib Nawaz" said in the comments, you can use Javascript (jQuery) to convert the list into a dropdown.
2. I don't know why you don't want to use any plugins (I suppose you mean "module")? But if it's fine for you to create your own module, there is another solution:

* Create a module
    * Overwrite the function theme\_menu\_tree to convert the "ul" into "select"
    * Overwrite the function theme\_menu\_link to convert the "li" into "option"
    * Bonus: If you don't want to overwrite every menus, you can overwrite only a specific menu using `[MODULE]_menu_link__[MENU NAME]`.

---
Tags: routes
---


title: multiple queries in select sql

text:
# Question
Title: multiple queries in select sql
```
$result = db_query("SELECT {node}.title, {content_type_answer}.field_question_nid, {content_type_answer}.nid FROM {node}, {content_type_answer} ORDER by nid ASC LIMIT %d, %d", 0, 3);
while($ref = db_fetch_object($otvet)) {
    $otvets[] = array($ref->field_question_nid, $ref->nid, $ref->title);
}

```

I have 2 content types: 1. question, 2. answer. In `{content_type_answer}` i have a nodereference field - `field_question_nid` that gives me the node id of the referenced question and {content\_type\_answer}.nid - gives me the answer node id.

But the problem is in title, `{content_type_answer}` table doesn't has a title row. In a code above i've succesfully selected title row from `{node}` table :D But how to make condition - i need only {node}.title from nodes which have `{content_type_answer}.nid`?

# Answer
> 1 votes
This is a job for Views. To expound upon the comments, this is a screen shot of a quick view that will do this:

I created two quick content types, answer and question. I used the body field just for expediency in both, and the only other field I added was a node reference called question in the answer type.

In the View, I filted on published nodes of type answer, the argument is that node reference field above, with the default coming from the URL. I output the Title and Body field. I set the paging options to 4 so that it would output a maximum of 4 answers to match the LIMIT in your query. I didn't sort the output but you can do that if you want in Sort Criteria.

I created only one quick question and answer. On my system, the question is nid 379, so:

putting that in as the argument, the view will output any answers (well, up to 4) with that nid as the node reference in question. Create a block display for this, and you can have this displayed on your node page with the question.

Now, as you mention in the comments, if you are sure you want to do all of this yourself in your page.tpl.php file with db\_query()s, feel free to scrape out the query Views has built for you from the preview. In this case, that would be:

```
SELECT node.title AS node_title, node.nid AS nid, node_revisions.body AS node_revisions_body, node_revisions.format AS node_revisions_format FROM node node  LEFT JOIN content_type_answer node_data_field_question ON node.vid = node_data_field_question.vid LEFT JOIN node_revisions node_revisions ON node.vid = node_revisions.vid WHERE (node.status = 1) AND (node.type in ('answer')) AND (node_data_field_question.field_question_nid = 379 )

```

and modify it to your specific needs.

---
Tags: 6, database
---


title: Bulk generate hierarchical vocabularies

text:
# Question
Title: Bulk generate hierarchical vocabularies
I have a quite big website with restaurants. I'm saving their data (like coords, city, street, country etc.) with CCK fields.

Fields *City* and *Country* are connected with vocabularies (named *Cities* and *Countries*). What i'm trying to do is to somehow bulk save all the *Cities* terms as a child elements of a term from *Cities* taxonomy. So if i have a restaurant located in *Barcelona, Spain*, i wan't to save a *Barcelona* term (from *Cities* vocabulary) as a child element of *Spain* term (from *Countries* vocabulary).

Have you any ideas how can i make something like this ?
thanks in advance.

# Answer
> 4 votes
I recently created a hierarchical taxonomy on our main premium site using some data exported from our SQLServer and used Taxonomy CSV import/export to import the file. I used LibreOffice Calc to massage the data into place, then exported from LibreOffice to CSV. A Google Docs version of my data is available, if you're interested.

Two things I remember doing:

1. I choose to import as a 'taxonomy\_manager' file
2. Any term which will be used as a parent needs to appear at the top before any of its children appear.

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


# Question
Title: Performance using location based information and proximity filters
I'm building a site where each piece of content is geocoded with latitude and longitude. Information will be shown based on proximity to a location chosen by the user. It seems like it would be faster if the information was shown based on city or state arguments because then Views can be cached. If every page view requires a proximity search of nodes from a lat/lng coordinate that no two users will ever share, I imaging the database will be getting a big work out.

A proximity search is fine, but how do I show other nodes in context of proximity whether it is state, town, city, or country?
What would the information architecture be?

# Answer
I'll answer the first part of your question about caching with a gentle warning and a tip...

I've tried caching location-based searches and it's a fast way to a HUGE (slow) cache\_views\_data table.

The reason is the same as the need to cache; there are lots of permutations of latitude and longitude, so every new request will add to the cache. Depending on the speed at which you have new content or updates, the cache will either:

* become immense as the queries are stored for many different lat/long combinations. This will happen with long cache times.
* be quite big but rarely hit because the cache times are suitably short to keep the pages showing fresh data.

Super-huge cache tables can quite possibly be as much of a performance hit as having the database just calculate what's nearby. Lookups might be ok but inserts and expunging old data will certainly slow your database server down.

One approach I considered but haven't yet implemented is to make the latitude/longitude arguments less granular by rounding the values to fewer decimal places. This way, you can have much higher cache hit rate at the expense of a little accuracy. For example, there's much more chance of (51.1, 0.9) being hit by multiple users than (51.123456, 0.887744). The number of decimals, and therefore accuracy loss, is entirely up to you.

You can either implement a views hook to change the views arguments, or use Views PHP to add custom code to your arguments which allows them to be rounded within the view itself.
> 2 votes

---
Tags: 7, views, performance, location
---


# Question
Title: Testing the value of Fields stored on Taxonomy Terms
I have a field (called Division) attached to a node. I want to print out a link (called Switch) on page.tpl.php that varies according to the value of this (node-based) field.

I can successfully do this with the following code:

In *template.php*

```
function elite_field_division_helper(&$variables) {
  if ($node = $variables['node']) {
    $field_division = field_get_items('node', $node, 'field_division');
    if ($field_division[0]['tid'] == 1) {
      $variables['switch_site'] = '<a id="switch_site" href="'.$GLOBALS['base_url'].'/business'.'">Visit Our Business Website</a>';
    }
    else if ($field_division[0]['tid'] == 2) {
         $variables['switch_site'] = '<a id="switch_site" href="'.$GLOBALS['base_url'].'/home'.'">Visit Our At Home Website</a>';
    }
  }

}

```

In *page.tpl.php*

```
<?php if (!empty($switch_site)):?>
  <?php print $switch_site; ?>
<?php endif; ?>

```

My question is: How can I get this code to work with fields that are attached to TAXONOMY PAGES? (As Drupal 7 allows taxonomy pages to have fields).

# Answer
Panels is very good for overriding Taxonomy pages. You can have different page and layout variants per vocabulary, user, theme, site etc. You can then include your code in a custom panel pane for taxonomy pages, together with whatever layout or views necessary, or write your own CTools content type for Panels.
> 1 votes

---
Tags: 7, theming, taxonomy-terms, entities
---


# Question
Title: How do I get the absolute URL when using l()?
I want to get `<a href="http://site.ru/node/123">New product</a>` from `l()`, and I call it as `l('New product', 'node/123')`, but this function generates a URL that is not absolute.

How can I generate an absolute URL with `l()`?

# Answer
You can make a link absolute with:

```
l(t('New product'), 'node/123', array('absolute' => TRUE));

```

See l() and url() for more.
> 23 votes

# Answer
Check out `l()` and the options in `url()` for how to construct a link with or without http: but basically you need to set the absolute option to TRUE.
> 2 votes

---
Tags: navigation
---


# Question
Title: host static files (images) to 3rd party host such as Amazon Cloud. Any modules can facilitate this?
I want host all images files to the cloud, such as amazon s3.

For example, when creating the node, uploaded automatically upload the files to the cloud, and all images path automatically point to the image stored in the cloud.

Any modules facilitate the CDN transition?

Thanks.

# Answer
I would go with the CDN module, also checkout the AmazonS3 module.
> 3 votes

# Answer
Media Mover supports staging/moving files to Amazon S3, plus complex file workflows.
> 1 votes

# Answer
Drupal CDN & Static File Server - The Amazon S3 Way is an oldie but a goodie as well
> 1 votes

---
Tags: cdn
---


# Question
Title: How to add vocabulary terms to a taxonomy category
I'm trying to get my module to install a vocabulary on enable/install but something about adding terms to it isn't working. any idea why this function isn't working?

```
function _vocabulary_add_items() {
  $vocabulary = taxonomy_vocabulary_machine_name_load('usertype');
  if($vocabulary === TRUE) {
    $terms = array(
        (object) array(
            'vid' => $vocabulary->vid,
            'name' => t('Economy'),
            'description' => t('Basic user account'),
            'format' => '', // default
            'weight' => 0, // default
            'vocabulary_machine_name' => $vocabulary->machine_name, // optional
        ),
        (object) array(
            'vid' => $vocabulary->vid,
            'name' => t('Deluxe'),
            'description' => t('Deluxe user account'),
            'format' => '', // default
            'weight' => 0, // default
            'vocabulary_machine_name' => $vocabulary->machine_name, // optional
        ),
        (object) array(
            'vid' => $vocabulary->vid,
            'name' => t('Ultimate'),
            'description' => t('Ultimate user account'),
            'format' => '', // default
            'weight' => 0, // default
            'vocabulary_machine_name' => $vocabulary->machine_name, // optional
        )
    );
    foreach ($terms as $term) {
        taxonomy_term_save($term);
    }
  }
}

```

# Answer
> 2 votes
`taxonomy_vocabulary_machine_name_load()` returns an `object` or `FALSE`. You're checking for exactly `TRUE` by using `===`.

Any of the following should work (sorted by my preference):

```
if ($vocabulary) {
if (is_object($vocabulary)) {
if ($vocabulary !== FALSE) {
if ($vocabulary == TRUE) { // only two equal signs here

```

---
Tags: taxonomy-terms
---


# Question
Title: ERROR:Cron run exceeded the time limit and was aborted. why?
My Drupal installation's cron runs fail when run manually or by cron script.

I thought it might be the Simple News module, but I've disabled then uninstalled that and the problem is still present.

My PHP `max_execution_time` is set to 120 seconds, but only takes 2 seconds before I'm redirected to `domain.com/user/1/edit` with no error message is displayed.

When I look in the dblogs I can see:

> Message: Cron run exceeded the time limit and was aborted.
> Severity: warning

I have looked in the Apache logs and no PHP error is given. How can I debug in fix this?

# Answer
Often a drupal\_goto() call in a page or module will be sending the execution of the cron run off course.

This often happens when the core Search module tries to index a page with such a `drupal_goto()` call. The solution is to find that page (or module) and remove the call, or change it so it doesn't fire during a cron run.

Try installing Elysia Cron to allow you to run each Drupal cron task in turn to work out what's causing the problem. From there you'll be able to debug it or look for ideas on the Drupal.org issue queue.
> 2 votes

# Answer
Usually it's a cron hook in just one of you modules that's causing the timeout. You need to find the problem module. This article: Drupal Cron Troubleshooting is one way to investigate this. Make a backup of module.inc so that you can undo the edit. If you aren't comfortable with editing this file, you could take the time-consuming approach of disabling all your contributed modules, running cron, enabling one module, run cron until you find the culprit.

A debugger is a better way to attack this, but you need to know how to use one.
> 1 votes

# Answer
You can see Cron run exceeded the time limit and was aborted

If you have a nginx or any frontend server, it can make this problem.
> -1 votes

---
Tags: cron
---


# Question
Title: Why are my views arguments not being handled properly?
I'm using Views 2 to rewrite the output of a specific field, which looks like this:

```
<a href="highlights1/[nid]/[field_uclw_value]">
  <span class="bold capitalized">[title]</span>
</a>

```

The link is generated as `http://www.xxxx.edu/highlights1/12499/Yes`, which I is correct. The view is at `/highlights1`, argument 1 is `12499`, and argument 2 is `Yes`.

But Drupal is not finding the page because its looking for the full path and NOT stripping & passing the arguments to the view named hightlights1.

These two args *are* defined in the referenced view, so why are they not being sent to the view?

# Answer
> 1 votes
Do you have a page display for your hightlights1 view with a path of `highlights1/%/%` set up?

Edit the path of your view's page display and ensure it's `highlights1/%/%` -- the percent signs each represent an argument for views to collect from the path and use.

---
Tags: views
---


# Question
Title: content field user reference populated by view (views2)?
Drupal-6.22

I have numerous content types where one or more users are associated with the type. On the bottom of the field definition page there is an advanced section where it asks for the name of the view to provide the content. I've created a view but it is not showing in the drop down in this area. What does one have to do in order to make a view available for this content field drop down?

The field area reads: Advanced - Users that can be referenced (View)

Please provide a URL where this is explained?

Thanks

# Answer
> 1 votes
The way I understand it, CCK will list all views on your site that return USERS, so, make sure your view is of type USER not NODE.

---
Tags: views
---


# Question
Title: How to create an alternate title for a node when in a nodequeue?
We want to be able to override the title of certain content items, but only temporarily, while they're included in a nodequeue. For example, we have a nodequeue view block in a small "featured" sidebar, without much room for long titles.

I want to avoid adding an alternate title to each content type because there are lots of content types and the alternate title only needs to be used while the node is in the nodequeue (ie, featured). Once the node gets replaced in the nodequeue, the alternate title would be cluttering up the database.

I found a module called Nodequeue Annotate, that happens to have the data structure I needed but it's intended for an unrelated use case. I've written a companion module to make it do what I need, but it seems like a bit of a hack to piggyback on a module to make it solve an unrelated use case.

So, I'm curious how would others handle that use case?

# Answer
I've used this css quite often in these cases:

```
width: // short width;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;

```

Which turns something like

```
A great new article about something so important that we have highlighted it for you

```

into

```
A great new article about som...

```

Obviously, this works best when the jist of the title is in the beginning of it :)
> 2 votes

---
Tags: blocks, 7, nodes
---


title: Help with subdomains

text:
# Question
Title: Help with subdomains
My hosting provider has problems. I put Drupal on a sub-domain of my site. When I try logging in or clicking a link it comes to a Internal server error. But if I navigate to the actual directory it works fine. What should I do?

Examples:

**Works:** sld.tld/subdomainroot/Y

**Fails** subdomain.sld.tld/Y

# Answer
If sld.tld/subdomainroot/Y works, that suggests that you have set $base\_url in your settings.php to include subdomainroot. If that's the case, subdomain.sld.tld/Y certainly won't work because drupal will be using the above. Now, if this is the case, and you change the above to subdomain.sld.tld, you still may have issues with cookies being set to the old domain until they are cleared.
> 2 votes

---
Tags: subsites
---


title: How can I position a logo

text:
# Question
Title: How can I position a logo
I absolutely love the Andromeda theme for the site that I am developing, however I have to make use of two logos. The site logo in a standard position (upper left) and a logo for a parent site which needs to be positioned at the bottom right of the footer. How can I do this?

# Answer
First of all, if you're going to change the theme, it is recommended to make a subtheme first so that updates don't clobber your changes. See Creating a sub-theme for more details.

As one option, the theme will have a `page.tpl.php` which is used to construct all the pages on your site. You could add your second image here.

Another way would be to add a block and place it in the footer if you really didn't want to modify the theme directly.
> 2 votes

---
Tags: 7, blocks, theming
---


title: Default values help

text:
# Question
Title: Default values help
I have a requirement whereby the default image for an image field in the article node should be set for a 6 month period of time and then the default image changes for the next 6 months and so on. I tested this in the article content-type by setting the default image and then creating content off the content-type. I then changed the default image and created new content. This changed the images in the new *and* old contents. I would like the old content to retain the old default image and the new content to reflect the new default image. Any pointers on how to do this?

Thanks.

# Answer
> 3 votes
The quickest solution is to not use a default image, but instead use a (hidden) field in your content type that points to an image to display if the main image field is empty, and change it's content every 6 months.

ADDITION: The next quickest solution is to look in a directory for the newest image file there that isn't newer than the node in question, and use that image if the main image field is empty. This way, just putting a new image in that directory will automatically be picked up by new nodes, but won't impact nodes already created.

---
Tags: 7, media
---


title: Heartbeat module

text:
# Question
Title: Heartbeat module
How do you enable AJAX in Heartbeat, such that when you click load older messages, it loads the messages? Currently, when I click the link there is no response whatsoever. Do I need to download any file?

# Answer
> 1 votes
No, you don't need to download any file. There was a recent issue with the refresh functionality that might be applicable to what you are experiencing: In heartbeat.entity.inc, at line 242, the "/js" is missing in front of heartbeat.js so the stream are not refreshing.

Instead of `drupal_get_path('module', 'heartbeat') . '/heartbeat.js'`, that line should be `drupal_get_path('module', 'heartbeat') . '/js/heartbeat.js'`-

---
Tags: 7, ajax, heartbeat
---


# Question
Title: How to create a block to show a digital clock?
I need to create a block to show a LIVE digital clock?

I tried to use the http://drupal.org/project/clock and the http://drupal.org/project/jstimer modules but it doesn't use javascript to refresh the time, it shows the time when the page is load, to refresh the time I need to reload the page.

How can I do this?

Something like this http://drupal.org/project/timeblock but for D7

# Answer
100% agree with Jimajamma above on extracting the stuff you need from the timeblock module, all it is really doing is just adding two javascript blocks with a minimal amount of formatting. For example, to replicate the 24-hour clock, all you have to do is create a new block with an 'unformatted' input format and add this code (extracted from the time block module):

```
<span id="liveclock" style="position:relative;left:0;top:0;">
</span>

<script language="JavaScript">
<!--

function show5(){
 if (!document.layers&&!document.all&&!document.getElementById)
 return
 var Digital=new Date()
 var hours=Digital.getHours()
 var minutes=Digital.getMinutes()
 var seconds=Digital.getSeconds()
 if (hours<12)
 hours="0"+hours
 if (minutes<=9)
 minutes="0"+minutes
 if (seconds<=9)
 seconds="0"+seconds
myclock="<strong>"+hours+":"+minutes+":"+seconds+"</strong>"
if (document.layers){
document.layers.liveclock.document.write(myclock)
document.layers.liveclock.document.close()
}
else if (document.all)
liveclock.innerHTML=myclock
else if (document.getElementById)
document.getElementById("liveclock").innerHTML=myclock
setTimeout("show5()",1000)
 }

$(document).ready(function(){ show5(); });

//-->
</script>

```

Quick fix to replace the body unload with a jquery $(document).ready() call, though probably not necessary inside a block.
> 2 votes

---
Tags: blocks
---


title: <?php if ($is_blog): ?>

text:
# Question
Title: <?php if ($is_blog): ?>
In my page.tpl.php, I want to add a line only for my blog page similar to how I see elements applied only to the front page.

```
 <?php if ($is_front): ?>

 <?php if ($is_blog): ?>

```

But it doesn't work. Can anyone tell me the correct PHP to target the blog page?

# Answer
`$is_blog` is not a valid variable in page.tpl.php. You can refer to the API documentation for more details on which variables are available.

In a situation like this, you will most likely want to implement template\_preprocess\_page() in your theme's template.php file in order to make additions to be page template.
Depending on whether you want this to apply on an individual blog entry's page or a blog listing page, the exact implementation will vary.

Another option would be to duplicate your page.tpl.php file and rename it to page--blog.tpl.php and make your additions there. Another simple solution would be to create a custom block that only displays on blog pages.
> 3 votes

# Answer
Sheena has the proper answer, but just to add a touch to clarify, if you want to have a `$is_blog` variable accessible to all your templates, you will need to add a `theme_preprocess_page` function in your `page.tpl.php`. Something maybe similar to this:

```
function <yourthemeName>_preprocess_page(&$variables) {
  $path = drupal_get_path_alias($_GET["q"]);
    // check if we are on blog page
    if (check_is_blog($path)) {
      $variables['is_blog'] = true;
    }
}

```

Hope that helps. Credits go to sheena\_d.
> 1 votes

# Answer
You can create a tpl.php file for every node type. To figure out the correct name of the tpl.php file install the Theme Developer module and simply point and click on your blog (or whatever you want to style differently).
> 1 votes

---
Tags: theming
---


title: Rewriting output of a field in node.tpl

text:
# Question
Title: Rewriting output of a field in node.tpl
One way is to use `$node->field_myfield[LANG][0][value]="value"` that needs another line for getting field's language using `field_language()`.

Is there an easier and cleaner way?

# Answer
> 6 votes
You should use the field\_view\_field() function. Have a look at Rendering Drupal 7 fields (the right way).

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


title: Help With SQL Query

text:
# Question
Title: Help With SQL Query
I have the following code:

```
$my_result = db_query("SELECT nid FROM content_field_taxo_listing WHERE field_taxo_listing_value = '%s'", $tid);

while ($my_row = db_fetch_array($my_result)) {
  $nodeids[] = $my_row['nid'];
}

```

What I want to do is to join (it might be a union, but I am not sure) the "content\_field\_taxo\_listing" table with the "node" table, and order the "nids" field by title in the "node" table.

What is the Drupal way for doing this?

# Answer
```
$my_result = db_query("
  SELECT {content_field_taxo_listing}.nid
  FROM {content_field_taxo_listing} LEFT JOIN {node} ON content_field_taxo_listing.nid = node.nid
  WHERE content_field_taxo_listing.field_taxo_listing_value = '%s'
  ORDER BY {node}.title", $tid);

```
> 1 votes

# Answer
Try this one:

```
$my_result = db_query("
  SELECT ctl.nid
  FROM {content_field_taxo_listing} ctl
  LEFT JOIN {node} n ON ctl.nid = n.nid
  WHERE ctl.field_taxo_listing_value = :tid
  ORDER BY n.title ASC",
  array(":tid"=>$tid)
);

```
> 1 votes

---
Tags: database
---


# Question
Title: Ranking items (groups, nodes) by the number of Facebook likes
I am on Drupal 7.

I need to add a Facebook like button that will be associated with organic groups pages. Each group will have a different like button so that each group has an independent "Likes" count. I can do this by simply configuring and adding a Facebook iframe or XFBML interface. More about this here: http://developers.facebook.com/docs/reference/plugins/like/.

What I cannot figure out is how to retrieve this information from Drupal and use it in a Views. I would like to rank the organic groups according to the number of Likes clicked for each... I figure out I would need some kind of integration with Facebook... Is there any kind of module that will allow an intregration between Drupal and Facebook for this specific functionality? I have been using Janrain for logging users, but as far as I know, it won't provide this kind of integration I am talking about... Or maybe some Views-Facebook, or even Flags-Facebook integration where I could associate Likes with flags for a certain item...

Thank you.

# Answer
> 1 votes
This question recently came up at work (small world), my thoughts:

1. Render the Facebook like button using the XFBML version of the button
2. Attach a handler to the click event (see the docs)

> ```
> FB.Event.subscribe('edge.create',
>   function(response) {
>     // do some AJAX stuff here
>     alert('You liked the URL: ' + response);
>   }
> );
>
> ```

In the above callback, fire an AJAX request back to drupal, to update either a custom table, or alternatively you can use the core statistics table. If you wish to use the core statistics table (or even create your own table) you can leverage the code from my module https://drupal.org/project/statistics\_ajax

One advantage of using core statistics, is that it has views integration out of the box, although in saying that writing custom views data sources for your table is easy too.

---
Tags: organic-groups, social-network
---


# Question
Title: How do I use field_view_field inside a custom views .tpl?
I have a view set up that uses an image from a node, I have customized the views-view-field.tpl to change the url the image links to dependent on the content type. I am trying to print out the picture using field\_view\_field in the .tpl, but its just printing out "array". Here is what I'm working with.

```
<?php if ($row->node_type =='article'): ?>
<a href="http://www.someurl.com"><?php print field_view_field('node', $row, 'field_field_image');?></a>

```

What am I doing wrong? Thanks.

# Answer
Ok, so I figured it out. First I did a node load:

```
<?php $node = node_load($row->nid);?>

```

Then I had to wrap my `field_view_field` in a `drupal_render`, finally I added my image style name in the display parameter, like this:

```
<?php print drupal_render(field_view_field('node', $node, 'field_image', 'image_style'));?>

```
> 3 votes

# Answer
Print out the field using `print_r()`. You will probably find that there are safe and raw values at the very least and it will be most likely the safe value you want.

EDIT:

In the comments oobie11 points to Rendering Drupal 7 fields (the right way). Bookmark this :)

Looking at the documentation for field\_view\_field tells me that the second argument is the actual entity. I don't think for this purpose the `$row` variable counts as an entity. You will need to do a `node_load` first getting the nid from the `$row` and pass the returned node to `field_view_field`.
> 1 votes

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


# Question
Title: Which parameters should I pass to form_set_value()?
I am trying to update a value during the validate phase of a node form: When the custom validation error is fired, I empty one of the fields.

I am trying to use the following code.

```
function eventcheck_node_validate($node, $form, &$form_state) {
  if ($node->type == 'article') {
    if ((array_key_exists('endpoints',$node->field_event_choose['und'][0])) && (($node->field_event_title['und'][0]['value']<>'') || (isset($node->field_event['und'][0]['value'])))) {
      $form_set_value(???);
      $form_set_error('event_checker_group',t('Error message'));
    }
  }
}

```

I understand that the last parameter for `form_set_value()` is the same `$form_state` the validation handler gets. What are the `$element` and the `$value`?

I was trying a lot and apparently the desired value resides in `$form['field_name']['und'][0]['value']['#value']` and only there. When I try `form_set_value($form['field_name']['und'][0]['value']['#value'],'foo',$form_state)`, I get this error.

> Recoverable fatal error: Argument 2 passed to drupal\_array\_set\_nested\_value() must be an array, string given, called in /includes/form.inc on line 2436 and defined in drupal\_array\_set\_nested\_value()

I also tried the following code.

```
$newvalue = $form['field_name']['und'][0]['value'];
$newvalue['#value']='foo';
form_set_value($form['field_name']['und'][0]['value'],$newvalue,$form_state);

```

I get this error.

> Warning: mb\_strlen() expects parameter 1 to be string, array given in drupal\_strlen()

# Answer
> 13 votes
After a lot of debugging, I finally managed to make this work. The trick lies inside `$form['complete form']`. but first things first, how does `form_set_value()` work and what does it do?

### The `form_set_value()` function

As the documentation suggests:

> If you want to update the value of `$form['elem1']['elem2']`, which should be stored in `$form_state['values']['elem1']['elem2']`, you would set `$element['#parents'] = array('elem1','elem2')`.

Now what does that mean? In my case, I had a textfield called 'field\_event\_title', which is the name I gave it on creation. In `$form`, all fields have a sub-array in `$form['field_name']`, which in my case is `$form['field_event_title']`. This is where the submitted value also is stored. Since it is a textfield, Drupal maintains both the language and the delta \[question for editors: is this right?\] of the input data. So in fact, the value is not stored in `$form['field_name']['value']`, but in `$form['field_name']['und'][0]['value']` (`['und']=language; [0]=delta`). Note that "und" is the Drupal key for the default language of the site; if it is in German, then it would be "de"; however, in most cases it should be "und."

To actually change the value using `form_set_value()`, one is ought to invoke the function by writing:

```
form_set_value($form['field_name'], array('und' => array(0 => array('value' => 'foo'))), $form_state);

```

### Updating a form to repopulate it with different values than submitted (or clearing them)

Thus far, this was what Krister Andersson suggested, but that did not work in my case, since I wanted to clear fields once a custom validation error has been invoked. One would suspect that the form repopulates itself using the values inside `$form_state['values']` (which is actually the place where the values are stored, the actual place that gets updated when using `form_set_value()` and the place which generates the `$form` later), but that is not the case: It uses the values inside `$form_state['complete form']`, which is a 'copy' of `$form` (notice that it is spelled 'complete form', with a space, not an underscore).

Using `$form_state['complete form']['field_name']['und'][0]['value']['#value'] = 'foo';` is what updates the values that actually repopulate the form on a validation error. (Note: you can, as do I in my usecase, set it to `=NULL` to simply empty the field.)

### Summary

Where is the difference between `$form['field_name']` (e.g. updating through `form_set_value()`) and `$form['complete form']`? Well, the former updates the actual value, which then gets stored inside the database; the latter is being used to repopulate a form when it failed a validation.

# Answer
> 1 votes
I managed to get it working by doing this:

```
// hook_form_alter, check so it's the correct form and attach a validate function
function sample_form_alter(&$form,&$form_state,$form_id) {
  if ($form_id == "sample_dummy_node_form") {
    $form['#submit']['#validate'] = 'sample_dummy_node_form_validate';
  }
}

// validate function, wich just sets the `title` field to `tjoohooo` using `form_set_value`
function sample_dummy_node_form_validate($form, &$form_state) {
  $form['title']['#parents'] = array('title');
  form_set_value($form['title'],t('tjoohooo'), $form_state);
}

```

If you haven't done so already, you should have a look at the documentation `form_set_value`

*** EDIT ***

In you example I guess the code in your validate method should be:

```
function hook_node_validate($node,$form,&$form_state) {
  if (fancy_stuff){
    $form['field_name']['#parents'] = array('field_name');
    form_set_value($form['field_name'],t('foo'),$form_state);
  }
}

```

From the documentation for the parameters:

> $element: The form element that should have its value updated; in most cases you can just pass in the element from the $form array, although the only component that is actually used is '#parents'. If constructing yourself, set $element\['#parents'\] to be an array giving the path through the form array's keys to the element whose value you want to update. For instance, if you want to update the value of $form\['elem1'\]\['elem2'\], which should be stored in $form\_state\['values'\]\['elem1'\]\['elem2'\], you would set $element\['#parents'\] = array('elem1','elem2').

---
Tags: 7, forms
---


# Question
Title: How do I add a link to a menu from a module in Drupal 6?
I'm creating a drop down menu with nice menus, but I'm having a problem programatically adding a link to the menu from modules. I have defined the menu in the Administration section under Site Building \> Menus and can get it to work fine if I add a link manually, but I can't get any links from modules to show up. Here is my code from module\_menu():

```
  $items['node/%node/jobs'] = array(
    'title' => 'Jobs',
    'page callback' => 'job_applications_form',
    'page arguments' => array(1, 'node'),
    'access callback' => 'job_applications_user_access',
    'access arguments' => array('site_owner', 1),
    'menu_name' => 'menu-dealer-menu',
    'type' => MENU_NORMAL_ITEM,
  );

```

The menu's name is menu-dealer-menu. I am using Drupal 6, and upgrading to 7 is not an option right now, and won't be for the next couple of months.

# Answer
> 1 votes
You are using a wildcard in the path `node/%node/jobs`. If you want Drupal to show a menu link, you have to tell it how to figure out the %node argument. You can do it with a function named `node_to_arg`.

The function name, actually, is \[wildcard\]\_to\_arg. I suggest you change the wildcard to something different, since there are several menu paths with %node in it. If you relied on node\_load to return you a node object, you can just call it from \[wildcard\]\_load.

There is documentation on \[wildcard\]\_to\_arg and you can see how user\_uid\_optional\_to\_arg implements it for the `user/%user_uid_optional` path.

---
Tags: theming, routes, hooks
---


title: How can I use Pages in drupal 7?

text:
# Question
Title: How can I use Pages in drupal 7?
I am using Drupal 7.

I want to make different looking pages, but I can't do this because it is always using the main theme block regions, and I can't change my specific page elements. For example, I want to make a page that has a cartoon images and another page that has a movie images on the background, and the block regions can be reordered. I tried Pages in Structure menu, but I don't understand it. I created one page, and assigned it a URL, but I can't access the page with my URL, as it says "page not found."

# Answer
The Context module would help here. It allows make 'sections' within your site based on selection rules like the path, views or menus chosen etc. Using Context you can apply a CSS class to the body based on the current section and then make the background image change based on that.

Context also allows you to use alternative layouts and you to re-order blocks as needed, and there are many add-on modules for it to extend its abilities further.
> 3 votes

# Answer
You should create different templates for every section you need. Check this out. The comments also :)
> 1 votes

# Answer
I think you could reuse the solution I suggested here and use ThemeKey contrib module.
> 0 votes

---
Tags: blocks, 7
---


title: Flag lists alternative

text:
# Question
Title: Flag lists alternative
Is there any good way to let users create custom node lists? I'm using Drupal 6.

I've found the Flag Lists module, but it has not been fully released, yet.

Any idea would be helpful.

# Answer
I think you need the Node Queue module with the Smartqueue Per User.

Although it's not listed on the front page, you can now get the 6.x-2.x-dev version which does the multiple lists (or queues) per user.

I've also got a patch to make it work with the latest version of Node Queue.

This module might appear flaky because few sites use it and the issue queue is stale, but it really does work the way it's supposed to. We're using that 6.x-2.x-dev on a production site with premium content and it gives us NO problems whatsoever.
> 2 votes

---
Tags: 6
---


# Question
Title: Which function(s) actually create the physical resized image files?
By default, Drupal 7 ships with 3 images styles: thumbnail, medium, and large.

For example, I upload a image file ('abc.jpg') with the image field (I assume the field name is called 'image'); while I am creating an "Article" node, the image file will be uploaded and stored in "sites/default/files/field/image/abc.jpg," and a record of this uploaded file is saved into database in the "file\_managed" table.
By that time, the medium and large styles versions of "abc.jpg" is not yet created.

The teaser of the "Article" node displays the image field with the medium style.

Then, I navigate to the teaser viewmode of that node for the first time. The medium version of "abc.jpg" is generated, and sits in "sites/default/files/styles/medium/public/field/image/abc.jpg."

The default view is set to display the image using the "large" style.

I view the node using its default view, and the large version of "abc.jpg" is created in "sites/default/files/styles/large/public/field/image/abc.jpg."

Basically, the image upload is quite smart; when an image has been upload, Drupal won't create all the different styles version of that image. Drupal only creates the style of an image when you first browse to the view using that specific image style.

Which functions/hooks are creating the file for the styled images?

# Answer
The function that generates the image URL basing on the style is theme('image\_style'), which is called by theme('image\_formatter'), which then called from image\_field\_formatter\_view(); this function is the implementation of hook\_field\_formatter\_view(), the hook that in a field formatter outputs the content of the field in the view for the entity containing that field.

The image is only generated when you access its URL. I tried the following code:

```
theme("image_formatter", array("image_style" => "thumbnail", "item" => array("uri" => "test.png", "title" => "Image title", "alt" => "Alternative text")));

```

The output that I obtained is the following:

```
<img typeof="foaf:Image" src="http://tero.local/dr72/sites/default/files/styles/thumbnail/public/test.png" alt="Alternative text" title="Image title" />

```

If you look at the code of image\_menu(), you will find the following lines:

```
  $directory_path = file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath();
  $items[$directory_path . '/styles/%image_style'] = array(
    'title' => 'Generate image style',
    'page callback' => 'image_style_deliver',
    'page arguments' => array(count(explode('/', $directory_path)) + 1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

```

image\_style\_deliver() is the function that generates the image.
> 5 votes

---
Tags: 7, media, files
---


title: Ajax working on 1 page

text:
# Question
Title: Ajax working on 1 page
I have a form that is using ajax to filter from a dropdown to another dropdown and then I have ajax setup on the submit button to submit the whole form via ajax.

Everything works fine in the main module page, but the ajax does not work on other module pages.

I don't see any javascript errors in the console, and it seemed that all the javascript files related to drupal's ajax were loaded with the page.

What could the problem be?

Thanks!

**Update:**

I am using Drupal 7.9. The code that I am using to submit the form in ajax is:

```
$form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Transfer'),
        '#submit' => array('ajax_create_transaction_submit'),
        '#ajax' => array(
            'callback' => 'ajax_create_transaction_callback',
            'wrapper' => 'user_transfer_panel',
            'effect' => 'fade',
            'progress' => array(
                'type' => 'throbber',
                'message' => t('Processing transfer. Please wait...'),
            ),
        )
    );

```

This code is working but only on 1 page within my module.

# Answer
So the problem was that I have various pages in my module which are each separated in their respective files e.g. mymodule.module, mymodule.page2.inc, mymodule.page3.inc etc

The issue was that the form of the block was in mymodule.page2.inc so when the user navigated to page3 the methods of the form where not being loaded.

The solution was to copy all the form methods into mymodule.module since it is like the parent of all the pages, so then the methods were accessible from all the pages.
> 1 votes

---
Tags: ajax
---