# Question
Title: What would cause a Drupal site to display a 500 error or a blank page depending on browsers?
After moving a site to the final server, I cannot anymore access the site. When I go to the home page, I get a WSD on Firefox, and a 500 error on Google Chrome.

As it is a shared hosting, I cannot access the Apache error log, and I am wondering if anyone experienced that before. How did you find your way out of it?

# Answer
The article about The White Screen of Death (Completely Blank Page) is a good place to start.

Depending on your shared host, you can often get access to logs if you poke around your control panel, or they sometimes are copied into your home directory.

Since you explicitly mentioned shared hosting, your best best is to open a trouble ticket. They can tell you exactly what is wrong fairly easily.

If it is a true 500 error, then my guess is that one of these two lines in the .htaccess is causing the problem.

```
Options -Indexes
Options +FollowSymLinks

```

You can try commenting them out one at a time and see what happens. I suspect that your host has `AllowOverride` set to `None` and one of those is trying to set a non-default value that the host has set.
> 6 votes

# Answer
To answer your main question, nothing is making the server behave differently based on your browser - it's just the browsers displaying the results of a 500 error differently.

But, as for a solution to the underlying 500 error - other things to check;

PHP version - is the final server running a different version?

PHP memory limit
> 2 votes

---
Tags: 7, wsod
---


# Question
Title: content administration page not found, and user manager page not found
I don't know what did this...but now when I try and go to my content manager or my user manager I get a 'page not found' in the admin overlay.

.htaccess is ok and nothing has changed in the php.ini

Where do I look next?

also to note: admin/people/people is giving me Permission denied?! I am UID 1 obviously...

updated: the add content button is still there.. so im guessing this is some broken core module? I have tried replacing the core and it still is giving me the same thing. attached is a screeen

# Answer
> 4 votes
Admin\_views was turned on and not functioning causing the overridden admin url aliases it uses to throw this error.

After disabling, the admin screens returned to normal function.

# Answer
> 0 votes
I'm 99% confident the issue is not with the Drupal core code. Looking at the .htaccess file seems like the right path. The path to the 404 pages is not being resolved correctly and something at perhaps the Apache layer is standing in the way. Any chance you can try an install on a different server so you can have a point of reference.

---
Tags: 7
---


# Question
Title: Better way to associate ticket quantities with event dates?
I'm fairly new to events in Drupal 7 but I have at least spent a few days now investigating strategies for my use case. Unfortunately, I haven't found a single relevant piece of info.

I have some recurring events that need to have a remaining tickets number associated with each event date. Some of these events are literally movies in a museum and teachers need to be able to see how many tickets are available for each show time when selecting dates and times for their field trips. Thus, movie show times is a useful (and accurate) model for this issue.

Within a single event node it's simple enough to create multiple date fields and multiple remaining tickets fields for the event. However, I've not been able to figure out how to associate a given remaining tickets number with a specific event date. So far, I only have lists of unrelated dates and numbers.

The alternate "solution" I've come up with is to have an event description node and numerous distinct event date (show time) nodes. The event date (show time) nodes would contain the event date and the tickets remaining for that date. However, I can't think of a way of explicitly connecting the event date nodes to the relevant event description node other than also including the node id in the event date nodes (which, for other reasons, is far from ideal).

Does anyone more experienced with events know whether this explicit connection is even likely to be needed? Even better, can anyone point me in a less cumbersome direction (e.g., associating the tickets required numbers with the right dates, all in one node, instead of creating separate event date nodes)?

Thanks so much for any and all assistance you're able to give!!! James Baker

# Answer
If you want to continue down the road you are on now, having an event description node and separate event date nodes, I would recommend you take a look at the References module.

If you want to keep all information within one node for a given movie/event, perhaps take a look at the Field Collection module. The article Create Multigroups in Drupal 7 using Field Collections may assist you to accomplish this.
> 1 votes

---
Tags: entities, datetime
---


# Question
Title: How to remove "There is currently no content classified with this term." phrase?
I have multiple terms created and for each I have created direct links. However under the content this message is displayed (because there are no content linked to the node) :

> There is currently no content classified with this term.

How to get rid of it ?

I don't like the CSS solution `display:none`.

# Answer
A quick method is to edit the settings.php file, and add the following code:

```
$conf['locale_custom_strings_en'][''] = array(
  'There is currently no content classified with this term.' => '',
);

```

The settings.php file should already contains the code to populate the `$conf['locale_custom_strings_en']` array at the bottom, but it should be commented out.

An alternative is to use the String Overrides module.

I would use the first method if you only need to modify one string, or few other strings. The pros are that you don't need to install another module, and only people who can alter the file on the site can alter the default strings. The cons are that it works only for English, and that is not possible to delegate the task (as requires access to the files on the web server).

In the other cases, including the case you are not comfortable with altering files on the server (or you cannot do it for many reasons), I would use the module. The module also works for other languages, as reported in the project page.

> Locale support, allowing you to override strings in any language
> 7 votes

# Answer
Using `mytheme_preprocess(&$variables, $hook)` to override the `$variables['page']['content']['system_main']['no_content']` variable.

```
function mytheme_preprocess(&$variables, $hook) {
  if(isset($variables['page']['content']['system_main']['no_content'])) {
    unset($variables['page']['content']['system_main']['no_content']);
  }
}

```
> 9 votes

# Answer
You can use hook\_page\_alter to alter those pages.

You could also create your own callback for the term page, which calls the one taxonomy use by default and then alter the output if no results are present.

`hook_preprocess_page` should also be useful to alter the output of the term pages.
> 1 votes

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


# Question
Title: What happens when an email from webform fails to deliver?
If webform attempts to send an email but cannot connect to the smtp server, what happens to the email? Does it get dropped on the floor? Does it throw an error in a log? Does it try to resend later? Does it mark it somewhere as unsent?

# Answer
> 3 votes
It throws an error and drop it on floor like below:

```
Warning: mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in DefaultMailSystem->mail() (line 76 of \modules\system\system.mail.inc).
Unable to send e-mail. Contact the site administrator if the problem persists.
Warning: mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in DefaultMailSystem->mail() (line 76 of \modules\system\system.mail.inc).
Unable to send e-mail. Contact the site administrator if the problem persists.

```

---
Tags: webforms, emails
---


# Question
Title: Add a term under a vocabulary when a content of particulr type is added
I have a vocab like 'category'. I want to add terms under this dynamically i.e when a content of type 'category\_list' is added a term with this content title should be added under the 'category' vocab. Can this be done?

# Answer
> 1 votes
In short, "yes".

Using hook\_node\_insert() where you can assign a category term value programmatically. Note that this is an over-ride (hook) of the node creation process. Basically do a Googe search for Drupal 7 node creation programmatically", example: Guide to programmatic node creation in Drupal 7. Look for the details on "Term reference (taxonomy) field".

Note that this an advanced Drupal task that involves creating a custom module that's specific to your site. If you're not already familiar with this process of applying hook functions to alter default Drupal functionality then I suggest you do some research on basic Drupal requirements for custom module creation first.

Good luck and keep asking questions, you'll figure it out and might become a Drupal rock star in the process!

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


# Question
Title: How to specify a permission as an access argument?
As I understand for a menu access argument I must specify a permission.

So, let say there is a permission for "Profile: Create new content" that is enabled for authenticated users, and I would like to use this as my menu access check.

This is how I put it in my menu callback?

```
function mymodule_menu() {
  $items = array();

  $items['play'] = array(
    'title' => 'Play',
    'page callback' => 'play',
    'access arguments' => array('Profile: Create new content'),
    'type' => MENU_CALLBACK
  );

  return $items;
}

```

This does not work though, so how do I get the permission name used by the system?

# Answer
This is based on Drupal 6 but I doubt it has changed.

`access arguments` returns `true` if the user has the permission specified in the array, however, it does not make sure to create that permission if it doesn't exist. If you want to use a module specific permission you need to define it using hook\_permission (hook\_perm for D6). If there already exists a permission that will suit you needs you can simply call that instead, though.
> 1 votes

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


title: Drupal BIRT Integration

text:
# Question
Title: Drupal BIRT Integration
I want to integrate BIRT reporting tool with Drupal 6. Does anyone has an idea on how to do it? BIRT reporting tool basically runs on a Tomcat server.

# Answer
Searching for "brit drupal" produced:
> 3 votes

---
Tags: 6
---


# Question
Title: Defined variables losing value after using drupal_bootstrap
We're trying to use drupal\_bootstrap to be able to delete a drupal user when a user is inactivated in our internal (non-Drupal) system. It appears that all defined variables set prior to the bootstrap call are losing value as soon as the call is made. Here's the weird part: it only happens on our live server - everything runs perfectly on dev.

Here's the code; I've stuck a whole bunch of error\_log statements in so I can see exactly where the variables are disappearing.

```
//email address is empty; delete institute record - but not if it's user 0 or 1
if($institute_uid > 1) {
  error_log("institute uid right before bootstrapping drupal: $institute_uid");
  //previous line prints and the $institute_uid is correct

  //set the working directory to your Drupal root - necessary for delete user function
  chdir('/home/www/institute');

  //require the bootstrap include
  require_once './includes/bootstrap.inc';

  //Load Drupal
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
  //(loads everything, but doesn't render anything)

  error_log("institute uid immediately after bootstrap = $institute_uid");
  //previous line prints but the $institute_uid value is blank

  $test = "123";
  error_log("test = $test");
  //previous line prints and $test value is correct

  user_delete(array(), $institute_uid); //$vuid = institute_uid from new_people
  $body .= '<br />Institute account deleted';

}

```

Any ideas? We're new to the bootstrap stuff; maybe there's a server setting, or line in a .ini file somewhere in Drupal that needs to change on our live server?

# Answer
When "register\_globals" is enabled, Drupal unsets all global variables before boostrap.

Disable the "register\_globals" option in your live server.
> 7 votes

---
Tags: 6
---


# Question
Title: Creating a new content type places random options on the content type page
I've created a new content type with multiple radio buttons.

Like this:

> 1) Is this your first survey?
> o yes o no
> 2) Is the color yellow?
> o yes o no
> 3) Tomorrow is friday?
> o yes o no

But when I go to the content type page I see this:

> 1) Is this your first survey?
> o yes o no
> `>` Authoring information
> 2) Is the color yellow?
> o yes o no
> 3) Tomorrow is friday?
> o yes o no
> `>` Publishing options

The "Authoring Information" and "Publishing options" just appear randomly, and they don't exist in the "manage fields" area. Where are these options coming from?

# Answer
> 1 votes
Those options are shown to the administrator users by default; if you log in as a regular user, you don't see them. You can enable and disable them in permissions "node / administer content".

---
Tags: 6, entities, nodes
---


# Question
Title: Why don't external JS files load on mobile site built with jquerymobile/JQM?
I'm developing a site that uses the Mobile Tools module to switch between a "desktop" and "mobile" theme. The mobile theme is implemented using the jquerymobile module and s sub-theme of JQM theme.

Unfortunately, the mobile theme will not load any external javascript files that are inserted by other modules (Google Analytics, Facebook Connect). These work fine on the "desktop" theme, but just don't load at all on the mobile theme, so I'm not getting any Google Analytics stats for views on that theme, nor can I implement Facebook Connect login.

According to the jquerymobile docs, there are some issues with the loading of scripts because of the AJAX page loading feature in jquerymobile, but I've turned that off, so every page is its own complete page request.

I am using version 1.0b2 of the jquerymobile library, and gently hacked the jQuery Update module to provide version 1.6.2 of jQuery, since that is a requirement for that version of jquerymobile.

# Answer
The problem turned out to be that a call to the `in_array()` function in the jquerymobile module did not use the optional third parameter for strict type comparison, so array keys that were strings were getting cast to the integer zero when compared to another zero, and returning true.

The fix was to add the TRUE parameter to the call to `in_array`.

Here is a quick sample that proves the problem:

```
<?php

$haystack = array('foo', 'bar', 'baz', 'bat');

$needle = 0;

$test = in_array($needle, $haystack); // same as in_array($needle, $haystack, FALSE)

var_dump($test); // bool(true)

$test2 = in_array($needle, $haystack, TRUE);

var_dump($test2); // bool(false)

?>

```

Patch file is uploaded on the drupal.org issue.
> 1 votes

---
Tags: javascript, theming
---


title: /node - 404 or 301?

text:
# Question
Title: /node - 404 or 301?
All the suggestions I've seen for getting rid of that stupid /node page involve programmatically disabling it altogether. Is there a specific reason nobody suggests to 301 it to, say, the home page? It seems to me it'd be smarter to teach web crawlers not to visit the page than send them into a dead end.

# Answer
I think it only makes sense to use a 301 if you have already been using /node as a page other than the home page, so it has already been indexed by search engines. If you're building a new site, or if your site has been using /node only as front page, then it has not been indexed and you can safely tell users and search engines that the page does not exist.
> 4 votes

---
Tags: 6
---


title: View of nodes with no taxonomy term

text:
# Question
Title: View of nodes with no taxonomy term
How can I create a view of nodes that are not tagged with any taxonomy term? Note, terms will be added in time and I wont be able to update the view each time.

Thanks

# Answer
you create a filter for "Content: Has taxonomy term" and then select "Is empty (NULL)" as the operator.
> 2 votes

---
Tags: taxonomy-terms, views
---


# Question
Title: How can I quickly check Drupal 7 porting status of the contributed projects?
How can I quickly check Drupal 7 porting status of the contributed projects ?

Answers should also guide readers if

* a user is a *developer* and would like to help porting the most frequently needed Drupal contributed modules, or
* a user is a *website owner* and would like to assess a possible upgrade from Drupal 6 to Drupal 7.

# Answer
There is the Drupal 7 contributed project porting status website that uses data from the Upgrade Status module to show Drupal 7 porting status of the top 61 contributed projects.
> 0 votes

---
Tags: 7, migrations, updating
---


# Question
Title: Translating the months in the archive view
I need the months in views' default archive view to display in a different language, just changing the language in Drupal doesn't seem to be helping, string overrides in settings.php aren't doing the trick either. I also tried downloading and importing the views language file but that too has failed. Where can I make this change?

# Answer
> 1 votes
Well, if you have tried all those options, what if you try to replace the respective values from a common view template, using for example, preg\_replace() PHP functions, to change this values?

for example: Here is the part of views-view-unformatted.tpl.php when each result is printed:

```
<?php foreach ($rows as $id => $row): ?>
  <div class="<?php print $classes[$id]; ?>">
    <?php print $row; ?>
  </div>
<?php endforeach; ?>

```

you can use a custom `views-view-unformatted.tpl.php` specific to your view, and use `preg_replace()` to detect and replace any specific term in $row, according terms that you want. for example

```
<?php
$string = $row;
$patterns = array();
$patterns[0] = '/jan/';
$patterns[1] = '/feb/';
$patterns[2] = '/mar/';
$replacements = array();
$replacements[2] = 'othermar';
$replacements[1] = 'otherfeb';
$replacements[0] = 'otherjan';
echo preg_replace($patterns, $replacements, $string);
?>

```

see preg\_replace() to get more details. I guess that you can use Devel module to see impact of this way against your site performance.

I hope information be useful.

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


# Question
Title: Build gallery in drupal 7 in the way required
I have this requirement. I want some ideas before i start building this.

1. I need to have various categories of galleries i.e cricket, football, rugby. There are the main categories.
2. In the gallery home page i need to have a drop down of these categories. Once i select a category all albums under this category like under cricket -\> cricket1 -\> cricket2 should come up.
3. When i click on any of the album i.e cricket1 it should go to its own page and show all images under it.

Basically i have doubt like what all modules should i use and how should i go about this. 1 main thing i need is views and taxonomies. Can any1 give me some ideas how to go about this requirement.

# Answer
> 1 votes
If I understand well your question, I think that you can use:

> I need to have various categories of galleries i.e cricket, football, rugby. There are the main categories

Taxonomy to content type/s related. Documentation of Taxonomy http://drupal.org/documentation/modules/taxonomy

> In the gallery home page i need to have a drop down of these categories. Once i select a category all albums under this category like under cricket -\> cricket1 -\> cricket2 should come up.

Views with exposed filters (you can create a block to show view inside home page) Documentation of views http://drupal.org/documentation/modules/views

> When i click on any of the album i.e cricket1 it should go to its own page and show all images under it.

the same view results will address to your specific content.

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


# Question
Title: Change Number of Values in CCK Filefield/Upload
Using hook\_form\_alter(), how would I change the default of 1-10 then Unlimited, to 1-24 then Unlimited? CCK Only gives 1-10 as options before going to Unlimited and I need to have 1-24. I know this is possible using hook\_form\_alter() but I do not know the syntax of how to write that.

Any help is greatly appreciated!

# Answer
```
/**
 * Implementation of hook_form_alter().
 */
function YOURMODULENAME_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'content_field_edit_form') {
    $form['field']['multiple']['#options'] = array(1 => t('Unlimited'), 0 => 1) + drupal_map_assoc(range(2, 24));
  }
}

```
> 1 votes

---
Tags: entities, files
---


# Question
Title: Implementation of the Google Identity Toolkit (openid like)
I´m trying to weite a module that implements the folliwing google api http://code.google.com/apis/identitytoolkit/index.html

it´s kind of like the openid, uses external accounts from the api to allow users to login without having to register the anoying long register form and pass through all verification

I´m new to D7 and openid conpcepts, what i´ve tested was the openid module that comes with D7 and got very disapointed...

first of all I had to have an openid url then I had to create the user and aprove my validation link from my email in order to get logged in to my drupal

that´s useless... because I went through basicaly the same process

What I want is something similar as this StackExchange experience, I used my gmail account and got logged in, I only had to login to google and that was it...

Any ideeas from where to begin with the implementation ? I want to be able to sync automaticaly the users that will use the Google Id kit with Drupal, without asking too many questions.. because after all what I´m interested is them be able to leave a trail on my site but do encourage them to register easily...

update:

found on google documentation this page http://code.google.com/apis/identitytoolkit/v1/drupalsample.html

# Answer
> 0 votes
If you want to implement it in specific open source platform, please use Google Identity Toolkit Plugins. There is a plugin for opencart 1.4.x: http://www.opencart.com/index.php?route=extension/extension/info&extension\_id=3302

It only asks you for 3 installation steps without any coding work to make your dream become true! =)

Drupal plugin for it will be alive soon.

---
Tags: users, authentication-authorization
---


title: How to style the date module

text:
# Question
Title: How to style the date module
How can I style the Date Module as noted in the image below? Which hooks/functions would be involved?

Is there a better Date input widget for Drupal 7?

I'm using Drupal 7 and the Date module is currently 7.x-2.0-alpha4.

.

# Answer
> 2 votes
I'd have to see the html, but find the class that wraps each field (the border is applied to that) and use a float left with some right margin. Find what class wraps both of them and apply overflow:hidden to that. The fields should now look like what you want.

---
Tags: 7, datetime
---


title: Contextually modify views output?

text:
# Question
Title: Contextually modify views output?
On the front page, i'd like the views to output taxonomy differently than i would on a term page.

I know i could modify output using a tpl file indicated by devel\_themer; but i'm not certain how one would contextually change it.

How would i go about doing so with a preprocess function?
Is it even possible?

# Answer
you could just get the current page with request\_uri() and then use some logic to style a view on the home page differently.

Or just create a second view and use the front module to show that view on the home page.
> 1 votes

---
Tags: 7, theming
---


title: Automatically fill combobox in views

text:
# Question
Title: Automatically fill combobox in views
I have created views with a node type (Property) that has term reference to vocabulary (Cities). Vocabulary (Cities) has a terms in a hierarchical order (City-Street).

I need to do the views in which I have two combobox for vocabulary terms (City-Street) with the following behavior:

* When user select a City I would like to automatically fill the second combobox(Street).
* When user select City I need a list all of the streets for that terms. Now I have a list only when user select an item from combobox Street. I have tried the Hierarchical Select module and it didn't meet my needs.

Do I need to make my own module, and which hook or hooks to use, or is there another solution?

I hope that I was clear.

Best regards,

Goran

# Answer
Take a look at Hierarchical Select.
> 1 votes

---
Tags: views
---


title: How can I enable Global: PHP field

text:
# Question
Title: How can I enable Global: PHP field
I'm trying to add a PHP field to a view, but I cannot see how to activate it. Do I need a module?

I'm already using / viewing:

```
Global: View result counter
Global: Math expression (Math expression)
Global: Custom text (Custom text)

```

I'd like to know how I could add:

```
Global: PHP field

```

I think it exists because of Global:PHP field with SQL in output code.

# Answer
Just install the Views PHP module and you can now add a "Global: PHP field" to your views that can include PHP code. Quote from its project page:

> This module allows the admin account (user 1) to add fields, filters and sorts to views which use PHP code. It also supports additional accounts when the core PHP Filter module is enabled.
>
> **Note:** While this module allows you to directly use PHP inside views which may be useful for quick and easy solutions, it is highly advisable to use regular handlers and plugins when available (or even to create one yourself). Take note that filtering and sorting a view using PHP always has a considerable perfomance impact.
> 5 votes

# Answer
You'll need to provide more details. Without understanding your question the link to the "Views PHP" module does in fact

> "allow administrators to add fields, filters and sorts to views which use PHP code."

The trick is that you'll still need to understand the Views system to know what to add with your code. Note the authour of the module advises

> "it is highly advisable to use regular handlers and plugins when available (or even to create one yourself)."
> 2 votes

---
Tags: views, 7
---


# Question
Title: Register only via a specific e-mail domain
I need to allow users to register for a Drupal-6 site, but only if their email contains a specific domain. For example, only allow users with *whatever.com* in their email address to register; a user with the email *bob@whatever.com can register* for the site, but *bob@something.com cannot register for the site*.

Is there a module for this? If not, which file would the PHP need to be altered for this?

# Answer
the "user restrictions module" is supposed to offer that feature. But it doesn't seem ready for production yet. However you could use the code to write your own.

I also tried to do it with the rules module and setup a rule for the "event" "user: before saving account" with a condition "data comparison" on field "account:mail". Add "value contains" and use "@whatever.com" and then check the "negate" box. That will basically trigger the rule for all emails that don't contain @whatever.com.

However I couldn't find a way to stop the username from getting saved. If you use the event "user: after saving account" you can show an error to the user and block the account. It prevents the registration but shows a second message to your user "you'll get notified by the administrator". Not a great experience for your customers.
> 1 votes

# Answer
I just wrote a hook to do something similar:

```
function MYMODULE_form_user_register_form_alter(&$form, $form_state, $form_id) {
  if (!($form_id == 'user_register_form')) {
    return;
  }

//if form is submitted validate the input
if ($form_state['method'] == 'post' && isset($form_state['input']['name']) ){

  $username = $form_state['input']['name'];
  if (strlen($username) < 5 || strlen($username) > 20) {
    $error_msg = t('The username has to be between 5 and 20 characters long. ');
    form_set_error('name', $error_msg);

```
> 0 votes

---
Tags: users, emails
---


title: Drush on Windows 7 and WAMP

text:
# Question
Title: Drush on Windows 7 and WAMP
Is running DRUSH on a Windows 7 64 bit machine in a WAMP dev environment worth it? I've heard there are some speed and performance issues with this set up? Will I lose any functionality with this set up?

# Answer
Try the dev version at Drush-on-Windows-Installer GitHub.

Some key functionality, such as remote sql-sync, is not working yet. You could also try running drush under Linux using a Virtual Machine on your Windows box.
> 5 votes

# Answer
i found this excellent tutorial over the net long time ago , http://vimeo.com/15371661 its a bit old & before drush windows installer came out . in this tutorial there is fine explanation how to install the drush with all the necessary components from the command line .

i hope you & others will find this useful.
> 2 votes

---
Tags: drush
---


title: Custom page template for a node type?

text:
# Question
Title: Custom page template for a node type?
I am creating a custom theme, and I need different page layouts depending on the node types. I can't use the node--xxxxx.tpl.php template, because I need control on the page layout outside the content of the particular page.

How can I do this?

# Answer
> 7 votes
There's a module for that: the Context module is what you need.
You can do it with page-\[type\] via preprocess functions.

---
Tags: 7, theming
---


title: Node id of home page

text:
# Question
Title: Node id of home page
If I choose a node to be the home page, how can I get its node id in the page template?

Can `menu_get_item()` be used for this?

# Answer
@Oswald: thanks for pointing in the right direction. This snippet does exactly what I need:

```
$front_url = variable_get('site_frontpage', 'node');
$front_url = trim($front_url, '/');
$front = explode('/', $front_url);
if( $front[0]=='node' && ctype_digit($front[1]) ) {
  $front_nid = $front[1];
}
echo $front_nid;

```
> 4 votes

# Answer
The drupal path of the home page is stored in the drupal variable `site_frontpage`. You can access it using

```
$site_frontpage = variable_get('site_frontpage', 'node');

```

You can find out whether this is a node page using something like

```
list($first, $second) = explode('/', $site_frontpage, 2);
if ($first == 'node' && is_numeric($second)) {
  // It's a node page and the node id is stored in $second.
} else {
  // It's not a node page.
}

```
> 3 votes

---
Tags: nodes, routes
---


# Question
Title: How to set the value of a field when hidden from certain users/roles?
I have a field which I don't want to be displayed for certain users, however I still want a value to be entered for that field, which is extrapolated from other fields they enter data in.

In order to do this, I'm setting the field as hidden in `hook_form_alter`:

```
$form['field_target']['#type'] = 'hidden';

```

and then setting the value of the field from within a form\_validate function based on another field, such as:

```
$form_state['values']['field_target']['und']['0'] =
    $form_state['values']['field_source']['und']['0'];

```

And this works fine, unless I force a form validation error on field\_source. When I correct the validation error and submit again, I get a white screen with PHP Error:

```
PHP Fatal error:  Cannot create references to/from string offsets
    nor overloaded objects in includes/common.inc on line 6288

```

This error happens even if I comment out the setting of field\_target. However I can fix this error by removing the `[#type'] = 'hidden'` line and everything works fine, except that the field shows for all users.

Is there any way to fix my above approach, or is there a better way to achieve what I'm trying to do?

# Answer
> 3 votes
Ok it seems I can get around this error by setting:

```
$form['field_target']['#access'] = FALSE;

```

instead of `['#type'] = 'hidden';` and Drupal no longer freaks out.

If anybody has a better idea though I'll glady accept a different answer :)

---
Tags: 7, forms, hooks
---


title: List Drupal Revisions

text:
# Question
Title: List Drupal Revisions
I just discovered the revisions function of Drupal. I tried it and the new revisions are stored in the database. I expected to get a list of revisions on the edit node page. But i don't see anything like this.

Is it possible to list and switch between revisions from within the UI?

# Answer
> 3 votes
If you are viewing a node that has revisions enabled, there will be a tab which will show all revisions of the current node. If you want to see a list of all revisions on the site you could use Views to create a view of node revisions. Then you can even add filters on content types, creation date, etc to customize your list.

---
Tags: version-control
---


# Question
Title: Notice: Trying to get property of non-object
I have created a module, and I am trying to use the following code:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_state['view']->name == 'album1') {
    // ...
  }
  // ...
}

```

The line that causes the error is the following one:

```
if ($form_state['view']->name == 'album1') {

```

The error I get is the following one:

> Notice: Trying to get property of non-object in mymodule\_form\_alter() (line 15 of C:\xampp\htdocs\drupal\sites\all\modules\mymodule\mymodule.module).

# Answer
`$form_state['view']` is not defined for all the forms, and it is not a value set by Drupal core modules. Before to access `$form_state['view']->name` you should verify `$form_state['view']` is defined, and it is an object (and not an array, for example).
> 5 votes

---
Tags: 7, views, forms
---


# Question
Title: Display node through panels but limit/deny access directly
I have a panel that displays a webform node depending on the fulfillment of certain selection rules (visibility rules) within the panel. However, I want to be able to prevent access to the webform directly. I have tried to unpublish the node, but this affects the display in the panel as well.

Edit: I'd also like to avoid adding code into template files etc.

# Answer
By

> Edit: I'd also like to avoid adding code into template files etc.

do you mean that you want a existing module / UI only solution? If so, I can't help you with that.

If you don't mind doing a small custom module, this is a somewhat common task that has been answered a few times on this site, and the main SO site, under slightly different titles.

Essentially, you want to redirect a node page to another page or you want to not have a node every viewable on its own.

Two questions worth reading are

Redirect node type to a view

How to prevent access to Views-only content?

Those two solutions can be adapted to your needs.
> 1 votes

---
Tags: 6, panels, users
---


title: Update CCK fields on a User

text:
# Question
Title: Update CCK fields on a User
I'm working on a Drupal 6 project and we've added some fields to a user profile via CCK. What's the best way to update this information programmatically? When the user logs in I'm gathering some data from a 3rd party API that I need to update their user with. I've got the data, but the `global $user` object doesn't seem to have the extra fields.

# Answer
OK, the information is stored in the node associated with the user, and not the user itself.

You essentially need to query the database to find the node for the user, load it, edit the fields, and then save out the node.

It would roughly look like

```
$sql = "
  SELECT nid FROM {node}
  WHERE type = '%s' AND uid = %d AND status = %d
";

$nid = (int) db_result(db_query($sql, "profile", $user->uid, 1));

$node = node_load($nid);

$node->field_foo[0]["value"] = "foo";

node_save($node);

```

This is a copy/edit/paste from a project of mine, so error checking and other steps have been omitted, and the code may not run as-is.
> 0 votes

---
Tags: 6, entities, users
---


# Question
Title:  How do I set up user's "Favorite Tags" and "Ignored Tags" tag subscriptions?
This website shows user-specific **"Favorite Tags"** and **"Ignored Tags"** listing tags the user subscribed to. Based on these subscription lists, content is being sorted in "views".

* How do I let the users pick favorite tags?
* How do I create a "favorite tags" block like it is done on this site?
* How do I up Views to prioritize content assigned to subscribed tags?
* Is it possible to use a Flags-like module to assign flags to taxonomy terms?

# Answer
I would recommend using the Flag module to allow your users to pick "favorite tags". It is still in beta for D7 however.

Also, in the future you could look at the Flag Terms module to allow your users to flag taxonomy terms. That module is still in dev.

You can use Views to create lists of "favorite tags", etc.
> 2 votes

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


# Question
Title: Views: greater than a date expose filter
How can I only show the nodes that are greater or equal to the selected date from expose filter on views?

I'd like to have a dropdown/expose filter which allows me to select the nodes that their post dates are greater or equal to (past week, past month, past six month)

# Answer
In Views, add a filter of *Node: Post date*. You should see something like the image below (without example values changed):

Click *Expose* to have the filter exposed to your users, choose the operator *Is greater than or equal to* and choose how you want to filter the results (by inserting a date to be greater than or equal to or entering a value of "-6 months", etc). This won't present a dropdown, but it will certainly add the filter you need for your view.
> 1 votes

---
Tags: views
---


# Question
Title: I can't create a book under Internet Explorer 7
I can't create a book under Internet Explorer 7; when I click "add a new book" in Book outline, the browser shows, "To help protect your security, Internet Explorer blocked this site from downloading files to your computer. Click here for more options…."

When I click on "Download the file," the file name is "form8c01710d," and it contains `{ "status": false, "data": "" }`.

# Answer
Actually, it is an issue that continues into modern versions of IE as well.

If your site has the jQuery Update module running, http://drupal.org/node/860966 speaks of the issue; the real issue is found in comment #6.

The only reason I am following up on this post here is that it is has a high in Google search, and I figured others are looking for how to solve the issue.
> 1 votes

---
Tags: 6
---


# Question
Title: Drupal 7 node reference field formatter for nid
I'm working in Drupal 7 and using the reference module to attach an node reference to another node. I'm then using views to show some of that nodes fields. When I display the field for the node reference, I'm give the choice of formatting it as a title, title with link, or rendering out the whole node. All I really want to be able to do is render out the nid or the node rather than the title. There were a number of modules that did this in Drupal 6, anyone know how to do it in Drupal 7?

Thanks

# Answer
> 1 votes
having trouble creating the patch, here is what I did, added

```
'node_reference_nid' => array(
  'label'       => t('Nid'),
  'description' => t('Display the nid of the referenced node.'),
  'field types' => array('node_reference'),
),

```

to the node\_reference\_field\_formatter\_info() function also added

```
  case 'node_reference_nid':
  foreach ($items as $delta => $item) {
    if ($item['access']) {
      $node = $item['node'];
      $result[$delta] = array(
          '#markup' => check_plain($node->nid),
       );
      if (!$node->status) {
        $result[$delta]['#prefix'] = '<span class="node-unpublished">';
        $result[$delta]['#suffix'] = '</span>';
      }
    }
  }
  break;

```

to the node\_reference\_field\_formatter\_view() function

that's it, hope it helps

# Answer
> 0 votes
Found a way to do this by altering the node\_reference module within the references module. If anyone is interested in the patch let me know

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


# Question
Title: I need a Drupal workflow solution where I can edit live/published nodes and save without the edits going live until commited
I need a module or method that can allow a PUBLISHED node to be edited in the admin and saved without the changes being made live until it is committed.

Site Example: http://bit.ly/p70f7E

```
1. User with EDIT permission logs in and edits this page/node - They make a copy edit such as changing the title "Litman Gregory Launches Alternative Strategies Fund" to "Litman Gregory Has Launched the Alternative Strategies Fund" or some kind of edit.
2. The user cannot publish the change but can save the revision or checkout/checking the file.
3. User with PUBLISH permission logs in and checks the edits for accuracy and then hits publish.
4. The page/node never gets unpublished, but the edits are made in the back-end without updating the live copy.

```

Any ideas?

# Answer
Try the Workbench module. If I'm not mistaken you can make draft versions of nodes that have been published.

From the module page:

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

---
Tags: 7, workflows
---


# Question
Title: Hierarchy and taxonomies (like in the animal taxonomies)
Trying to figure out how to implement hierarchical taxonomies. For example, take animals. Animals belong to a family, a genus and a species. family being the least specific, and species being the most specific. It's easy enough to create three taxonomy vocabularies, but in this case, a species belongs to a genus and a genus belongs to a family, there should be some way to infer the family and genus from the species. Please let me know if this makes sense, and there is a way to do this.

# Answer
> 2 votes
You could try Taxonomy Manager module to quickly create tree of taxonomy nodes where each of taxonomy levels can be your family, genus, species and at the end animals. My suggestion is do not try to create separate taxonomy dictionaries , ie separate taxonomies for family, genus, species. Let's keep them all in one common taxonomy.

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


# Question
Title: How can I display empty text for an empty CCK field that is output in a node template
I am using a node-content\_type.tpl file to control the content display of a certain content-type. I am rendering the fields like so:

```
print $node->field_name[0]['value'];

```

I want to display some empty text if the field is empty so it doesn't show up blank. Is there a way to set empty text for all of the field of a content type so I don't have to check every field individually? Can I do this in a preprocess function in my theme's template.php file?

# Answer
I guess that these examples could be useful:

example 1:

```
$exampleArray1=array("a"=>"one","b"=>"two","c"=>"");

function walkingfunction(&$value,$key)
{
    if($value == ''){
    $value = "empty text";
    }
}
array_walk($exampleArray1,"walkingfunction");

print_r($exampleArray1);

```

Example 2:

```
$exampleArray2=array("a"=>"one","b"=>"two","c"=>"");

foreach($exampleArray2 as $key => &$value) {
    if($value === '') {
        $value = "empty text";
    }
}

print_r($exampleArray2);

```

for the two examples, the value of c now is `empty text`. `&` is used to get element as a reference to change it.

this is an example with a CCK field:

```
foreach ($field_test as $key => &$value) {
    if($value['view'] === '') {
        $value['view'] = "value is empty";
    }
}

```
> 0 votes

# Answer
You could use an if statement, to check for value, and if not print something else:

```
<?php
  if (!isset( $node->field_name[0]['value'] )) {
    print t('My empty text');
  } else {
    print $node->field_name[0]['value'];
  }
?>

```

But I think that if you print the whole field you don't need to do this. Use something like:

```
<?php print $node->field_name_rendered; ?>

```
> 0 votes

---
Tags: 6, entities
---


# Question
Title: How would you implement a limited time featured node?
I am using Drupal 6.

I would like to create for a limited time (start date, end date) another version of a node that would share almost all its properties. This featured version is in fact a recipe sponsored by a company, so we have to put the company logo, etc.

About the only thing that would change is a couple of line of data, another category (keeping the other ones) and the main image.

An exemple of the node I want to create a featured version is here : http://www.moietcie.ca/cuisine/recettes/entrees-et-amuse-gueules/acras-de-morue

The big difficulty is to have the possibility to create a *temporary* version. After the date is passed, it must return to normal. Hence, I must keep all the data of the normal version.

I first thought of hijacking the translation system since we don’t use translations and force a fake language: French — Featured. Content without this translation would fallback to French (the normal version).

I did some quick tests, and beside the fact that my admin menu is now in English, it works but I hate my idea. I have to modify core modules of Drupal and I know this is bound to fail at some point.

Do you have any ideas ?

Thanks a lot

# Answer
> 1 votes
I would do the following, but it assume that you use Panels.

1. Create a panel page.
2. Add your first node as Content. Add a Visibility rule, choose PHP, and add in code that checks your date range based on the current time.
3. Add your second node as Content. Add a Visibility rule, choose PHP, and add in inverse of the code above.

I wouldn't be surprised if you can also accomplish this with the Scheduler module, but I am not sure how the URL would be handled in this scenario.

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


# Question
Title: Printing views exposed sort criteria separately to exposed filters
Exposed filters are either: \- Printed in views-view.tpl.php using the $exposed variable. \- Printed in a block, probably using the same variable.

This variable ($exposed) contains the exposed sort criteria and filters. I would like to find a way to print them separately. Ideally there would be a way to use something like:

```
<div id="sort"><?php print $exposed->sort; ?></div>
<div id="filter"><?php print $exposed->filter; ?></div>

```

Does anyone know of a way you can achieve this? Or in last case how to print each sort and criteria individually?

# Answer
> 0 votes
If you can not use each item of $widgets in separated way, you can `push` each widget in a separated array for use each widget across your custom html.

```
<?php foreach($widgets as $id => $widget): ?>
    <?php
    array_push($elements, $widget);
    ?>
<?php endforeach; ?>

<?php
echo $elements[0]->widget;
echo $elements[1]->widget;
//etc
?>

```

---
Tags: 7, views
---


# Question
Title: How can I limit the number of upload files programmatically?
I need to limit the number of upload files programmatically because the max number of files is 10 or unlimited and I need 14 upload files. Is it possible? I found the Upload max files module, but my question is if it is possible, programmatically.

I have installed Drupal 6.

# Answer
The patch reported in Add a custom 'number of values' for 'multiple/ multi-value' field. (e.g. nodereference, image field) can be useful to solve your requirement. (It has been tested with Drupal 6.20.)
> 1 votes

# Answer
I assume you use filefield module for attachment, if so, use this:

```
/**
 * Implementation of hook_form_alter().
 */
function YOURMODULENAME_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'content_field_edit_form') {
    $form['field']['multiple']['#options'] = array(1 => t('Unlimited'), 0 => 1) + drupal_map_assoc(range(2, 14));
  }
}

```
> 1 votes

---
Tags: entities, files
---


# Question
Title: Webform updates CCK field, doesn't update in node edit
I have a CCK field used to track the number of volunteers needed for a specific position. Once someone signs up to volunteer for that position, the number needed is decreased by one.

The issue is that when I go to edit the original node, the # of volunteers needed is not updated with the new number from the database. I checked the database and I can see that the correct values are being written. They aren't being loaded into the node edit form.

It appears to be a caching issue since when I clear my cache the problem is corrected. Is there a way to fix this apart from turning off caching?

Thanks!

# Answer
I figured this out: The CCK field was being rewritten by a cached value instead of a value directly from the database. I told the form to query the database directly, and then it began working correctly.
> 4 votes

---
Tags: views, entities, caching, webforms
---


# Question
Title: Add link to topic list after new topic or comment submission
I would like that, when users submit a new topic or posts a reply in a forum, they would be redirected to the topics list.

How can I do this?

# Answer
> 2 votes
There's count of ways to do it, one of these: Rules module. Just add condition on node or comment adding, and add action for redirecting. For taking correct forum page of node or comment, I assume you should enable "php filter" and add php code that got forum taxonomy term and redirect to certain page.

---
Tags: 6, redirection, nodes
---


title: Is it worth to switch to InnoDB?

text:
# Question
Title: Is it worth to switch to InnoDB?
Is it worth to switch from MyIsam to InnoDB for a Drupal 7 site that has 2000 visits per day? Would it be worth if it has 10000 visits in the future?

How much faster can a site become with InnoDB if it has mostly reads and not writes? And how much if it has a lot of writes in the database?

I'm asking all this because some articles I have read are negative about InnoDB, and opinions are split.

So, does the generally spoken statement "InnoDB is better always" reflect reality?

# Answer
> 5 votes
The general rule of thumb was to use InnoDB to write intensive tables (due to its row locking nature) and MyISAM for the read-heavy loads. I have seen a few very busy sites fully on InnoDB running without any hiccups or drop in performance too.

Drupal 7 defaults to InnoDB as the database abstraction layer has been rewritten and immensely improved.

You could look into MariaDB which is a drop-in replacement for MySQL, faster and has extra engines. There is also Percona, another high performance replacement. They both address some of the downsides of InnoDB.

The reason I am listing the alternatives is that Oracle made a few very suspicious moves and it may be that pretty soon we won't be able to use MySQL for free. (see http://arstechnica.com/business/news/2011/09/oracle-may-fork-itself-with-recent-mysql-moves.ars)

If bigger changes are not viable/possible, I'd recommend making a clone of the site using InnoDB and load test it using tools like Apache Benchmark, siege, New Relic

---
Tags: database, performance
---


title: Permission to edit options per node

text:
# Question
Title: Permission to edit options per node
In a content type there are tabs at the bottom for publishing options, add menu item, url alias, comments, etc. You can set defaults/access to these options when you create the content type. But what if you want to give the superadmin access to these options but not a lower level admin? And do this on a per node basis?

For example, I don't want the lower level admin to change the URL alias, publishing settings, or the menu position on a top section node, ie xyz.com/about. But he can make a revision.

# Answer
The Override Node Options module looks like it would help you out. More details from the module's project page:

> The Override Node Options module allows permissions to be set to each field within the Authoring information and Publishing options field sets on the node form. It also allows selected field sets to be set as collapsed and / or collapsible.
> 1 votes

---
Tags: nodes, users
---


title: Views - Display grouped dates per node

text:
# Question
Title: Views - Display grouped dates per node
I have a Committee content type which has multiple meeting dates.

I'm trying to get a View that shows multiple Committees and meeting dates. Basically, like so:

```
Committee A
1/1/2012
2/1/2012

Committee B
1/2/2012
2/2/2012

```

Instead I get:

```
Committee A
1/1/2012

Committee A
2/1/2012

Committee B
1/2/2012

Committee B
12/2/2012

```

I have tried Group Multiple Fields, but the checkbox does not stay checked after I save. Any pointers much appreciated.

Thanks!

# Answer
There is a bug in the Date module. Found this in the Issues queue:

### Group Multiple Value functionality is broken, patch for review

in http://drupal.org/node/1086100

The patch in #2 there worked for me. Hope it gets rolled in, but in the meantime hope this saves someone else some time.
> 1 votes

---
Tags: 6, datetime, views
---


title: Multistep CCK module

text:
# Question
Title: Multistep CCK module
I was working with the Multistep module.

While working with this module I found that it creates a node of the corresponding CCK after the first step itself and then keeps editing the node. Is there any setting or any other method by which this can be stopped?

I want my CCK node to be created only after the last step of the multistep is finished. Is there any other way to acheive the required without using the module?

# Answer
On a recent drupal project I used multistep and ran into similar issues.

To work around this I used with drupal "workflow" states, to keep the incomplete forms as draft, and have users explicitly set the form to complete by changing the state on the last page.

We then rewrote all the drupal views that we used for reports, so that they filtered out any draft nodes or nodes with state not set.

You might also be able to change the state automatically, by hooking into node save and writing some code to check whether the user is on final page, and doing any extra checks to confirm that the node is completed and should be moved to a different state.

```
 $step = _multistep_get_current_step($type);

```

Do watch out that the multistep current\_step may be return 0 if the user or admin user viewing all steps on one page. Also watch out for loopholes where users can skip past steps onto final page without completing everything.

I realise for some applications that a lot of partially completed nodes is just untidy, but advantage for us was that our users could come back to partially completed forms and continue later, and that it also gave us an insight into how many people gave up part way through, all of this could be managed using normal drupal views to produce lists of items in draft state.
> 2 votes

# Answer
Maybe the Node Wizard module? From the project page:

> Form is submitted only at last step (not like multistep module do).
> 0 votes

---
Tags: forms
---


title: Organic Groups user sectioning

text:
# Question
Title: Organic Groups user sectioning
I have just set up a site working with Organic Groups. I am now adding users and user permissions.

I create a type called **group** which serves as the group node and **page** that serves as the group node content.

**The issue is I want my authenticated users to add new page content but only within groups I have assigned them to.**

Can anyone advice how I can do this?

# Answer
when your users post new "page" content they can select the associated group. You could make that a required field.
> 0 votes

---
Tags: organic-groups, users
---


# Question
Title: Getting the content type in Template.php
I am trying to get the content type to conditionally add JavaScript code/files to the template.

The code in template.php is the following one:

```
echo $node->type;

```

The same line in "node.tpl.php" is returning the content type. How do I get it to work in template.php?

# Answer
> 11 votes
You can put `hook_preprocess_node()` in your template.php.

```
function THEMENAME_preprocess_node(&$variables) {
  $node = $variables['node'];
  if ($node->type == 'your_type') {
    //Add the JavaScript file.
    drupal_add_js('/path/to/jsfile.js')
  }
}

```

# Answer
> 4 votes
The "template.php" file for a theme is the equivalent of a ".module" file for a module: It's a collection of functions that are invoked from Drupal in specific cases.

As you are referring to the "node.tpl.php" file, I guess you are adding a preprocess function in your theme. In that case, the variable to use inside `THEMENAME_preprocess_node()` is `$variables['node']`, which is the same variable available in `THEMENAME_preprocess_page()`.

---
Tags: 7, nodes, theming
---


title: Drupal 7 - databases other than mysql

text:
# Question
Title: Drupal 7 - databases other than mysql
I hear that Drupal can use not only MySQL but also Postgres, MariaDB, and MongoDB. (Please add here if it can use also some other database.)

Which of those databases have a great enough performance gain to justify switching? And how can I switch to the proposed database?

# Answer
> 7 votes
Out of the box, Drupal supports MySQL (or an equivalent such as MariaDB), PostgreSQL and SQLite for its *main* database. With additional drivers it also supports Microsoft SQL server and Oracle Database.

The MongoDB module can be used to off-load storage of things like cached data, fields (ie. most data for content, user, taxonomy terms, etc.) and sessions data from the *main* database to MongoDB. But MongoDB alone can not be used, you still need a SQL database. See NoSQL vs Other SQL Drupal Setups and its accepted answer for more information.

I'm not an expert, but except for SQLite, I'm not sure switching DB engine is a good way to get great performance gain. I guess each engine has its strengths and its own optimization tools. I guess great performance gains can be obtained in each of them, but you have to knows how to do it.

There are also others performance aspects to consider, such as caching layers (Varnish, Memcache, APC, etc.), clustering and Content Delivery Network for static files.

# Answer
> 3 votes
I don't think performance is a reason to use another database than MySQL/MariaDB. A typical reason for sqlite would be simplicity (runs within PHP, no external service required), a typical reason for prefering PostgreSQL/SQL Server/Oracle would be that you are already using it and have existing know-how and infrastructure for it.

There are many alternative ways to improve the performance, for example using a different cache backend (to get a large part of the load away from the database), optimizing your database (there is enough to find on this site and google about this topic), setting up slave servers to distribute the load across multiple servers and more.

That said, Drupal 7 works perfectly fine on PostgreSQL, Sqlite and I think it also runs well on SQL Server (although you might run into issues with contrib modules), no idea about Oracle.

---
Tags: 7, database
---


title: How do I tweak an image field markup?

text:
# Question
Title: How do I tweak an image field markup?
I have an image field that is set to link to content. Drupal makes this markup:

```
<a href="/content-page">
  <img src="http://mysite/sites/default/files/image.jpg">
</a>

```

Now I need to tweak the markup and add some styling, for example:

```
<a href="/content-page" style="border-style: none !important;">
  <img src="http://mysite/sites/default/files/image.jpg" style="border: none; outline: none;">
</a>

```

I want to add the inline CSS in this way because the page is for emailing.

What would be the best way to do this? I have tried:

1. Putting the markup into field--myfield.tpl.php and inserting variables, but the `$items` array doesn't give me clean image file or target URLs.
2. Using the Custom Formatters module, but it gives me AJAX errors for some reason and not sure it would do the job anyway.
3. I could use a preprocess function in template.php, but I am hot sure how.

# Answer
> 1 votes
For link, it's easy to provide in field--myfield.tpl.php:

```
$items[0]['#path']['options']['attributes'] = array('style'=>'border-style: none !important;');

```

But image doesn't have this, so you can miss upper code and rewrite formatter in template.php (add attributes there).

```
/**
 * Returns HTML for an image field formatter.
 *
 * @param $variables
 *   An associative array containing:
 *   - item: An array of image data.
 *   - image_style: An optional image style.
 *   - path: An array containing the link 'path' and link 'options'.
 *
 * @ingroup themeable
 */
function YOURTHEMENAME_image_formatter($variables) {
  $item = $variables['item'];
  $image = array(
    'path' => $item['uri'],
    'alt' => $item['alt'],
  );
  // Do not output an empty 'title' attribute.
  if (drupal_strlen($item['title']) > 0) {
    $image['title'] = $item['title'];
  }

  if ($variables['image_style']) {
    $image['style_name'] = $variables['image_style'];
    $output = theme('image_style', $image); // Here you should add attribute, check that it's your field.
  }
  else {
    $output = theme('image', $image);
  }

  if (!empty($variables['path']['path'])) {
    $path = $variables['path']['path'];
    $options = $variables['path']['options'];
    // When displaying an image inside a link, the html option must be TRUE.
    $options['html'] = TRUE;
    $output = l($output, $path, $options);  // Here you should add attribute, check that it's your field. Or just take upper code.
  }

  return $output;
}

```

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


# Question
Title: Taxonomy filter. List terms with ajax checkbox selection
I need help to make some filter. Block with taxonomy terms list and checkbox selection closure. Checkbox need to return all nodes categorized by selected terms on change. It has to be transparent for user (Ajax). Thanks!

# Answer
Use combination of next modules:
> 1 votes

---
Tags: taxonomy-terms, ajax
---


title: What is the best way to use Panels

text:
# Question
Title: What is the best way to use Panels
I have D6 and the Panels module installed.

I want to be able to control the entire page layout from within Drupal itself, without having to write any new code such as a template file etc

To achieve this, I create a very basic template file which includes the standard html, style, body elements etc and just:

```
<?php print $content; ?>

```

This works great, it allows me to for example create a Panel layout for different page layouts, but it also allows me to create full-page landing pages without header/footer etc

The only drawback is that for pages that dont have a Panels template, say for example the user login page, how do I then style/structure this page?

# Answer
> 2 votes
I found this article:

http://ykyuen.wordpress.com/2011/09/13/drupal-customized-user-registrationloginforgot-password-page-with-panel/

Which describes how to workaround this issue with Panels.

This worked well for me, didnt take long at all, but it seems a little hackish. If anybody knows a better way please let me know.

---
Tags: panels
---


# Question
Title: Page manager selection rules for a variant for the front page
I'm trying to make a Ctools page variant for the front page but I'm not sure of the of the selection rules I need to use to make it apply to the front page. I've tried making it apply to everything BUT any of the existing content types but that didn't work.

Does anyone know of a set of selection rules that can let me target the front page?

Thanks

# Answer
If fron page point to "node" (in Site information administering page), just change it to show some selected node (blank node for example), then edit this node in panels as you want, if you want list nodes, enable there views...
> 1 votes

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


title: Speeding up Views 2?

text:
# Question
Title: Speeding up Views 2?
How can I speed up my complex views? I don't want to remove functionality from my views to speed them up. Some of my views have 5 lefts joins. Is there anything I can do to optimize these queries?

Here's an example: http://i27.lulzimg.com/214ce7e242.png

Here's another one: http://i27.lulzimg.com/5c1d52ab2d.png

# Answer
You can try installing DB Tuner and/or run mysqltuner.pl and experiment with the suggestions.

**Edit to address the comments.**

In addition to trying to optimize the database itself, you can also copy/paste the SQL that Views generates and run the query manually with an EXPLAIN. This may shed some light on why the query is taking a while to run. You can then edit the view as needed, and potentially add some indexes that the above tools may not have identified.
> 1 votes

---
Tags: views, 6
---


# Question
Title: How to hide the title field in create content?
I have a type of content that I won't use the page title, I will have to use a taxonomy field (the titles will repeat), because it's a restaurant list with auto-complete.

Can I do it with hooks or something? I could copy some content from other field into the title if it's gonna be mandatory at submit..right?

How can I do it?

# Answer
> 5 votes
The Automatic Nodetitles module in conjunction with the Token module is perfect for this. From the project page:

> "auto\_nodetitle" is a small and efficient module that allows hiding of the content title field in the form. To prevent empty content title fields one can configure it to generate the title by a given pattern.
>
> When the token module is installed it's possible to use various node data for the auto generated title - e.g. use the text of a CCK field (since 5.x).
>
> Advanced users can also provide some PHP code, that is used for automatically generating an appropriate title.

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


# Question
Title: D7: jQuery script for creating 'active' links in menu system. (partially works)
This is such a pity D7 does not have by default active links sets in the menu system. I mean everyone likes to have a clue where he is in the site by the active state of the menu.

I wonder why there is no such default feature in Drupal7?

Now I tried to do this in jQuery like this (see below) but it only works for predictable URL like static pages (it doesn't work for menu links created out of taxonomy terms). If someone can help me make it work for all the links in the menu I would appreciate.

```
  <script type="text/javascript">
  /*Script for creating active links*/
  $(document).ready(function(){
   var currentURL = document.location.pathname;
   var activeTopLevelPageArray = currentURL.split('/');
   var activeTopLevelPage = activeTopLevelPageArray[1];

   // applying the class to what we find
   $('#header ul li a[href^=/'+activeTopLevelPage+']')
    .addClass('active');
   // now making the nav menu do what we want with styles for the active element
    $('#header #primary-menu ul li a.active:first')
    .addClass('current-main') // assign main active bg to active link
    .parent('li') // select the parent list item
      .addClass('active-trail'); // then assign a class to it for manipulation

    /* If there is no match, just activate the "home" menu item/tab */
    var isActive = $('#header #primary-menu li.active-trail').size();
    if (isActive < 1) {
    $('#header #primary-menu li:first').addClass('active-trail');
    }
});
  </script>

```

# Answer
> 0 votes
I'm pretty sure Drupal 7 does that for you out of the box. I can see, from my D7 site, I have first, last active-trail classes

```
<ul class="menu"><li class="first leaf"><a href="/opportunities" title="">Opportunities</a></li>
<li class="leaf active-trail"><a href="/organisations" title="" class="active-trail active">Organisations</a></li>
<li class="last leaf"><a href="/events" title="">Events</a></li>
</ul>

```

As can be seen above the LI have the class you require. Do you have any custom code, modules or theme functions causing this not to happen on your site?

---
Tags: 7, routes
---


# Question
Title: Is it possible to hide a field on a form without writing code?
there are good instructions on hiding a field using a hook.

Is there a simpler way of doing this? I would like to hide a term reference field on a node edit form but use the default value for it.

# Answer
If you simply want to hide the field and have the default value saved, you should be able to simply hide the field with CSS. Find the ID of the wrapper surrounding the field and set it to `display: none;`. Here is a working example from my D6 site:

```
#edit-field-vendor-sort-order-0-value-wrapper {
  display: none;
}

```
> 5 votes

---
Tags: 7, forms
---


# Question
Title: How can I have a URL like www.example.com/about?language=ja to set Japanese for the page?
I've enabled the Locale and Content Translation module but am having trouble understanding how to do something that it seems should be working.

Basically I have a page, we'll say '/about' and it's in English.

I click translate, I have a few languages enabled, so I click to add translation for Japanese. It brings up the interface for making a new page. I change some stuff to Japanese, and set the URL alias to be /about ('about') like the english page.

I've setup my language options to use the "Session" detection method.

The result I'm wanting to achieve, but not getting is to have:

```
www.example.com/about -- to go to english (this works)
www.example.com/about?language=ja -- to go to the Japanese translation, this does not work, it just loads up the English page.

```

It seems like this would be the normal functionality so I feel like I'm missing something here.

# Answer
> 1 votes
just to be sure: at admin/config/regional/language/admin\_language, enable "Session" Detection method make sure request/get parameter set to language make sure you have about page in 'ja' language

try to visit yoursite.com/?language=japanese, it should be translating interface/etc - this way you can check translation is working.

# Answer
> 0 votes
It seems the Content Translation module is out-dated and was replaced by Entity Translation. Content Translation doesn't seem to work with the Session Detection method (at least with URL Aliases), but Entity Translation works fine with it.

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


title: menu_link_save() fails

text:
# Question
Title: menu_link_save() fails
`menu_link_save()` fails; I'm manually updating "plid," "p1," and "depth."

```
$sql =  "UPDATE menu_links SET plid=" . $parent . ", depth=2, p1=" . $parent . ", p2=19072 WHERE mlid=" . $child->mlid ;
$query = Database::getConnection('default');
$query->query( $sql );

$sql =  "UPDATE menu_links SET has_children=1 WHERE mlid=" . $parent;
$query = Database::getConnection('default');
$query->query( $sql );

```

# Answer
In general, it's not safe to manipulate individual rows of the menu\_links table directly. Since it's a tree structure, changes in one row can affect other rows. You should use the API function menu\_link\_save.

If you have accidentally corrupted your tree, the following code should repair it (for Drupal 6):

```
// Recursively crawl menus and repair the tree structure.
menu_repair(0);
function menu_repair($parent) {
  $result = db_query("SELECT mlid from menu_links WHERE plid = %d", $parent);
  while ($row = db_fetch_object($result)) {
    print "repair: $row->mlid\n";
    $menu = menu_link_load($row->mlid);
    menu_link_save($menu);
    menu_repair($row->mlid);
  }
}

```
> 1 votes

---
Tags: routes
---


# Question
Title: How to prevent login if a condition is not met
I am working on a Drupal 6 site (which I did not make and am not in charge of the general IT architecture at this company).

The site is on an intranet and they regularly import all users from an external source to Drupal users. The requirement is to restrict access to a subset of the imported users.

So: When a user logs in if they are on the authorized list then proceed else deny access

I realize this isn't the most effective way of doing things and I would have done in differently, personally. But I am stuck having to do it this way.

What I have working so far:

* I have feeds and data modules to import a CSV of authorized users
* I am using `hook_user()` in my module to check if the user is on the authorized list

the problem:

I have all the above working but I can't figure out a clean way to log the user out or terminate the session when they are not found on the list. When I use this it causes errors:

```
function mymodule_user($op, &$edit, &$account, $category = NULL) {

  switch ($op) {
    case 'login':
        $strID = $account->uid;
        $strName = $account->name;
        if ($strID <> 1) {
            if (!mymodule_checkACL($strName)) {
                global $user;
                $user = array();
            }
        }
    break;
  }

```

Any better way than this? Sorry if the question seems a little basic, I'm new to this.

Thanks

# Answer
You can use `sess_destroy_uid($account->uid)`.

You might also consider blocking users during the import process; this is done by setting the "status" column to 0.
> 3 votes

---
Tags: hooks, users, security
---


# Question
Title: 'Notify user of new account' checkbox to be selected as default
What I am trying to do is have the 'Notify user of new account' checkbox selected as default when creating a new account.

I have been trying similar steps as to http://drupal.org/node/1059168 but the solution posted in the comments is for D7, I need it for D6.

Any ideas, on how I could change this code for D7

```
<?php

/* Hook form alter
 * Sets "notify user of new account" chosen by default
 */
 function YOURMODULE_form_alter(&$form, $form_state, $form_id){
  if ($form_id == 'user_register_form') {
     $form['account']['notify']['#default_value'] = TRUE;
  }
}
?>

```

to have it work with D6?

Or any helpful links I mat have missed would be greatly appreciated.

# Answer
> 1 votes
found here - http://drupal.org/node/1295268#comment-5060488

```
<?php
function MODULE_NAME_form_alter(&$form, $form_state, $form_id){
    if ($form_id == 'user_register') {
        $form['account']['notify']['#default_value'] = TRUE;
    }
}
?>

```

---
Tags: users, 6
---


# Question
Title: small php script used in drupal module not clear with arrays in php
Here is a small PHP code which I am not clear with.

```
/**
* Form for configurable Drupal action to beep multiple times
*/
function beep_multiple_beep_action_form($context) {
$form['beeps'] = array(
'#type' => 'textfield',
'#title' => t('Number of beeps'),
'#description' => t('Enter the number of times to beep when this action executes'),
'#default_value' => isset($context['beeps']) ? $context['beeps'] : '1',
'#required' => TRUE,
);
return $form;
}

```

In the above user defined function return $form what does it return? How do you access the individual elements of $form\['beeps'\] what is the significance of writing word beeps in square braces in $form\['beeps'\]

```
function beep_multiple_beep_action_validate($form, $form_state) {
        $beeps = $form_state['values']['beeps'];
        if (!is_int($beeps)) {
        form_set_error('beeps', t('Please enter a whole number between 0 and 10.'));
        }
        else if ((int) $beeps > 10 ) {
        form_set_error('beeps', t('That would be too annoying. Please choose fewer than 10
        beeps.'));
        } else if ((int) $beeps < 0) {
        form_set_error('beeps', t('That would likely create a black hole! Beeps must be a
        positive integer.'));
        }
}

```

In above code what is

```
$beeps = $form_state['values']['beeps'];

```

line doing?

# Answer
In your first section of code, that function is creating a form using Drupal's Form API and `$form['beeps']` contains the settings for a single form element, in this case a textfield.

The second function is the one is used to validate the form values and will display an error for any unacceptable value.

`$beeps = $form_state['values']['beeps']` fills the variable `$beeps` with the value of the "beeps" textfield from the form generated in the first function.
> 2 votes

---
Tags: hooks
---


# Question
Title: Access content at alias without redirecting to original content location
Is there a way to generate an alias for content WITHOUT having it redirect to the original content location and therefore preserve menu location?

For example - I have one node which is located at http://mysite.com/oranges but I'd also like to access it at http://mysite.com/apples WITHOUT being forwarded on to the original URL.

Is this possible? I know, from an SEO standpoint this is not ideal, but we are creating several groups of pages (sub-sites) and several of the sub-pages need to have the same content and it will be tedious to edit them one-by-one.

Is the only option here to create and embed blocks on the pages so that the content is unified?

# Answer
With the core module path you can do this:

> **Tips about URL aliases**
>
> Although it is possible to assign the same internal URL to multiple aliases, this is generally not a good idea for search engine rankings; Google, for example, penalises your site by dropping its rank if Google thinks that you are publishing duplicate content under multiple URLs (a form of web spamming).

I just tried to add 3 aliases on the same `node/123` and it works without any problem. Go to `Administer > Configuration > Search and metadata > URL aliases` or directly to `admin/config/search/path` to add a new alias and see the existing ones.
> 2 votes

# Answer
The front module has an "alias" option that does that for the homepage. You might be able to "extend" that module.
> 0 votes

---
Tags: blocks, path-aliases
---


# Question
Title: How can I enable my community to flag (report) bad content on my site?
I got a dev site with Drupal 7.

I want to give my visitors the ability to flag (report) content that is abusive or problematic.
I tried using the Flag module together with the Flag Abuse module.

The Flag Abuse module can reset (remove) the flag/reports only one time; after that, it removes the Flag/Report and the Reset Button (for administrators). That is very bad, and totally not practical. Imagine a bad user creates 2 accounts, adds content with account "A," and reports that content with account "B"; you as administrator will check the content, see whats wrong, fix it and press the reset button. After that, the report and reset buttons are gone. So the bad user can edit his content and nobody can report it to administrators. So that module is pretty useless.

Do you know a similar module to solve this problem? Or do you know how I can fix the reset button? I have managed to do the reset button appear multiple times, but I get a lot of errors: The button only works every 3rd time that is pressed.

# Answer
I made my own solution. Using Flags, Rules and Views.

I have also uploaded a video Tutorial on youtube explaining how to flag content and create a "Reset" action on content edition.

http://www.youtube.com/watch?v=b5xieuVf01E&list=PL1A89955CCEB73A09&feature=plpp
> 2 votes

---
Tags: 7, flags
---


title: Creating a basic trigger

text:
# Question
Title: Creating a basic trigger
After installing Drupal 7, I created 2 files (beep.module and beep.info).

```
/**
 * @file
 * Provide a simulated beep.
 */
function beep_beep() {
  watchdog('beep', 'Beep!');
}

/*
 * Implementation of hook_action_info().
 */
function beep_action_info () {
  return array(
    'beep_beep_action' => array(
      'type' => 'system',
      'label' => t('Beep annoyingly'),
      'configurable' => FALSE,
      'triggers' => array('node_view', 'node_insert', 'node_update', 'node_delete'),
    ),
    'beep_multiple_beep_action' => array(
      'type' => 'system',
      'label' => t('Beep multiple times'),
      'configurable' => TRUE,
      'triggers' => array('node_view', 'node_insert', 'node_update', 'node_delete'),
    ),
  );
}

/**
 * Simulate a beep. A Drupal action.
 */
function beep_beep_action() {
  beep_beep();
}

```

```
name = Beep
description = Simulates a system beep.
package = Pro Drupal Development
core = 7.x
files[] = beep.module

```

In http://localhost/drupal/?q=admin/structure/trigger/node I see "Beep annoyingly," but not "Beep multiple times."

Can anyone point out what I can doto see both?

# Answer
I see youhave a callback function `beep_beep_action()` but no `beep_multiple_beep_action()` have you forgotten it ?
> 2 votes

---
Tags: 7
---


# Question
Title: Making a view with a node reference argument
I have two content types, Contributor and Articles. The Articles content type has a node reference field linked to the Contributor, so when someone creates an Article they can select a Contributor to reference.

On the Contributor nodes, I'd like to have a block view that shows Articles linked to that Contributor. When I make the block view, how do I set up the argument, or is there a better way to do this?

# Answer
> 3 votes
you are almost there. Create a view with display type block for content type articles. Then add a contextual filter (called arguments in Drupal 6) and select the node reference field that links articles and contributors. Select "Provide default value" and "node ID from URL". You can also validate it to make sure it's of the type "contributor".

Give the block a name and then go to "structure/blocks" and assign that block to a region and have it show up for all content type "article".

---
Tags: nodes, views
---


# Question
Title: Basic question with respect to Drupal form API
I am learning the Drupal Form API. I am new to HTML and PHP also. I read in a book how to define a form in Drupal, where they used the following example:

```
/**
* Define a form.
*/
function formexample_nameform() {
  $form['user_name'] = array(
    '#title' => t('Your Name'),
    '#type' => 'textfield',
    '#description' => t('Please enter your name.'),
  );
}

```

What will the HTML equivalent of above example be? Similarly, to validate the form they did it as follows:

```
/**
 * Validate the form.
 */
function formexample_nameform_validate($form, &$form_state) {
  if ($form_state['values']['user_name'] == 'King Kong') {
    // We notify the form API that this field has failed validation.
    form_set_error('user_name',t('King Kong is not allowed to use this form.'));
  }
}

```

What will be HTML equivalent of both of these functions?

# Answer
If I understand well your question, you are reading a book that does not explain the relation between common html forms/behaviors facing same things in Drupal.

The html equivalent of your first function is a text field. An html example:

```
<label>User Name: </label>
<input type="text" value="" name="user_name">

```

see following guide for more information about text fields: http://www.tizag.com/htmlT/htmltextfields.php and other html form elements: http://www.tizag.com/htmlT/forms.php

And regarding your second function, (if I am not wrong) there is no equivalent in html4 for validations in a web page. a common ways is to use javascript (one example: http://www.tizag.com/javascriptT/javascriptform.php or server side languages/technics like php (one example: http://www.html-form-guide.com/php-form/php-form-validation.html). with html you can build forms, not validate forms.

one note, if you are interested in Drupal and forms, an alternative is build forms using CCK module http://drupal.org/project/cck (without coding) for Drupal 6, or just use Drupal 7.

Also, if you are new in Drupal, HTML and PHP, alternatively you can start to learn Drupal without coding or touch APIs, HTML and PHP http://drupal.org/documentation/customization/tutorials/beginners-cookbook (Drupal 6), http://drupal.org/node/1062604 (Drupal 7)
> 2 votes

# Answer
The HTML produced from the first function (the form builder) can be roughly seen checking the code for the theme functions, which are at least two: theme\_textfield(), and theme\_form(). The exact output can change basing on the theme being used, and third-party modules installed on the site.

For the validation handler, the function that adds the class for form fields with a validation error is \_form\_set\_error(), while the list of the validation error messages are set with form\_set\_error(), which uses the following snippet:

```
  if ($message) {
    drupal_set_message($message, 'error');
  }

```

The messages that are set with `drupal_set_message()` are then output with theme\_status\_messages().

Also in this case, the real output depends from the theme being used, and from other modules installed on the Drupal site; both can alter the output used for the rendering.
> 2 votes

---
Tags: forms
---


# Question
Title: How can I schedule change of the default front page?
I have a node being displayed on the front page, set at *admin/config/system/site-information* \> Frontpage.

**I need to change it to another node on specific date.**

It would be ideal if I could do that using views display of /frontpage + Promote node to frontpage. But i have a referenced by *nid* view inserted into the nodes of this content type (using Views Field) which does not show anymore if I use this method.

Thanks

# Answer
> 2 votes
I would add a date field to the node and then filter the view to only show the node scheduled for today. Point your front page to that view.

You'll need the date module.

---
Tags: 7, rules, nodes
---


# Question
Title: View showing related nodes before unrelated nodes
I'm trying to create a view, which will show constant number of nodes. I want it to show related nodes first, and after them (if there aren't enough related nodes) to show other nodes. As far as i understand, contextual filters will remove all the unrelated nodes and I can't find sort order which will promote related nodes to the top.

Is there any way of doing this with views?

# Answer
similarterms might fit your bill. If not, here is a comparison of 4 modules that show related content
> 0 votes

---
Tags: views
---


title: Get nid in views custom PHP argument

text:
# Question
Title: Get nid in views custom PHP argument
i want to limit node reference (autocomplete widget) based on one of CCK field on current node. So, i made view to limit results and in argument-\>Provide default argument-\>PHP Code. And write code like this:

```
$mynode = node_load(arg(1));
return $mynode->field_foo[0]['nid'];

```

But problem is in that arg(1) is not returning NID of current page but string 'autocomplete' (i guess it is name of function). (Didn't had luck with menu\_get\_object() either)

So how can i get NID of current node other than using ARG() in views custom PHP argument?

Can i reference directly on CCK field (yes, as I sad it is on samo page as autocomplete text-field)?

Thanks for help.

UPDATE: This is specific to autocomplete widget.

It works well with other widget types (select list, checkbox...)

# Answer
> 1 votes
If you want to have the current NID of the viewed page in your view, you should use the following:

In your view: At the Arguments section you select "Node:nid", in the configuration of this argument at "Action to take if argument is not present:" you can choose "Provide default argument" after that you choose "Node ID from URL".

And there you have your NID in your view.

# Answer
> 1 votes
Lets say if you have these fields in a node creation form. Like

1. Select Field
2. Auto-complete

And the auto-complete should show results based on the first field. Now you ll be using the auto-complete even before this node is created right? means the nid of the node will not be created yet.

Or is it like, the nid that you want to pass is that of the result in the 1st field ?

---
Tags: views
---


# Question
Title: How can I show comments on nodes displayed in a view?
I've got a content type with comments enabled for each node, and I've created a view that will just display all nodes of this type.

I'd like it for users to be able to add and view comments in this view. Currently, one solution is to set Row Style: Nodes, which gives me the full node and the comments; however I want to be able to tweak and control what is displayed on the node (such as shorten the date format, remove some fields).

The other alternative I've tried is to set Row Style: Field, which gives me control on what fields to display, but I can't see any way of getting comment functionality to appear.

What's the best way to address this problem?

# Answer
You can bring in the comment details of the nodes listed using Relationships. Relationships brings in comments related to the current item in the view result. Which will start showing up in the add fields selection list.

Another option would be the same as what Kirk suggested. Instead of changing the tpl it would be a better idea to use panels then.

Panels is capable of bringing in comments for the current node displayed. You can also theme them as required. Also you can create multiple variants of display for the node like how we have full view and teaser, you can have your own custom variant. which can be selected based on certain conditions.
> 1 votes

# Answer
My suggestion is that you use the 'node' display, but make changes to your node.tpl.php file in your theme. This will give you the results that you want, but it obviously won't be very point-and-click.
> 1 votes

---
Tags: views, 6, comments
---


# Question
Title: How may I show the top 4 most recent result and then randomize in Views?
I currently have a view; I would like to select the top 4 most recent nodes, and then display them in a random order.

I think it would work if they were all posted on the same day. I have a "sort by date," and then I am using the random seed module to randomize the results.

However, if they occurred on different days, the random does not take effect because it is sorting first by day.

Does anyone have any advice?

# Answer
I'm not sure if I understand your requirement correctly but you can the following:

1. Create a views of node (teaser, fields.. whatever you need)
2. Sort by date (following the granularity you need)
3. Add a "Global: Random" sorting
> 2 votes

# Answer
You can do it with two displays, one as your block/page and the other one as attachment, that you setup as attached to your first display.
The first is your normal display, with four most recent results; the attachment shows the results in random order.

The only tricky problem is to avoid the first nodes appear into the second display, but you can find many ways to achieve it.
> 1 votes

---
Tags: views
---


# Question
Title: How to create Embedded Media Field: Video with custom resolution per Views field
Is there a way to apply a custom resolution to an Embedded Media Field: Video at the time of building a View? Alternatively, a way to define more than the just the Full / Preview presets?

# Answer
You can set it in the `template_preprocess_node()`

depending on your view mode you can set the first element :

```
if ($vars['view_mode'] == "full") {

   $node->video_field_name[0]['#settings']['width'] = '300';
   $node->video_field_name[0]['#settings']['height'] = '150';

}

```

dont forget to set all elements, not just the first one

other settings you can set:

```
#settings
  controls (Boolean) TRUE
  width (String) 300
  height (String) 150
  download_link (Boolean) FALSE
  download_text (String) Download

```

**Edit**:

`template_preprocess_views_view_field` is what you need for views probably. there you can access to the $vars\['row'\] with all data you need. maybe you will need to rerender the field.

If this does not work there is a workaround: the embedded-media-field sets its settings in the drupal js-settings. get the js settings with `drupal_add_js()`, find the element `mediaelement` and set the settings manually.
> 3 votes

---
Tags: views, files
---


title: Freetagging with location?

text:
# Question
Title: Freetagging with location?
I want users to be searchable by their location. How do you add a free tagging widget type to a location field. Or, can GMAP/Location recognize every city as a term? Basically, how can users have location terms in their profile.

# Answer
> 1 votes
If you are talking about the location module you'll have a couple of barriers with profiles on D7. I think they are working on a fapi compatible version but it is not ready yet.

There is a D6 module (html5 user geolocation) which may provide a good starting point.

Given a location (lat long) the Google maps API can give you an address.

You can then just pick the administrative level you like and save that as a tag.

# Answer
> 1 votes
For free-tagging style, cite-based, geographic location of user, I would use a dedicated taxonomy vocabulary. With geographic location information attached to each term in the vocabulary. Taxonomy terms are entities, so like for many other entity types, you an attach fields to them. So the Geofield module can be used to attach this information.

With minor coding, it should be possible to provide an implementation of `hook_taxonomy_term_insert()` that automatically add geographic information to newly created cities (ie. term in the dedicated vocabulary) using some geocoding service, and/or the mark them as needing manual review and geocoding. This may even be possible without any coding using the (recent) Geocoder module. You can also import cities for your intended audience periodically with the Feeds module (but you may need to provide your own mapper for Geofield).

Another option is to directly adds geographic information to either user entities or user profile (using Profile2). For this, the Geofield module already provide some map-based input widgets, and geocoding through Geocoder.

---
Tags: 7, taxonomy-terms, users, location
---


title: Change arguments in view

text:
# Question
Title: Change arguments in view
I have a view with arguments in the page and attachment displays.

When I go to the view page, I see a list of arguments (links) because in "Action to take if argument is not present" I selected "Summary, sorted ascending."

How do I sort arguments (in this case is term) by weight? I don't see any option to do this. Where can I change the query "ORDER BY term ASC" to "ORDER BY weight ASC" in code?

When I click an argument, I have another page with a list of arguments again, because I have an attachment. How do I only show the argument name I have clicked?

# Answer
you are using drupal 6, or drupal 7?

If I understand well your questions:

you can change the query used to generate view results (Order BY, Where, etc) using query\_alter hook. here one example: Making a field sortable in Views

About weight of arguments, I think that you can control order of precedence in 'rearrange' option:

If your question is related with weight of taxonomy terms, in your View settings \> Add sort criteria \> Taxonomy: Weight seems will be useful to sort according weight of each term:

regarding shows argument clicked, you can get argument from the current url easily using `arg()` http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/arg/7:

example URL: `http://example.com/node/12345/edit`

in this example

`arg(0)` is `node`

`arg(1)` is `12345`

`arg(2)` is `edit`

here some experiences in Drupal forum to review, with or without using arg():

http://drupal.org/node/180589

http://drupal.org/node/283945

you can add a php code to get respective argument, for example using arg() in a view header or in a drupal php node/page/block:

`<?php echo arg(0); ?>` or `<?php echo arg(1); ?>` according your target argument.

I hope information be useful.
> 1 votes

---
Tags: views
---


title: Query for child nodes

text:
# Question
Title: Query for child nodes
On any node in Drupal 7, I want to show a list of its child nodes. How do I do this? I basically want to create my own navigation system.

I'm still unfamiliar with the terms in drupal 7. I establish the hierarchy of nodes via the following steps:

1. go to admin dashboard menu and click on "Add content"
2. select the "Page" content type
3. fill out the fields
4. under "Menu settings," I select "Provide menu link"
5. I choose the parent node under the "Parent item' drop-down menu
6. save and publish

# Answer
Out of the box, there is no concept of sub pages or child nodes in Drupal. What you refer to is the menu structure used for navigation. A node can have a menu items *linking* to it and menu items can be organized hierarchically. The system was not designed to create and define relation between nodes, but only for navigation. If you look at the API, there is no simple way to retrieve the children of a menu item.

The book module included in Drupal core can be used to create a hierarchical structure for nodes. There are other options such as the relation, references and node hierarchy modules.
> 1 votes

# Answer
I would look into using the Node Hierarchy module to manage the parent/child relationships, and then create a view that displays the child pages using the Views integration built into Node Hierarchy. This view could then be embedded in each parent using the Viewfield module.
> 0 votes

# Answer
The option "Menu settings-\>Provide menu link" is not creating a relation between nodes, it is just the reference to the menu system. If you want to make some reference between nodes you should use the References Module, but it probably not what you want.

before the navigation, you should concept a structure of your site, than you will see which is the easies to create your navigation.
> 0 votes

---
Tags: nodes, 7
---