# Question
Title: How to correctly specify image links in a content type?
How to correctly specify img src like inside a content like Basic page or Blog, which does not break even when site is accessed as http:/example.com/drupalsite or http://example.com/ and while accessing as http:/example.com/node/2 or http://example.com/path-auto-title ?

# Answer
> 1 votes
First set `$base_url` in your `settings.php` file in *sites/default/* directory. I am sure you are using ckeditor or some other editor. In editor setting use use relative URL for images and links. Make sure your Apache `mod_rewrite` or `rewrite_module` is enabled.

# Answer
> 0 votes
The img src should be saved relative to the domain. But this should be done automatically by Drupal if you upload a file for example with the upload field. How do you place images? Directly in WYSIWYG?

# Answer
> 0 votes
You can use `drupal_get_path_alias`

**Parameters**

**$path:** An internal Drupal path.

**$path\_language:** An optional language code to look up the path in.

**Return value**

An aliased path if one was found, or the original path if no alias was found.

---
Tags: path-aliases
---


# Question
Title: How can I format a cell to not wrap in a themed table with the Antonelli/Bartik theme?
I want to limit the text in a cell so it truncates whatever would be wrap to the next line. However, I want there to be a minimum width, so if a user is viewing the table on a phone oriented vertically it won't just show 1 or 2 characters because of the narrow width.

# Answer
one way would be setting the min-width in the css to some value. this would ensure no matter what device it is being viewed it will set this minimum width. google up for sum css trick.
> 2 votes

---
Tags: 7, theming
---


title: Foreign key for content type

text:
# Question
Title: Foreign key for content type
I have a content type named 'products' and every product have a unique vendor, so I want to add a field to the content type 'products' that allow me to chose the appropriate vendor from a list.

Is this possible without creating a custom module ? Can I create another content type 'vendors' and join the two content type ?

Thanks.

# Answer
> 3 votes
It is possible to reference content types from one another but not with the core field system. There are currently 3 modules that offer this functionality:

1. References
2. Entity Reference
3. Relation

I'll let you read the module pages yourself to decide which one is best for your use case.

Each of the modules provides a field type that you can attach to one content type to reference another. The fields behave just like any others in the system and so can have a static or unlimited cardinality.

# Answer
> 0 votes
may be you could go to structure-\> content type-\>product then edit product and click manage fields, you could add fields here. as already said above you should installed fileds, eninty modules first.

---
Tags: nodes
---


# Question
Title: How to theme single node differently to nodes in taxonomy list?
I'm editing node.tpl.php, to apply custom theming when the site displays single nodes.

However, if I browse for a certain taxonomy term, the list of nodes presented is also affected by my changes.

Is there a way to theme just the single node pages?

# Answer
> 1 votes
You have access to the `$page` variable in your template file; if the node is being displayed in a full page this variable will be `TRUE`, and `FALSE` otherwise.

If you look at the core node.tpl.php file you can see it too takes advantage of this:

```
<?php if (!$page): ?>
  <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?></a></h2>
<?php endif; ?>

```

That's used to only display a title on the node if it's *not* the main page display.

You also have access to a `$view_mode` variable if you want to be more specific about the particular view mode, e.g.:

```
<?php if ($view_mode == 'teaser'):
<?php // print something ?>
<?php endif; ?>

```

# Answer
> 0 votes
See same question here. Assign specific template to specific pages

See here Drupal 7 Theme Hook Suggestions

For nodes You can use

```
node--[type|nodeid].tpl.php
base template: node.tpl.php
Theme hook suggestions are made based on these factors,

```

listed from the most specific template to the least. Drupal will use the most specific template it finds:

```
node--nodeid.tpl.php
node--type.tpl.php
node.tpl.php

```

Also Drupal 6 Template Suggestions

To use same tpl for multiple pages you need to use theme\_preprocess\_node Like

function theme\_preprocess\_node(&$vars, $hook) { $node = $vars\['node'\]; if(in\_array($node-\>nid), $myuids) $vars\['template\_file'\] = 'your\_template\_file'; }

# Answer
> 0 votes
What version of Drupal? Take a look in the Theming Guide. Especially the Overview of theme files and Working with template suggestions. In the last link, you can see, when you install Theme Developer how the template file has to be named. The sum of all in D7: Drupal 7 Theme Hook Suggestions

---
Tags: theming
---


# Question
Title: Shared Drupal 7 core and shared contrib libraries & modules
I have a server and I run around 20 Drupal 7 websites. As I start to get more clients It's becoming increasingly more time consuming doing Drupal core and modules updates.

Is there any way to have a shared Drupal 7 core, libraries and modules (just the main ones that I use as standard like views, context, backup, libraries etc) so I can updated those once and it updates for ALL of my websites. Any site specific modules I would still like to keep seperate.

I'm running a linux server with WHM and cpanel for each account if that helps at all. I also have shell access to my sevrer.

*note: that each website is running as a different account on the server so each is an individual vhost.*

Any advice on how to manage this would be greatly appreciated

# Answer
1. You can symlink the same core into several drupal installs. This works cross vhost.
2. You can also run several sites on the same Drupal Core in a multi-site fashion. This however requires you to keep a single vhost, so you need to restructure the server config for this.

Note that I recommend *against* clustering to many sites. If you break a single core, you break all of them. So you would do well to run, say 5, sites per core. Obviously the number should be adjusted depending on how much resources they require and how many sites you run in total.
> 3 votes

---
Tags: 7
---


# Question
Title: How can I stop a message (displayed via drupal_set_message()) from being printed?
When a node is saved, the Location Taxonomize module by default prints a message if terms are created. This message is very confusing for my users so I want to remove it.

I found where the message is being displayed in the module's code:

```
/**
 * @param $items - an array of items ready to be taxonomized
 */
function location_taxonomize_taxonomize($items, $form, &$form_state) {
  $saved = 0;
  $tids = array();
  foreach ($items as $item) {
    $results = location_taxonomize_process_item($item);
    $saved += $results['saved'];
    $tids = array_merge($tids, $results['tids']);
  }
  if (!empty($tids)) {
    if (location_taxonomize_term_attach_enabled()) {
      location_taxonomize_term_attach($tids, $form, $form_state);
    }
  }
  $msg = t('Location taxonomize: @num new terms saved', array('@num' => $saved));
  drupal_set_message($msg);
  return array("saved" => $saved, "tids" => $tids);
}

```

Obviously I could just delete the line `drupal_set_message($msg);` but then I would have to do this every update and I would eventually forget. I'm still learning how to use hooks and I know that hooks can be used to remove form elements but what about status messages? Is it possible to stop the message from being displayed using hooks and if so, could you please give me some pointers about how to go about doing so?

# Answer
> 4 votes
I admit to not having used it before but the Disable Messages module looks like it would do the trick:

> Gives a site owner options to disable specific messages shown to end users.
>
> Features:
>
> * Filter out messages that match a full text string exactly.
> * Filter out messages that match a regular expression.
> * Permissions to specifically hide all messages of a given type from any role.
> * Disable all filtering for specific users.
> * Disable all filtering for specific paths.
> * Apply filtering only for specific paths.
> * Debug system to get messages in the HTML without showing it to the end users.

I think a regular expression would probably be best for this particular message (because of the replacement done using `t()`); something like this should work:

```
^Location taxonomize: [0-9]+ new terms saved$

```

---
Tags: hooks
---


title: Show only login page to guests

text:
# Question
Title: Show only login page to guests
When ever user comes to my website he should be greeted by a pop up or normal login page only. When he logs in whole website should open up to him. SO how do i do this ?

# Answer
There are just so many ways to skin this cat...

Another variant, that does not use panels:

1. Set all content types accessible only to Authenticated users.
2. Enabled "Per content node access control settings" for Page content type. ( Your settings may differe here.)
3. On login page node enable access for Anonymous users.

You could then use Login Destination to redirect users to home page after logging in.

* See also this answer that explains how to do this with views.

Another even simpler method requires just a little elbow grease and a bit of thinking but **no** additional module if done right. Consider the following code, that displays different content depending on if user is logged in:

```
<?php  global $user; ?>
<?php if ($user->uid) : ?>
  Welcome <?php print l($user->name,'user/'.$user->uid); ?>.   <?php print
l("Logout","logout"); ?>.
<?php else : ?>
  Welcome Guest. <?php print l("Login","user"); ?>/<?php print l("Register","user/register"); ?>.
<?php endif; ?>

```

So if you have a front-page template, using a conditional like above can give you two totally different outputs depending on the page.

Last but not least, another option I saw mentionned as being noteworthy is using the Role-Theme module, and again theming the authenthicated user with whatever differences you want.

Hope that helps, happy coding!
> 1 votes

# Answer
Two separate Panels everywhere variants, one with a selection rule "User is anonymous", the other with "User is authenticated", could accomplish this.
> 1 votes

# Answer
This is a slight variation on @Letharion's answer, but I just did this for a client.

First, remove all permissions from the Anonymous user.

Then, install Panels.

Make a panel page that is only available to the Anonymous user, and put the login form on it.

Set up the global 403 page to point to this page.

Make two panel variants for the home page. The Authenticated user sees the normal front page. The Anonymous user just sees the login form and some sort of message (using custom content).

This worked well on the site I just retrofitted. This is one of the reasons I use Panels from the get-go; it makes changes like this pretty trivial to make.
> 1 votes

---
Tags: 6
---


# Question
Title: Overriding page.tpl.php for a menu_hook page
I am trying to override template for a custom page I have in `hook_menu`.

```
 $items['announce_your_new_products'] = array(
    'title' => 'Announce Your New Products',
    'description' => 'Announce New Products.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('announce_new_product_form'),
    'access arguments' => array('access content'),
    'file' => 'view_new_products.pages.inc',
    'type' => MENU_CALLBACK,   );

```

I have read to override a specific node's page template is `page--node-[nid].tpl.php` and `page--announce_your_new_products.tpl.php`, with and without underscores, but since this doesn't have a nid I was hoping someone could point me in the right direction on how to achieve this. I have tried `page--node-announce_your_new_prodcts.tpl.php` but it doesn't seem to work. Thank you.

# Answer
You wouldn't need `node-` at the beginning of your template file name as your path isn't a node page. Going off the Drupal 7 Theme Hook Suggestions, the file should be called:

```
page--announce_your_new_products.tpl.php

```

If that doesn't work, try:

```
page--announce-your-new-products.tpl.php

```

Unfortunately the docs aren't very clear on which way will work.
> 5 votes

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


# Question
Title: How to hide revisions tab in quiz module?
I am using quiz module in one of my project.

The module seems to be excellent and it satisfies all my need.. thanks to the development team... http://drupal.org/project/quiz

In the mean time i need to do one additional task. And i am struggling with it..

**There is a tab called "Revisions" which will be enabled when some updates are done.**

According to my criteria the **"Revisions" tab should be hidden always**... Is there any way to do this...

Thanks in advance..

# Answer
> 3 votes
It is provided by the Diff module: Disable the new check-box on workflow settings, "Enable revisions page."

# Answer
> 1 votes
use the `hook_menu_alter()` function to disable the tab:

```
function {MODULENAME}_menu_alter(&$items){
  $items['player/score']['type'] = MENU_CALLBACK;
}

```

---
Tags: quiz
---


# Question
Title: How to put a view generated slideshow as a page background?
I need to create a homepage with a slideshow as a background. The slideshow shows images and texts. Similar to this one: enter link description here

What I've done:

1) I created a slideshow block with views

2) I put that block in the homepage

Now I spent some hours playing with css to put it in the background and making it fill the entire page. But with no results at all..

I'd like to know if is there module to make easier to accomplish this.

# Answer
> 3 votes
I'd recommend the Backgroundfield module with Views Slideshow. Create a View with display option Slideshow and the only field to display as your background field. Violá, no coding required.

---
Tags: blocks, theming
---


title: Display a video next to a quiz

text:
# Question
Title: Display a video next to a quiz
On my site I have a series of quizzes.

Each quiz has it's own video (an embedded Vimeo video).

The videos are on a custom content type called 'Video'.

I want to display the video next to the questions throughout the quiz.

I used the Entity Reference module and on the quiz node I referenced the video node.

I used page manager to display the video node next to the quiz. This was ok but when I started the quiz, the video disappeared.

I thought I could create a block with mini panels or with views and display the referenced node but I can't seem to get that to work.

Does anyone know how to display a node on a block that is being referenced by the current node? Or is there a way I can use page manager to display the video when the quiz is in progress?

I am using Drupal 7, and the Quiz module 7.4.

# Answer
> 2 votes
I worked out a way to do it.

Create a block with some custom PHP.

```
<?php

//Find current nid
if (arg(0) == 'node' && is_numeric(arg(1))) $nodeid = arg(1);

//Load that node
$node = node_load($nodeid);

//Get referenced entity if it exists
if (isset($node->field_videolink['und'][0]['target_id'])) {
    $refnid = $node->field_videolink['und'][0]['target_id'];

    //Now load that node
    $node2 = node_load($refnid);

    //Display the body
    print($node2->body['und'][0]['value']);
};

?>

```

The entity reference field is called 'videolink'. You should enable the block only for the quiz content type otherwise you'll get an error on the home page.

Apologies if the PHP is a little shoddy. I'm not an expert by any means.

---
Tags: entities, quiz
---


# Question
Title: Gaining access to hooks in contrib modules: Webform Validate
Imagine the scenario: You installed Webform and Webform Validation. You got a Webform. You set some validation rules. Say, question #1 must be answered "True" and #2 must be "False" or else you failed and you can't submit your form.

So then, you want to override the validation. But you don't want to change the validation criteria, just the actions. Instead of just tossing out a drupal\_set\_message for each one, you want to count up how many validated and how many didn't. You want to display to the user the correct validation condition for some, but not all, and you want to do it depending on the count.

So where does Webform hide its validation criteria once they've been set? Node\_load doesn't show them to you. The Webform API don't give you no love. Because they're stored away by a separate contrib module.

Where do you go?

# Answer
> 0 votes
Webform Validation can help you in this regard. And there is a way to define custom validation rules too through hook.

---
Tags: webforms, forms
---


# Question
Title: How can I show the drop-down lists for countries/administrative areas (from Addressfield) as exposed filters in Views?
When editing the values of addresses provided by the Addressfield module, selecting certain countries (e.g., the United States) automatically populates a drop-down list of states.

I would like to do the same thing in a View using exposed filters-- when a user selects a country using the exposed filter for country, it should make available a select box for administrative area (state/province).

Adding exposed filters for the country and administrative area do not generate drop-down lists; instead, I simply get a plain text field with the standard options- *is*, *contains*, etc.

By installing the Countries module, I can get a drop-down list of the countries (but not the administrative areas). How can I do this using only the Addressfield module?

Is there a pre-existing solution to make it work like it does on the edit page?

# Answer
As of right now, there is no such views integration in the Addressfield module, although the linked issue does include a discussion of possible directions to take to tackle the problem.
> 0 votes

---
Tags: views, entities
---


# Question
Title: Moving content from dev directory to production server
When developing websites for clients, each developer has all sites under a relative path in his htdocs dir:

* /client1site/
* /client2site/
* /clientsite/ and so on

Most links within the drupal installation, in content or image srcs have to be absolute to this path: /client1site/en/a-nice-article/ in order to work.

But when client 1's site goes to production, links stop to work because now the structure looks like www.client1site.com/en/a-nice-article.

The situation is general, in the sense that you can develop under a path /X/ and have to go to production under a path /Y/.

Can this be solved with an easy way without having to edit all content or image srcs by hand? Can some mod\_rewrite wizardry save the day?

# Answer
> 1 votes
Frankly, I have never suffered from any path reference issue that you are describing, speaking of managed files. As per unmanaged files, which laying around on the ftp server, that you may happen to refer to in raw code or WYSIWYG editors, make sure you don't use absolute paths starting with domain name. Check your WYSIWYG editor settings. Instead, you'd want to:

* use links starting with slash - I call them root links
* edit the settings.php file and provide an explicit URL of your current site root in the `$base_url` variable. This is what the root links will refer to as base. Thus, when you move your site to another domain, it should require just changing of that one value.

I'm not sure there is a tool to do global replacements of absolute path you might already have. You could however dig into database and do a global search on it.

# Answer
> 1 votes
There is a module that can help with this situation. The Pathologic module is (from the module's page)

> an input filter which can correct paths in links and images in your Drupal content in situations which would otherwise cause them to “break;” for example, if the URL of the site changes, or the content was moved to a different server. Pathologic can also solve the problem of missing images and broken links in your site’s RSS feeds.

Basically, once you set it up (slightly more difficult than the average module but documented well) it works silently in the background and keeps your links working properly. Warning: as noted on the project page, it has some issues with multilingual sites.

# Answer
> 1 votes
WYSIWYG editors usually do so by hard coding the absolute urls when images are inserted using them. This can be overcome by pathlogic module as Patrick Kenny suggested, that works as input filter to change the domain in content with the current on which the Drupal instance is configured.

But always make sure

* to use relative paths
* to generate URLs by url() or `l()` function even if to generate absolute paths (see documentation)
* to append `$base_path` or `base_path()`. By default it is '/' but when Drupal is configured in some sub directory it will reflect the change e.g. `/subdir/`

---
Tags: navigation, installation, staging
---


# Question
Title: How can I concatenate two fields in a view?
I have a view set up to use the unformatted list type. I'm pulling in about 10 different fields, but would like to concatenate two of them onto a single line in the display. Is this possible?

Example: fields are Content: Session Number, Content: Title, Content: DateTime, Content: Speaker. Right now, all of them render onto separate lines. I'd like for the Session Number and Title to be concatenated onto a single line, so I get S3 | My Session Title.

# Answer
Let's say you have field A, and field B.

1. Make sure A, comes *before* B in the fields list.
2. Edit field A, and check "Exclude from display". The field will now no longer show up.
3. Edit field B, find the checkbox for "Re-write the output of this field".
4. Below the new textbox, find "Replacement patterns." There you should now be able to find something that looks like \[field-A\], and \[field-B\], with possibly many more options.
5. Enter "\[field-A\] \[field-B\]" as the replacement pattern.

And you should have the fields concatenated.

There are some situation, where the markup generated by Views with this configuration is not desirable, as you will now have A "inside" B. If that's a problem, one can add a completely new dummy field, of type "Global: text", and to steps 3, 4 and 5 on that field instead.
> 32 votes

---
Tags: 7, views
---


# Question
Title: Hook_view_pre_render(&$view) to alter field_title link locations
I have a function in a custom module:

```
function mashavumodule_views_pre_render(&$view) {
    dsm($view);
}

```

After clearing the cache, I had a dump of $view but know my question is:

If I want to alter the location the the field\_title links to, what part of the $view array should I alter and is hook\_views\_pre\_render the best hook to use to do this?

# Answer
You don't specify what type of changes you want to make, but in general, yes, hook\_views\_pre\_render is a good place to change the way the View looks when actually rendered.

You will find the hits from views in `$view->results`, and that is where you will want to make changes.

Note though that you may not even need the hook, you can use replacement patterns, as in this answer to accomplish many simple, and some advanced, changes to fields.
> 2 votes

---
Tags: 7, views, hooks
---


title: Receiving XML Posted data

text:
# Question
Title: Receiving XML Posted data
I have a question about what would be the best way for a module to accept a posted XML file via a web service. What I am trying to do is receive the file, read through the contents of the file, and update a setting on my site via the contents of the file. Could some one point me in the right direction?

# Answer
Here is the cURL solution.

```
//login curl
$crl = curl_init();
$url = "http://************.localhost:8080/user/login";
curl_setopt($crl, CURLOPT_URL, $url);
curl_setopt($crl, CURLOPT_COOKIEFILE, "/tmp/cookie.txt");
curl_setopt($crl, CURLOPT_COOKIEJAR, "/tmp/cookie.txt");
curl_setopt($crl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($crl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($crl, CURLOPT_POST, 1);
//Drupal login credentials
$postdata = array(
  "name" => "restuser",
  "passw" => "*******",
  "form_id" => "user_login",
  "op" => "Log in",
);

//Tell cURL to use post data
curl_setopt ($crl, CURLOPT_POSTFIELDS, $postdata);

$result = curl_exec($crl);
$header_code = curl_getinfo($crl, CURLINFO_HTTP_CODE);
if ($header_code != 200) {
    die("Cannot login.");
    echo 'Connection Died';
}else{
       if (file_exists('order.xml')) {
            $xml_data_before_encode = simplexml_load_file('order.xml');
            $xml_data_post_data = preparePostFields($xml_data_before_encode) ;

            $URL = 'http://*******.localhost:8080/users/restuser/12345';
            $crl = curl_init($URL);
            curl_setopt($crl, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($crl, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($crl, CURLOPT_POST, 1);
            curl_setopt($crl, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
            curl_setopt($crl, CURLOPT_POSTFIELDS, "$xml_data_post_data");
            curl_setopt($crl, CURLOPT_RETURNTRANSFER, 1);
            echo $output = curl_exec($crl);
            curl_close($crl);
       }else{
            print 'Second cURL request did not fire.';
       }

```

} function preparePostFields($array) {

```
  $params = array();

  foreach ($array as $key => $value) {
     $params[] = $key . '=' . urlencode($value);
  }
  return implode('&', $params);

```

}
> 0 votes

# Answer
This isn't something I've tried myself, but if you create a form with a file element, you should be able to control the $\_POST\['id'\] that Drupal looks for by manipulating the id of the file-element.

That way the file should get passed on to the forms submit function, and then you can do whatever you want with it's content and react accordingly afterwards.
> 1 votes

# Answer
While I haven't used it for your exact situation, you should take a look at the Services module. The module is rather well documented, and has examples. Creating an endpoint and wiring up your callbacks should be fairly easy.
> 0 votes

---
Tags: 8
---


# Question
Title: After crash I can't access certain sections nor login to site
I'm working on localhost. After saving a view the loading icon kept going for about 15 minutes. I changed over to other admin sections and they were fine, but after coming back to the original view the loading icon was still there. My clever answer was to log out and log back in to see if this fixed it. Oh terrible mistake, now I can't log back in, the page stays loading for a long time until finally returning a blank page. Being logged out I can still view the site's sections EXCEPT the view that crashed, that page just hangs.

I'm on a tight schedule so reinstalling would be my last option. Anyone has experienced this, how can I fix it from 'outside'? I'd appreciate any help, I'm growing desperate.

Thank you.

EDIT \[SOLVED\]:

Not much of a solution but I ended up restoring the DB with a backup file (luckily I had backed it up early today!) and the site works fine again. I couldn't post this as an answer because I don't have enough reputation.

# Answer
My fix was to re-install the database from a backup I did. Not exactly a solution to the problem but it worked :)
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to display users associated with a node through Views
I would like to create a View that displays users associated with a certain nid.

Under contextual filters, I have checked Content: Nid and selected

```
Provide a default value - Content ID from URL

```

Under Relationship, I have selected

```
Entity Reference: Referencing entity

```

Then under Fields, I have selected

```
(User referencing Content from field_office) User: First Name (First Name)
(User referencing Content from field_office) User: Last Name (Last Name)

```

But nothing is being displayed when I type in my nid into `Preview with contextual filters`

Essentially what I am trying to do is perform the following query:

```
$args = array(':nid' => $node->nid);
$results = db_query('SELECT USER_ID FROM USER INNER JOIN node ON USER.OFFICE_ID =
  node.title AND node.nid = :nid', $args);

```

I have done this before, but accidentally deleted the View. Now I am unable to make the View again, thought the DB structure has not changed at all.

Could someone please point out what I'm missing?

# Answer
It seems to me that since your node reference field is on your user object and you want to list users, all you have to do is:

* create a view listing Users
* add a contextual filter corresponding to your entity reference field. The entity reference field on the User should appear in the contextual filters list. Choose that one.
* Choose where the contextual filter value is coming from. If your view will be at `myview/nid`, where `nid` is the node id you want to use to filter, then you don't need to choose any other behavior. If you'll be displaying this view on a node page, use the default-\>content id from URL option.
* Choose your user name fields without relationships. There is no relationship needed unless you need to bring in fields *from the node being referenced*.
> 5 votes

---
Tags: 7, views
---


# Question
Title: How to disable the revision feature completely?
I've followed discussions here and on d.o about removing unneeded revisions tables.

How would I completely prevent any data from being written to the node\_revision and field\_revision\_\* tables?

# Answer
> 4 votes
Field SQL norevisions actually solves exactly that problem by

> Field SQL norevisions provides a field storage backend using SQL that does not create a revision table for each field.

I haven't tried it, but anything written by Alex Pott can probably be expected to work properly.

I assume however that this also goes for *all* entites as it changes the storage backend.

Without a new storage engine, the below is the original, less useful, answer:

The revision tables *must* be available, and they *must* contain data. Unfortunately, you just *cannot* get rid of them without completely breaking Field API, the reason being that the revision, contrary to their name, is *the* data storage.

Perhaps it's possible, with more database wizardry than I know, that you can set the regular field\_data\_\* tables to be mirrors of each revision table. That *might* work.

Other than that, I can't think of any solution that would do this.

**Edit:** While I don't know if this will have, "interesting", side effects, I asked the wizards if this was at all doable. Can I have one table be an alias or symlink to another?.

**Edit 2:** Actually, it seems like much wizardry isn't needed at all. One could try replacing the field\_data\_\* tables with a View that replicates the corresponding revision tables. Again, I haven't *tried* this, and my understanding of the interals of field api are a bit lacking, but it certainly *could* work.

**Edit 3:** (Yes, this is getting silly), someone pointed out that the above will cause the same data to be written twice, now to the *same* table. So it probably wont work anyway.

---
Tags: 7, nodes
---


# Question
Title: Drupal 7 errors after upgrading from 7.12 to 7.14
I just updated my drupal version from 7.12 to 7.14 and now I get these errors when trying to update/edit a content type:

```
Warning: array_merge() [function.array-merge]: Argument #1 is not an array in _form_set_class() (line 4134 of /var/www/vhosts/xxx/public_html/includes/form.inc).

Warning: implode() [function.implode]: Invalid arguments passed in theme_radios() (line 2809 of /var/www/vhosts/xxx/public_html/includes/form.inc).

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

```

Please note that this is happening when I edit the node not the actual content type definition. But only for this one particular content type. All the other work fine still.

If it's at all helpful here are the fields for that content type:

```
Title - title - Node module element

Photo - field_photo_image - Image - Image

Vote - field_photo_vote - Fivestar Rating - Stars (rated while viewing)

Domain access - domain - Domain Access settings.

Description - field_photo_description - Long text - Text area (multiple rows)

Author - field_photo_author Text - Text field

Admin selected - field_photo_winner - Boolean - Single on/off checkbox

```

Any help would be much appreciated.

C

# Answer
> 2 votes
I ran into the same issue and found the solution here: http://drupal.org/node/1427430

Do you happen to also have the opengraph\_meta module installed? If so just edit this file:

```
sites/[your-site]/modules/opengraph_meta/opengraph_meta.module

```

search for this line:

```
'#attributes' => array('class' => 'opengraph-thumbs-wrapper clearfix'),

```

and change it to look like this one:

```
'#attributes' => array('class' => array('opengraph-thumbs-wrapper','clearfix')),

```

# Answer
> 0 votes
I think that something has gone wrong with the update version. Are you sure you've followed step by step the upgrade guide ?

http://api.drupal.org/api/drupal/UPGRADE.txt/7

---
Tags: entities
---


# Question
Title: Drupal 7 - eRecruiter profile with Solr Fatal Errors
I just installed Drupal 7 using the eRecruiter profile release but I am gettig loads of errors. I know it's not me server as I run 10 other drupal site on my server and there is nothing showing up in the drupal logs.

These are the errors:

This one when I click in Job Search: `Fatal error: Call to a member function pre_execute() on a non-object in /var/www/vhosts/xxx/public_html/profiles/recruiter/modules/views/plugins/views_plugin_display.inc on line 2432`

This one when I click on Resume Search: `Fatal error: Call to a member function pre_execute() on a non-object in /var/www/vhosts/xxx/public_html/profiles/recruiter/modules/views/plugins/views_plugin_display.inc on line 2432`

And this when I click on My Resume: `Fatal error: Call to undefined function entity_i18n_string() in /var/www/vhosts/xxx/public_html/profiles/recruiter/modules/field_collection/field_collection.module on line 913`

I used the exact drupal and module releases that were included with the profile from here: http://epiqo.com/recruiter

I got the errors... did some searching on line and one person recomended updating Drupal and ALL the mondules. I did all the updates but the errors are still present.

I have installed Apache Solr and it's working fine and drupal says that it has found it.

I then tried to install it localy on my mac and I'm getting the same errors.

My `php_error.log` reported the following:

`[01-May-2012 17:50:28] PHP Fatal error: Access level to SearchApiViewsHandlerField::$additional_fields must be public (as in class views_handler_field) in /Users/xxx/Sites/vhosts/eRecruiter/profiles/recruiter/modules/search_api/contrib/search_api_views/includes/handler_field.inc on line 195`

and:

I get the same sort of log message when I click on Job search, Resume search and my resume.

Here's a link to the online demo version: http://drupaljobs.epiqo.com/

I'm desperatly needing help with this as I have spent hours search forums and blogs.. got me nowhere :( Any help will be much appreciated.

C

# Answer
> 1 votes
A lot of errors here, let's see if we can do something..

**Job/Resume Search**

```
Fatal error: Call to a member function pre_execute() on a non-object..

```

When you try to invoke the action, the result does not return the query object, and for that reason you have this error, for example.

**php\_error.log**

```
PHP Fatal error: Access level to SearchApiViewsHandlerField

```

Changing from protected to Public Field made solve this issue.

**My Resume**

```
Fatal error: Call to undefined function entity_i18n_string() in

```

Entity 7.x-1.x-dev released on February 28, 2012 - 08:13 no longer contains the function entity\_i18n\_string().

---
Tags: views, search
---


# Question
Title: How to set up Apache Solr with facets so that it uses a front page search form?
So I am working on my first mid sized D7 projects and it needs some rather advanced searching capabilities (at least advanced for me). I've installed Solr, created a server and an index with the Search API, and created a search page. So far so good... everything works according to what you'd expect, and it even has facets, which is something I really wanted for this site. The problem is that this seems to be pretty much my ceiling... and I would like to change some things. For instance:

1. I would like to be able to search through my indexed taxonomies. Right now I can only search the node titles and descriptions and I have a bunch of taxonomies which is what I really want to search through.
2. I would like the users to be able to search from a search form in my home. Right now the core search is all I have in my front page, and if I want to use the Solr server I have to go to my search page. Ideally I want the user to enter a search term in the search form, to be redirected to the results page, and just there for him to see all the facets to further filter the results... linkedin style.

How would you guys accomplish something like that?

Edit:

Seems it seems I haven't stated clearly what I intend to do I'll try to upload some pics regarding point 1:

admin/config/search/search\_api/index/node\_search/fields

These are the fields I choose to be indexed!

admin/config/search/search\_api/page/search/edit

If you see I can only choose "Title" and "description" from the fields to search from... so if I search for a taxonomy term which is not in any title or description, I get nothing. I would like to make the taxonomies in the first picture searchable... which is why I indexed them in the first place.

Edit 2:

I've finally managed to get the core search form to work with Solr following this tut(http://web3us.com/drupal6/how-create-web-site-handbook/apache-solr-drupal/apache-solr-3-drupal-7-turtorial-screen-shots) but I still don't know how to display the fields I want in the search results. Right now the results look like this:

And I would like each of them to look as the Teasers I've configured in my "Restaurant" content type (which are the nodes that I've set Solr to index)

# Answer
**Question #1:** Go to admin/config/search/apachesolr/settings and select 'Bias'. There you can set up the weights next to the terms you want to search through. Perhaps they're on 'Omit' or something like that...

**Question #2**: Go to the search settings page and make Apache solr search be your default search. That way, when users type in keywords in your regular search form, they will automatically use your apachesolr search. admin/config/search/settings

Let us know if that worked for you!
> 3 votes

---
Tags: search
---


title: themes diabled after core update

text:
# Question
Title: themes diabled after core update
Every time we update Drupal core our custom themes, all previously enabled and one set to default, are no longer enabled. Has anyone else experienced this or know why this would happen?

# Answer
> 0 votes
This is a known bug in Drupal core for 6.x and 7.x

---
Tags: 7, theming, updating
---


title: A newly created Page does not Display

text:
# Question
Title: A newly created Page does not Display
Below is my .module file, when i go to mysite/timeline/nodes there is no display. While what i am planning is to display a timeline . I am new to Drupal (and web development). I have other JS,JSON and PHP file in my module folder too to make the simile timeline script available to the code, if somebody needs to see that please tell. Also i have read that tpl.php provides sometype of solution (i havent read it much so i dont know how it does exactly) but i want to display the regular page theme and put content in the content area when using hook\_menu to create a new page.

```
function similetimeline_menu() {
$modulepath = drupal_get_path('module', 'similetimeline');
drupal_add_js($modulepath . '/similetimeline.js');

$items = array();
$items['timeline/nodes'] = array(
'page callback' => 'similetimeline_callback_nodes',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
$items['timeline/ratings'] = array(
'page callback' => 'similetimeline_callback_ratings',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}

function similetimeline_callback_nodes() {
$query = new EntityFieldQuery;

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', 1);

$results = $query->execute();
$output = array();
if (isset($results['node'])) {
$nodes = node_load_multiple(array_keys($results['node']));
foreach ($nodes as $nid => $node) {
  $output[$nid] = array(
    'title' => $node->title,
    'timestamp' => $node->created,
    'body' => $node->body[LANGUAGE_NONE][0]['safe_value'],
  );
 }
}
dpm($output);

global $base_path;
$timeline_lib_path = $base_path . libraries_get_path('simile_timeline');

// Set some global js variables that the library is going to need for proper inclusion and funcionality
$timeline_inline_js = "
var Timeline_ajax_url = '$timeline_lib_path/timeline_ajax/simile-ajax-api.js',
     Timeline_urlPrefix = '$timeline_lib_path/timeline_js/',
     Timeline_parameters = 'bundle=true';
";
drupal_add_js($timeline_inline_js, array('type' => 'inline', 'weight' => 10));

// Adding general timeline library
drupal_add_js("$timeline_lib_path/timeline_js/timeline-api.js", array('weight' => 11));

$html = '';
$html .= '<div id="my-timeline" style="height: 150px; border: 1px solid #aaa"></div>   <noscript>
 This page uses Javascript to show you a Timeline. Please enable Javascript in your browser to see the full page. Thank you.</noscript>';

 print theme('similetimeline', $html);
 return null;
 }

```

# Answer
> 0 votes
So continuing from the comments above.

You are calling `theme('similetimeline', $html);`, which in turn will call `theme_similetimeline($html)`. So the main reason you don't get any output, is simply that you lack the theming function.

To get started, you can do away with theme() all together and just `print $html;`. Especially since you've already generated the markup, but on the other hand, it's great that you've already gotten far enough to know you should use theme(), considering you say you are a beginner. The reason for theme calls, is that you can separate the module and it's functionality, from it's markup, meaning this timeline can look different in different themes.

You will find a more extensive example, and a great answer by Clive, in a similar question I asked recently.

---
Tags: hooks
---


# Question
Title: Creating custom bread crumb trails (Drupal 7)
How would one create a custom breadcrumb such as this:

For a given page such as a node or organic group page in Drupal 7?

# Answer
> 2 votes
I don't know anything about Organic Groups, otherwise I'm using Path breadcrumbs and Custom Breadcrumbs.

---
Tags: 7, breadcrumbs
---


title: Query other external databases

text:
# Question
Title: Query other external databases
I'm trying to query an other mysql database that has an completely other table-structure than drupal (no session, semantics table and so on). When trying to add the database to my config file I get these strange errors that I'm missing the semantics table.

I get the feeling that drupal is expecting that the other database is an also drupal database, which it is not..

My question is: how do I query and complete other other database (other user and table) the drupal way?

I already tried this but it gives the same problems: http://drupal.org/node/18429

# Answer
> 2 votes
It sounds like one of two things might be happening:

1. You're overwriting the default database (which needs to be the Drupal database) with your custom database.
2. You're calling API functions that interact with the Drupal database before switching back from your external db.

In either case these are abridged versions of the code from the docs page you linked to with a few comments that will hopefully help it to make more sense:

**Drupal 6**:

```
// Define the default database, this MUST be the database containing the Drupal installation.
$db_url['default'] = 'mysql://drupal:drupal@localhost/drupal';

// Define your external database separately.
$db_url['mydb'] = 'mysql://user:pwd@localhost/anotherdb';

```

module file:

```
// Switch to the external DB
db_set_active('mydb');

// Perform a query. Note that you should not call any Drupal API functions that will
// interact with the database until you've switched back. If you need your data to
// interact with the API, save it in a variable, switch back to the Drupal DB, and
// THEN make the API call
db_query('SELECT * FROM table_in_anotherdb');

// Switch back
db_set_active('default');

```

**Drupal 7**:

settings.php:

```
$databases = array (
  'default' => array (
    'default' => array ( // Again this must be your Drupal database.
      'database' => 'drupal',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'mydb' => array (
    'default' => array (
      'database' => 'db1',
      'username' => 'username2',
      'password' => 'password2',
      'host' => 'db.example.com',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

```

module file:

```
// Switch to the external DB
db_set_active('mydb');

// Get some data. The same rules about accessing the API functions apply here.
$results = db_query($sql);

// Switch back to the default db.
db_set_active('default');

```

---
Tags: database
---


# Question
Title: How can I include user pictures in e-mail notifications sent by the privatemsg module?
I have the Private Message module configured to send notifications when users receive a private message. I have the Mime Mail module configured and working; the private messages are sent as HTML and display properly. However, I have been unable to find a way to include user pictures in the messages.

On my site, I have a field that contains the user picture (I am not using the standard user pictures built-in to Drupal). However, I have overridden the user pictures template to show this field, so a solution that works for user pictures should hopefully work for my case as well.

I tried to solve this with tokens.

The token module makes available the following token: `[privatemsg_message:author:field_acc_profile_picture]`

However, when I include this token in the message, it is simply returned as a text string; no substitution is performed.

I thought this could be done with PHP but there is no way as far as I can tell to include PHP in the e-mail notify message field.

So, how can I include user pictures in e-mail notifications sent by the privatemsg module?

# Answer
> 2 votes
One way you could do this (which is what I do on a couple sites), is to implement `hook_privatemsg_message_insert()` in a custom module. Turn off the privatemsg module emails or any rules-generated emails, and instead write a custom bit of code that sends the private message.

In my case, I needed to do a few other customizations, but at its simplest, you can get a profile picture URL by loading the user $account from $message-\>author-\>uid.

A quick example:

```
<?php
/**
 * Implements hook_privatemsg_message_insert().
 */
function custom_privatemsg_message_insert($message) {
  global $base_url;

  // Get the account from which message was sent.
  $account_from = user_load($message->author->uid);

  // Get the person to whom the message is being sent (I only handle one).
  foreach ($message->recipients as $key => $recipient) {
    $account_to = $recipient;
    continue;
  }

  // Set up variables for our message body.
  $variables = array(
    'from' => $account_from->realname,
    'link' => l('Click here to view/reply to this message', $base_url . '/messages/view/' . $message->thread_id, array('external' => TRUE)),
    'message' => check_markup($message->body, $message->format),
  );

  // Print the message body using a custom theme function. Because email clients
  // require obnoxious markup, it's best to use a theme function or template...
  $body = theme('custom_private_message', $variables);
  $body_plain = strip_tags($body);

  $subject = t('New Private Message: ') . $message->subject;
  $email_to = $account_to;
  $email_from = $account_from->realname . ' <' . $account_from->mail . '>';

  // Now, use whatever mechanism you want to send the actual email.
}
?>

```

---
Tags: privatemsg
---


# Question
Title: UC Orders and Webfrom Submissions in same view
Does anyone know a method to create a view with both 'UC Orders' and 'Webform Submissions'? I am using 'UC webfrom pane' to collect some extra info on checkout but am really struggling to add this data to a view with order data.

What would be a possible way to do this? Help is much appreciated.

# Answer
check this out... I had the same issue and was able to solve it: http://archive.org/details/DisplayWebformSubmissionDataInViews
> 0 votes

---
Tags: views, ubercart, webforms
---


title: Overlay zoomed image in node?

text:
# Question
Title: Overlay zoomed image in node?
How can I implement a zoom functionality on my content nodes? Like I need to put a zoom button next to my image and clicking it brings a floating zoomed image over the page like it's done here. I'm using Drupal Commerce.

I know that it can be done through Colorbox or Lightbox2 but these modules only function in Views (or not?). How can I put this functionality on my node (product page)?

I have themed my custom `node.tpl.php` template for the product display page.

# Answer
I have used the Colorbox module to successfully achieve the desired effect.
> 0 votes

# Answer
I have achieved this on a node before using Fancybox by setting up an image preset for your thumb size that opens with Fancybox. For the image to link to Fancybox you need select a Fancybox image preset under display settings for full node within your content type.

Make sure you initialize the plugin before activation using the appropriate jQuery selector.
> 3 votes

# Answer
Magic Thumb zooms images on a product page.

The Drupal module is here:

http://www.magictoolbox.com/magicthumb/modules/drupal/
> 0 votes

---
Tags: media, nodes
---


# Question
Title: render($page['content']) in the wrong place!
Ok I'm having this really weird problem with my Drupal 7 site. I have edited my `page.tpl.php` file. Following is the html where this oddity occurs

```
<table class="main_content">
<tr>
    <td>
        <div class="left_main">
            <div class="main_title">
                 <h2 class="centerBoxHeading"><?php echo $title; ?></h2>

            </div>
            <?php print render($page['content']); ?>
        </div>
    </td>
    <td>
        <table>
               <tr>
                   <td>
                       <div class="right_main">
                           <div class="main_title">
                                <h2 class="centerBoxHeading">Bestselling</h2>
                           </div>
                           <?php print render($page['right']['views_bestsellers-block']); ?>
                       </div>
                   </td>
               </tr>
               <tr>
               <td>
                   <div class="other_blocks_right">
                       <div class="main_title">
                           <h2 class="centerBoxHeading">Poll</h2>
                       </div>
                       <?php print render($page['right']['poll_blocks_11']); ?>
                   </div></td>
               </tr>
        </table>
   </td>
</tr>
</table>

```

So far everything looks fine. But when opened in the browser `print render($page['content']);` prints outside the table before it! I have checked this through firebug.

I have also edited a `node.tpl.php` file and everything is fine inside it.

Can anyone suggest what is going on?

# Answer
The content in my `node.tpl.php` was wrapped in a `tr` tag. Don't know how it got there. When I removed it everything was fine.
> 2 votes

---
Tags: 7, theming
---


# Question
Title: How can I lead to 404 Page Not Found when View page has no result?
How can I lead to 404 Page Not Found when View page has no result?

I tried this code from http://drupal.org/node/1295824#comment-5192868in "empty text" but the View page still exist with only page title eve if it has not result to list.

```
<?php
drupal_set_header('HTTP/1.1 404 Not Found');
?>

```

# Answer
> 5 votes
You should use the `drupal_not_found()` function. It sets the correct headers, omits blocks from the page output to conserve CPU and bandwidth, and is the correct way to set a 404 through code in Drupal.

Also see `drupal_access_denied()` which might be useful.

# Answer
> 0 votes
You can use `drupal_goto()` to redirect and set a proper status code.

---
Tags: views, 6
---


title: Jquery and Ajax 404 Undefined Error

text:
# Question
Title: Jquery and Ajax 404 Undefined Error
Hi I am developing a module in which i am sending data from javascript to drupal using jquery ajax.

but i am getting 404 error undefined.I am not able to figure out. Pls help

Here is my code

This is **tbg.js** an external js file

```
$.ajax({
        url: 'localhost/drupal/my_currenttime/10',
        type: 'GET',
        success: function(data){
            alert(data);
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert(jqXHR.status+textStatus + errorThrown);
        }
    });

```

In my module file i am calling this js file in hook\_nodeapi

```
function modulename_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL)
{
  switch($op)
  {
    case 'view':
    drupal_add_js(drupal_get_path('module', 'modulename').'/tbgscript.js', 'module');
    break;
  }
}

```

I have created a call back url for the ajax request in modulename\_menu() hook

```
function modulename_menu()
{
  $items['my_currenttime/%'] = array(
  '#title' => 'My custom callback',
  'description' => 'Desc',
  'page callback' => 'custom_currentTime',
  'page arguments' => array(1),
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
  );

  return $items;
}

```

and my page call back method is

```
function custom_currentTime($args)
{
   echo "HELLO".$args;
}

```

i want to access the value $args in my module file.

# Answer
> 2 votes
I would guess that the URL is wrong in your javascript.

Currently, if your site is on `http://localhost`, the page requested will be:

```
http://localhost/localhost/drupal/my_currenttime/10

```

When I suspect it should be:

```
http://localhost/drupal/my_currenttime/10

```

To fix that just add the `http://` part to the beginning of the URL variable in your JS code, or make it relative:

```
url: '/drupal/my_currenttime/10'

```

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


# Question
Title: MIssing 'Drush configuration' and 'Php configuration' when running 'Drush status'
If a run the method 'drush status' in the terminal I see that the values for 'Drush configuration' and 'Php configuration' are missing.

It give me not problem at all. But is this correct?

Look the capture:

I use the free version of MAMP.

# Answer
One of my colleagues has MAMP installed and that's what his Drush status looks like too.

I'm using the build of Apache built in to OSX and the only difference I see is that the PHP configuration is filled in:

Like you, neither my colleague or I suffer any problems with these settings missing so I wouldn't worry too much about it.
> 0 votes

---
Tags: drush
---


title: Access JavaScript cookie in module file

text:
# Question
Title: Access JavaScript cookie in module file
I am setting a cookie in an external JavaScript file with the current user time. I want this time to be available to the server, so I am retrieving this from a cookie.

I am able to fetch the value, but only when I refresh the browser twice. If I change my current system time, and refresh the page, I still see the old time; when I refresh again, then I see the updated time.

### JavaScript code

```
var now=new Date();
currTime=now.getHours();
document.cookie = "currentTime = " +currTime;

```

### PHP code

```
$current_time = $_COOKIE["currentTime"];
echo $current_time;

```

I am calling the external JavaScript file in `hook_nodeapi()` using `drupal_add_js()`.

As I said, I am able to get the updated value of current time from cookie but only if I refresh twice.

What could be the problem?

# Answer
I understood the problem. It is because the first time it sets the cookie, and in the second time it becomes available to PHP; hence two refreshes.
> 1 votes

---
Tags: hooks, javascript, cookies
---


# Question
Title: How can I display a search form with a different style from search bock, inside a node?
I have a search block enabled at top side of my site. But I also need to display the same search form, but with different css class applied inside a node. How this can be done?

# Answer
> 1 votes
Since blocks can only go in a single region (without some messing about), I think you'll have to use code for this. You could add the form in a preprocess function in your theme's template.php file:

```
function MYTHEME_preprocess_node(&$vars) {
  if ($vars['node']->type == 'my_node_type') {
    $form = drupal_get_form('search_form');

    $vars['search_form'] = render($form);
  }
}

```

Now in your node.tpl.php file, or node--content\_type.tpl.php file, you'll be able to output the search form like this:

```
<?php if ($search_form): echo $search_form; endif; ?>

```

The default classes and ID added to the `<div>` surrounding the node will be be perfect for targeting that particular instance of the form with CSS. You can easily use developer tools/firebug to determine what selector to use.

---
Tags: search
---


# Question
Title: Pass parameter from a custom php function to hook_block
I have a hook\_menu page callback. I want to use the argument which it receives in hook\_block.

For example

```
function myCustomFunction($args) {

}

modulename_block() {
  // Use $args here
}

```

How can this be done. Is there a way I can pass this as a parameter.

# Answer
> 1 votes
I'm not sure how this would be expected to work consistently; if your block relies on arguments built up from a particular page callback, then the block will only work on that page.

Having said that, if the page callback arguments are based on a known value, for example a node ID, then I can see how it might work for a particular path/set of paths.

Let's say this is your menu item in `hook_menu()`:

```
$items['my/path/%node'] = array(
  'title' => 'A title',
  'access arguments' => array('access content'),
  'page callback' => 'MYMODULE_some_function',
  'page arguments' => array(2)
);

```

And this is your code for `MYMODULE_some_function()`:

```
function MYMODULE_some_function($node) {
  $the_value = do_something_to($node);
}

```

In your `hook_block()` function you can grab the node ID out of the URL, load the node manually, and perform the same function on it that you have in `MYMODULE_some_function()`. For example:

```
function MYMODULE_block($op = 'list', $delta = 0, $edit = array()) {
  // I've omitted the 'list' op, obviously you'll need to implement that yourself

  if ($op == 'view' && $delta == $the_delta) {
    // Check that we're on an appropriate page
    if (arg(0) == 'my' && arg(1) == 'path' && is_numeric(arg(2))) {
      $nid = arg(2);

      $node = node_load($nid);

      $the_value = do_something_to($node);

      $block['content'] = $the_value;
    }
  }
}

```

You might want to centralise the code that runs `$the_value = do_something_to($node);` into it's own function so you're not repeating yourself.

---
Tags: 7, hooks, blocks
---


# Question
Title: Allowing users to add taxonomy terms but requiring administrators to verify them
I would like to allow users to add new taxonomy terms, but I would like this to be verified by an administrator. The way I envision this working would have a user filling out a form which would send a notification to the specified admin; then, if the admin accepted the users request some hook or method would be triggered that would create the new taxonomy term.

Is there way to do this kind of thing with Drupal?

# Answer
Brainstorming here...now that taxonomy is part of the entity system, it should be possible to do something like this:

1. Install http://drupal.org/project/workflow
2. Add a field to your taxonomy called "Published" or "Approved" that is a boolean checkbox
3. Setup a workflow that is triggered on taxonomy term creation with Approved as a field only accessible to admins
4. Write a hook into taxonomy terms that removes a term unless it is approved (this is the tricky part - there are a lot of ways to get to taxonomy terms, so this might make this approach moot).

Alternative: Since you mentioned a user filling out a form - you could pretty easily have a content type called "Taxonomy Term" or something with the needed Taxonomy fields, then use workflow/Rules to send the submission to an admin, upon approval use Rules or custom code to create a new taxonomy term.
> 8 votes

# Answer
I never did something like this, but my approach would be to create a "proposed taxonomy term" content type and model the logic via the Rules module.
> 3 votes

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


# Question
Title: Using field_create_instance(), db_set_active() and node_save() in conjunction
I'm in the process of writing a module that will essentially publish a node to two sites (the one the user is creating the node on and another one specified in code). Both sites run on the same Drupal installation, with all the needed database info defined in `$databases`.

In short, part of the process involves populating a hidden field in the second website's "article" content type. That field isn't defined on the first site because it doesn't need to be referred to there. I want to make Drupal "aware" of the field by the time it performs node\_save(), but without actually creating the field on the first site, because the resulting tables in the database would go unused.

So, the basic logic of my module's code is:

* Modify the node form slightly to include a new checkbox
* If it's checked:
    + Manipulate `$node` to specify values for a field that only exists on the other site
    + Use `hook_node_insert` and `hook_node_update` to switch to the other site's database and perform a `node_save` in it

It's a bit more complex than that and the other site also checks said field's value to display a message, but the steps above are the ones relevant to my problem. Initially I thought just adding an array for the field in `$node` would do the trick, but then I learned that the field needs to have an instance attached to the bundle before any subsequent database interactions will do anything with it. In order to do that, it looks like the standard procedure is to use `field_create_field` and `field_create_instance` \- only I would like to get away with only using the latter, since I don't want the field to actually exist on the first site, only the second one.

Are there any reliable ways of achieving this? I hope I explained it well enough but will try to provide more detail if necessary.

# Answer
> 0 votes
I've figured out a solution to this, although I'm not sure if it's the best performance wise. It would seem that even after switching database with `db_set_active()`, `node_save()` (and presumably any other field\<\>database operations) will continue to use the field info as defined beforehand, so even if you've specified a value for a field that only exists in the second database, it will assume the field doesn't exist. Using `field_info_cache_clear()` right after `db_set_active()` solves the problem.

Obviously clearing any cache in a hook like this sort of defeats the purpose of the cache; fortunately in my case it won't be necessary too often.

If anyone knows of a better way of handling it without clearing any caches or creating the field on both/all sites, I'd love to know. I won't mark this as the accepted answer for the time being.

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


# Question
Title: How do I pass data between hooks that don't interact?
How do I pass data between hooks that don't interact between them, or between a menu callback and a hook?

In the case the two hooks have a parameter in common, and that parameter is passed by reference, that is easy. What do I do when the hooks, or the menu callback and the hook, don't get a common parameter?

# Answer
> 12 votes
In Drupal 7, or higher, use a static variable handled with drupal\_static().
`drupal_static()` is a function that handles a central storage for static variables. Differently from the variables declared using the `static` keyword, the static variables handled with `drupal_static()` are accessible from every function; this is possible because `drupal_static()` returns the variable's content by reference, allowing every function to alter it.

Suppose that you need to pass a value between a menu handler, and the implementation of hook\_block\_view(); you could use the following code.

```
function mymodule_menu() {
  return array('path/%' => array(
    'page callback' => 'mymodule_callback_function',
    'page arguments' => array(1),
  ));
}

function mymodule_callback_function($data) {
  $data_passer = &drupal_static('mymodule_block_data');

  $data_passer = $data;

  // Other logic specific to this page callback.
}

function mymodule_block_view($delta = '') {
  // $data_passer will now contain the value of $data, from above.
  $data_passer = &drupal_static('mymodule_block_data');

  // Change the block content basing on the content of $data_passer.
}

```

In the case that data need to be accessed more frequently, you should use a static local variable that would contain the value returned from `drupal_static()`. As static variables can only be initialized from literal value, and static variables cannot be assigned to references, the only working code is similar to the following one. (This code is taken from user\_access().)

```
  // Use the advanced drupal_static() pattern, since this is called very often.
  static $drupal_static_fast;
  if (!isset($drupal_static_fast)) {
    $drupal_static_fast['perm'] = &drupal_static(__FUNCTION__);
  }
  $perm = &$drupal_static_fast['perm'];

```

The value returned from `drupal_static()` is reset every time Drupal bootstraps; if you need a value that is preserved between different pages, then you need to use a database table to store the value, or use variable\_get()/variable\_set().

Drupal 6 doesn't implement `drupal_static()`, but you could copy its code in a function defined in your own module.

```
function &mymodule_static($name, $default_value = NULL, $reset = FALSE) {
  static $data = array(), $default = array();

  // First check if dealing with a previously defined static variable.
  if (isset($data[$name]) || array_key_exists($name, $data)) {
    // Non-NULL $name and both $data[$name] and $default[$name] statics exist.
    if ($reset) {
      // Reset pre-existing static variable to its default value.
      $data[$name] = $default[$name];
    }
    return $data[$name];
  }

  // Neither $data[$name] nor $default[$name] static variables exist.
  if (isset($name)) {
    if ($reset) {
      // Reset was called before a default is set and yet a variable must be
      // returned.
      return $data;
    }
    // First call with new non-NULL $name. Initialize a new static variable.
    $default[$name] = $data[$name] = $default_value;
    return $data[$name];
  }

  // Reset all: ($name == NULL). This needs to be done one at a time so that
  // references returned by earlier invocations of drupal_static() also get
  // reset.
  foreach ($default as $name => $value) {
    $data[$name] = $value;
  }

  // As the function returns a reference, the return should always be a
  // variable.
  return $data;
}

```

Before using a static variable with `drupal_static()` (or the back ported function defined in your module), you should keep these considerations in mind:

* The code works only when the code that sets the static variable runs before the code to get its value; if the execution order is not the thought one, the code doesn't work. When the order of execution is not clearly defined in Drupal documentation, there is the risk the order changes in future versions of Drupal; check the execution order doesn't change in the Drupal version for which you are implementing your code.
* Drupal could have implemented a mechanism to share data between different hooks. For example, in the case of different implementations of hook\_form\_alter(), each implementation can share data with other `hook_form_alter()` implementations using `$form_state`; in the same way, form validation handlers, and form submission handlers, can share data using the `$form_state` parameter that is passed by reference. Before implementing your own code, verify it is possible to share data using a different mechanism already implemented by Drupal for the specific case.

---
Tags: hooks
---


# Question
Title: Attaching a field of a node type in another form
I have content type 'story' which have an upload field. I have workflow modules installed.

I want the upload field to be presented within the workfloaw form. So within form alter function I did:

```
field_attach_form('node', $node, $form['append'], $form_state);

```

then unset all other fields of the story node and appended validation and submit handlers:

```
$form['#validate'][] = 'node_form_validate';
$form['#submit'][] = 'node_form_submit';

```

on submission I get this error:

"EntityMalformedException: Missing bundle property on entity of type node. in entity\_extract\_ids() (line 7409 of /var/www/site/includes/common.inc)."

I tried by specifying 'bundle' and 'entity\_type':

```
$form['#bundle'] = 'story';
$form['#entity_type'] = 'node';

```

and

```
$form['append']['#bundle'] = 'story';
$form['append']['#entity_type'] = 'node';

```

but did not help. What can I do?

Thanks.

# Answer
> 1 votes
"EntityMalformedException: Missing bundle property on entity of type node." means that Drupal does not recognize your entity as a valid one. In the entity info listing, there is a mapping from "bundle" to "type", for nodes.

Either your `$node` doesn't have a `->type`, or Drupal no longer has the type registered. The type could have been removed, either from the UI, or by disabling a feature, and possibly in more interesting ways as well.

---
Tags: 7, forms, files
---


# Question
Title: HTML code to PHP code mapping does not work
I am trying to include the timeline API, and install the timline files on my webserver. The timeline-api.js gives an example of an HTML page that contain the following code.

```
<script>
var Timeline_ajax_url="http://YOUR_SERVER/apis/timeline/ajax/simile-ajax-api.js";
var Timeline_urlPrefix='http://YOUR_SERVER/apis/timeline/';
</script>
<script src="http://YOUR_SERVER/javascripts/timeline/timeline-api.js"
type="text/javascript">
</script>

```

It also contain the following comment.

```
   /*
    * Eg the two next lines pass the same parameters:
    * Timeline_parameters='bundle=true';                    // pass parameter via js variable
    * <script src="http://....timeline-api.js?bundle=true"  // pass parameter via url
    */

```

I am trying to do the same thing in Drupal using the following code.

```
$timeline_lib_path = $base_path . libraries_get_path('simile_timeline');
// Set some global js variables that the library is going to need for proper inclusion and functionality.
$timeline_inline_js = "
var Timeline_ajax_url = '$timeline_lib_path/timeline_ajax/simile-ajax-api.js',
Timeline_urlPrefix = '$timeline_lib_path/timeline_js/',
Timeline_parameters = 'bundle=true';
";
drupal_add_js('similetimeline',$timeline_inline_js);
drupal_add_js('similetimeline','$timeline_lib_path/timeline_js/timeline-api.js');

```

I have an uncaught reference error: Timeline is not defined.

# Answer
You have the smallest of errors in your code; in the very last line you're trying to interpolate a variable into a string using single quotes. You need to use double quotes instead:

```
drupal_add_js('similetimeline',"$timeline_lib_path/timeline_js/timeline-api.js");

```

Have a peek at the PHP Strings Documentation for more information.

I've just noticed another problem actually; you don't seem to be using `drupal_add_js()` properly. The first argument should be the name of a file or an inline string, in which case you should specify that it's inline:

```
drupal_add_js($timeline_inline_js, 'inline');
drupal_add_js("$timeline_lib_path/timeline_js/timeline-api.js");

```
> 0 votes

---
Tags: javascript
---


# Question
Title: How to remove a specific item from the search index?
I have a content type in a D6 site that allows the creator of a node to mark the node as "withdrawn" -- he can still see it, but attempts by others to see it are caught and redirected somewhere else, like their user page. When this node gets withdrawn, I'd like to remove it from the local search index (standard Drupal search) as well.

My somewhat brutish way of doing this is:

```
    db_query("delete from {search_dataset} where sid = %d", $node->nid);
    db_query("delete from {search_index} where sid = %d", $node->nid);

```

which seems to work -- the node stops showing up in search results. But I'm worried about {search\_total} -- there are entries there that correspond to the words in the node's content. I can't just remove all the node's terms from {search\_total}, of course; is this worth worrying about? Or am I seriously screwing up the search index by doing this in the first place? Thanks!

# Answer
Looking at the code executed from node\_delete\_multiple() (which is then the function used by node\_delete()), I see that the function called is search\_reindex().

```
    // Remove this node from the search index if needed.
    // This code is implemented in node module rather than in search module,
    // because node module is implementing search module's API, not the other
    // way around.
    if (module_exists('search')) {
      search_reindex($nid, 'node');
    }

```

The code executed from that function to delete rows from the search tables is the following one.

```
db_delete('search_dataset')
  ->condition('sid', $sid)
  ->condition('type', $module)
  ->execute();

db_delete('search_index')
  ->condition('sid', $sid)
  ->condition('type', $module)
  ->execute();

// Don't remove links if re-indexing.
if (!$reindex) {
  db_delete('search_node_links')
    ->condition('sid', $sid)
    ->condition('type', $module)
    ->execute();
}

```

I suggest using `search_reindex()`, but to reply to your question, it doesn't seem that updating the "search\_total" table is necessary, at this point; Drupal doesn't do it when a node is deleted. That table is updated from search\_update\_totals(), which is called from search\_cron(). See the comment given for the following code, executed from `search_update_totals()`.

```
  // Find words that were deleted from search_index, but are still in
  // search_total. We use a LEFT JOIN between the two tables and keep only the
  // rows which fail to join.
  $result = db_query("SELECT t.word AS realword, i.word FROM {search_total} t LEFT JOIN {search_index} i ON t.word = i.word WHERE i.word IS NULL", array(), array('target' => 'slave'));
  $or = db_or();
  foreach ($result as $word) {
    $or->condition('word', $word->realword);
  }
  if (count($or) > 0) {
    db_delete('search_total')
      ->condition($or)
      ->execute();
  }

```

In Drupal 6, the equivalent of `search_reindex()` is search\_wipe(), which is called from node\_delete(). The function contains the following code to delete the tables' content.

```
db_query("DELETE FROM {search_dataset} WHERE sid = %d AND type = '%s'", $sid, $type);
db_query("DELETE FROM {search_index} WHERE sid = %d AND type = '%s'", $sid, $type);
// Don't remove links if re-indexing.
if (!$reindex) {
  db_query("DELETE FROM {search_node_links} WHERE sid = %d AND type = '%s'", $sid, $type);
}

```

Also in this case, I suggest using `search_wipe()`.
> 1 votes

---
Tags: nodes, search
---


title: Autocomplete textfield widget?

text:
# Question
Title: Autocomplete textfield widget?
Does anybody know of a Drupal 7 autocomplete widget for textfields? I've tried Autocomplete Widgets, but the "Autocomplete for allowed values list" widget from that doesn't seem to exist in Drupal 7 -- only the other two widgets show up. My goal is to store plain text but autocomplete from a user profile field. Thanks!

# Answer
Creating autocomplete for a Drupal form textfield is pretty easy.

1. Add the `#autocomplete_path` to the form element
2. Create a menu callback that returns JSON data with `drupal_json`
> 6 votes

# Answer
Try http://timonweb.com/how-create-ajax-autocomplete-textfield-drupal-7

ALSO: http://qandeelaslam.com/blogs/cck/converting-texfield-autocomplete-using-drupals-form-api http://www.elevatedthird.com/blog/enable-ajax-autocomplete-drupal-7-webform-textfield

(Looking for a module, now.)
> 7 votes

# Answer
There is http://drupal.org/project/autocomplete\_widgets:

> This module adds 3 autocomplete widgets for CCK fields of type Text and Number.
>
> Autocomplete for allowed values list: This widget can be used for Text and Number fields and it takes candidate values from the defined list of Allowed values of the fields. You can even generate your allowed values list using PHP, so the limit to provide a widget with autocomplete features is your imagination!
>
> Autocomplete for existing field data: This widget can be used for Text only and it takes candidate values from existing values in the database for that field.
>
> (7.x only) Autocomplete for predefined suggestions: This widget can be used for Text only and allows an admin to provide a list of suggestions but still allows users to enter anything they want in a text field. Use this widget to help avoid (but not prevent) variations of the same value. Ex: burger, hamburger, Burger ...
>
> (7.x only) Autocomplete for existing field data and some node titles: This widget works just like the "existing field data" widget above except it will also suggest node titles for nodes of a specific content type(s).
> 3 votes

---
Tags: entities, ajax, 7
---


# Question
Title: How should I load a node with its images programatically?
I want to load a node with its images in Drupal 7, such as using the following code:

```
  $current_node = node_load(arg(1));
  db_query("SELECT nid, title FROM {node} WHERE type = :type AND created < :created LIMIT 1", array(':type' =>  $current_node->type, ':created' => $current_node->created))->fetchObject()

```

I wish to load the image field in the content; I think I should use left join to load the image file.

Does anybody know what to do next? What is the image table name?

# Answer
> 1 votes
You're going to have to join another table for every field that you want to grab the data for, which is just a pain. Instead, you could just get the `nid` with your query, and use `node_load()` a second time to get the other node object, complete with attached fields.

You can do that like so:

```
$args = array(':type' => $current_node->type, ':created' => $current_node->created);
$sql = 'SELECT nid FROM {node} WHERE type = :type AND created < :created';
$nid = db_query_range($sql, 0, 1, $args)->fetchField();

$new_node = node_load($nid);

$title = $node->title;
$image_field_values = field_get_items('node', $new_node, 'field_image');

$first_image = array_shift($image_field_values);
$image_file = file_load($first_image['fid']);

$image_html = theme('image_style', array(
  'style_name' => 'thumbnail',
  'path' => $image_file->uri,
  'alt' => 'Some alt text'
));

$body_values = field_get_items('node', $new_node, 'body');

// And so on

```

# Answer
> 1 votes
Yes and to add more to it, if you use node load it is safer because then the Drupal caching will by default will work for you. And if you are writing queries to get the result then every time the page is going to get a hit, the query will be fired and no caching will be done by default. You have to explicitly handle the caching at this point of time.

---
Tags: nodes, media
---


title: Add field in hook_node_info();

text:
# Question
Title: Add field in hook_node_info();
Is it possible to add fields to a node type declared using hook\_node\_info? Do I have to add the fields separately? If so, what hook would I use for that?

# Answer
You need to attach the fields separately, they can't be added through `hook_node_info()`. You would usually do this in a `hook_install()` function in your module's .install file.

A nice simple example from Drupal core is in the blog module's install file:

```
function blog_install() {
  // Ensure the blog node type is available.
  node_types_rebuild();
  $types = node_type_get_types();
  node_add_body_field($types['blog']);
}

```

The function simply rebuilds the node types (so the newly added type is available), then adds a body field to it using the `node_add_body_field()` function. This function in itself gives an excellent example of how to create a field, an instance of that field, and then attach it to a content type using the `field_create_field()` and `field_create_instance()` functions.

The code isn't that so long so I'll include it here as an example:

```
function node_add_body_field($type, $label = 'Body') {
  // Add or remove the body field, as needed.
  $field = field_info_field('body');
  $instance = field_info_instance('node', 'body', $type->type);
  if (empty($field)) {
    $field = array(
      'field_name' => 'body',
      'type' => 'text_with_summary',
      'entity_types' => array('node'),
    );
    $field = field_create_field($field);
  }
  if (empty($instance)) {
    $instance = array(
      'field_name' => 'body',
      'entity_type' => 'node',
      'bundle' => $type->type,
      'label' => $label,
      'widget' => array('type' => 'text_textarea_with_summary'),
      'settings' => array('display_summary' => TRUE),
      'display' => array(
        'default' => array(
          'label' => 'hidden',
          'type' => 'text_default',
        ),
        'teaser' => array(
          'label' => 'hidden',
          'type' => 'text_summary_or_trimmed',
        ),
      ),
    );
    $instance = field_create_instance($instance);
  }
  return $instance;
}

```
> 8 votes

---
Tags: 7, entities
---


# Question
Title: Modules Page: Keep Package Sections collapsed
As I'm working over and over with modules, I'm constantly having to scroll past all of the Core modules and such. I can collapse module packages, but when I reload the page they are all expanded again. Is there any way to make drupal remember which module packages to remain collapsed?

# Answer
This is a different approach, but installing the Module Filter module will allow you to quickly filter the list of modules by simply typing a few letters of the module's name. Alternately, you can quickly show only the modules from the categories that you would like to see by using the vertical tabs it places on the left-hand side of the page.
> 3 votes

# Answer
In addition to Module Filter (which is great) there are also a couple of settings provided by the Admin Menu module that might help out:

It doesn't 'remember' which ones you've last had open though, it collapses them all every time the page is re-loaded.
> 2 votes

---
Tags: 7, users
---


title: Using Menu Tabs with Views 3 (Drupal 7)

text:
# Question
Title: Using Menu Tabs with Views 3 (Drupal 7)
So I'm confused by the Menu Tabs functionality of Views 3 (Drupal 7 site).

My menu is organized like this:

> About-Us =\> /about-us
> --Management =\> /about-us/management
> ----Top-Management =\> /about-us/management/top-management
> ----Board-of-Directors =\> /about-us/management/board-of-directors

I have a View setup with two page displays and their paths are: about-us/management/top-managers about-us/management/board-of-directors

I configured the 'top-managers' page display to be a "Default Menu Tab" I configured the 'board-of-directors' page to be a "Menu Tab"

For the Default Menu Tab, I had to provide a Parent Menu Item, so I selected "Normal menu item". I also tried "Already Exists" but that seemed worse.

So.. When I go to about-us/management/top-managers I get the correct page display, and there are tabs at top. When make the 2nd tab active ("Board of Directors"), the path changes correctly and I get the correct page display. But the 1st tab ("Top Management") links to the parent's path (about-us/management) instead of to itself (about-us/management/top-management).

So the 1st tab links to about-us/management and the 2nd tab links to about-us/management/board-of-directors. I want the 1st tab to link to about-us/management/top-managers

How do I get the default menu tab to link to its own path instead of the parent's path? Or am I doing something completely wrong?

# Answer
Check this:

> How to add a tab to a Views page:
>
> On the View that you want as the default tab: In the Views ‘page settings’, set the Menu Type as ‘Default Menu Tab’ then click the little setting ‘gear’ and set the ‘parent menu item’ to ‘normal menu item’. Set the path as “/something/tab1″; for example, “/postlist/allposts”
>
> On the View that you want as your second (or 3rd, etc) tab, set the Menu Item Type as ‘Menu tab’. Set the path as “/something/tab2″ for example, “/postlist/newposts”
>
> The key to making the tabs show on the View page is the path setting! All of the pages must have the same parent-path – in the examples above this is “/postlist”. If the parent-paths are not the same, you will never get that damn tab to show up in the View.

For more check the original post
> 2 votes

---
Tags: 7, views
---


# Question
Title: the article can't show the image in the full mode in drupal 7
my article can't show images in the full view but only in the teaser view, even go to the article content type setting, in the full mode, it is fine that I allow to show the image.

any idea why?

# Answer
Make sure to set the display on the content type (manage display link) as it ultimately sets the values of the teaser and full node.
> 0 votes

---
Tags: media
---


# Question
Title: Changing upload_max_filesize inb Drupal 7
Is there any way to change php's upload\_max\_filesize setting from settings.php in Drupal 7? This used to work for me in Druapl 6 but no longer seems to. I don't like the idea of doing it in .htaccess, because that's a core file that will get overwritten on an upgrade.

# Answer
> 1 votes
Personally I would change it in the /etc/php.ini file as it won't be overwritten. You will need to restart apache to see the changes

---
Tags: 7, configuration
---


# Question
Title: Match JSON POST data with custom node fields
Is there a fool-proof method to generate a correctly formatted JSON data object to be received by a create node resource given by a REST server, defined with Services in Drupal 7?

I have setup a REST server accepting the `application/json` content type. I have also set up an anonymous endpoint with the `create node` resource enabled and I managed to create a new item with the Poster plugin for Firefox with Content Type set to `application/json` and the following data

```
{"title":"Review","type":"story"}

```

I can't seem to get any further though. I am following this guide and the node is created but my data for the rest of the fields is not added. I use this JSON editor to generate my code so it matches the structure shown by the `dsm($_POST)` call I placed in `node.module`'s `node_submit` handler for testing.

The JSON data I am trying to post looks like this (I remove all whitespace before using Poster):

```
{
"title":"great success!",
"type":"story",
"field_review":[
    {"und":
        [{"0":
            [
                {"value":"Some text"}
            ]
        }]
    }
],
"field_rating":[
    {"und":
        [
            {"rating":"60"}
        ]
    }
],
"field_product_type":[
    {"und": "1"}
],
"field_barcode":[
    {"und":
        [
            {"value":"33333333333"}
        ]
    }
]
}

```

What am I missing?

# Answer
> 1 votes
The function json\_encode(); from my understanding.

---
Tags: 7, entities, services
---


# Question
Title: How to check all checkboxes in a Views exposed filter by default?
I'm using the Views and Better Exposed Filters modules to allow users to select age ranges like this:

This view functions as a search page. However, users are confused because if they simply hit *Apply*, all age groups are searched even though no age groups are checked. For this reason, I would like to show all age groups as selected by default to make it clear that all age groups are searched by default.

How can I do this?

# Answer
> 4 votes
If you click on the filter in the Views admin UI to get to the "Configure filter criterion" popup, and then select all of the options for the filter like so:

Then they appear ticked by default when you access the View page.

---
Tags: views
---


# Question
Title: Install.php available after xcopy deployment
I created a Drupal 7 site with Sqlite on my dev machine. When I go to localhost/install.php it says: Drupal is already installed.

After deploying the whole bunch to shared hosting (windows) the install.php is available again although the site works. It is even available to anonymous users and when the site is in maintenance mode. What should I do to disable that? Or should I deploy another way?

# Answer
What the installer checks for, is whether or not the settings file has database information for the site.

While this sounds simple in theory, and shouldn't lead to install.php being executed, there are many components involved.

1. There's DNS, which may or may not respond to various sub-domains.
2. There's the webserver configuration, which may or may not serve sub-domains, and may or may not re-write them before they hit Drupal.
3. Drupal, since 7, supports a sites.php file which can map domains to `sites/` directories.
4. Finally, there's the sites directory itself, where Drupal can find a settings.php file, check for a valid `$db_url`, and decide whether or not to allow installation.

Due to the many components, and the technical complexity of setting them all up right, it's very easy to end up in a situation where install.php decides to allow installation. This should generally not be a problem, as anonymous users should not be able to create new databases, but it looks quite wrong regardless.

While removing install.php is a solution, it's technically hacking core, and makes future deployments needlessly complicated.

I normally do two things to counteract this.

The first thing is to run the site from a directory named after the domain, such as `sites/example.com/` *and* make `sites/default` a link to the main site. This way, any unexpected domains being requested by Drupal will be served by the main domain.

Second, I always just block access to install.php completely on any production systems with this vhost file:

```
# ssh -L 8080:127.0.0.1:80 example.com
<Location /install.php>
  Deny from all
  Allow from 127.0.0.1
</Location>

<Location /update.php>
  Deny from all
  Allow from 127.0.0.1
</Location>

```

This ensures apache blocks access to both install and update. The comment at the top is a reminder for how I can open an ssh tunnel to the server so my traffic looks like it's coming from 127.0.0.1, thus allowing developers access to run update.php.

Something similar in IIS below. Note that I have **not** tested this. Someone with ISS experience, please update or comment so I can improve this part.

```
<location path="install.php">
    <system.webServer>
        <security>
            <authorization>
                <remove users="*" roles="" verbs="" />
                <add accessType="Allow" roles="Administrators" />
            </authorization>
        </security>
    </system.webServer>
</location>

```
> 2 votes

# Answer
One way is just to delete the install.php file altogether. Another option is to set permissions on the file so that it is unusable by the user that providing content through apache (presumably)
> 0 votes

---
Tags: installation, deployment
---


title: Why would one use Field Collection

text:
# Question
Title: Why would one use Field Collection
Having come across the Field Collection module (FCM) on Drupal, I would like to know why one would use the FCM. I appreciate one may need to create different profiles for users (i.e. Teacher, Student, Campus) that may have cross-linked data, but I'm a little stumped in my mind why the FCM can help.

Can someone elaborate on what benefits the module can have, prior to me doing a fair amount of 'trial and error' work to find out how it can benefit. Anything to enlighten us on Field Collection would be most welcome.

# Answer
There are several uses of field collection, but as the name implies, it's all about "Collecting fields" into groups.

I have a personal use case where I have a content type called "Project". Each project, can have several "subtask"s, and each subtask has a boolean, "completed".

If I have a normal multi-value field for "subtask", how do I conveniently stick a "complete" checkbox on to them? That would be it's own multi-value field, and there would be no connection between the data points, nor any easy way to theme the edit page to make them look like they belong together.

However, since "subtask" is actually a field-collection with a "name" and a "checkbox", they are logically grouped together, both in storage and in rendering.

If one want's a "quick" solution to a similar problem, then FC is an excellent module. However, if I were to build something serious, I would first consider if Relation can solve the problem instead. This will probably not always be the case, but with a bit of extra work, using relation instead of FC will yield a more flexible solution.
> 7 votes

---
Tags: entities
---


# Question
Title: How to pass a form and other variables to theme functions?
I wonder how can I pass a form and other variables (an array) to `hook_theme()`, I know that if you want to render a form in hook theme you have to use `'render element'` so now I can't use `'variables'` to pass my variable array. here is what I did to render the form:

```
function example_theme() {
  return array(
    'deductible_form' => array(
      'arguments'      => array('form' => NULL),
      'template'       => 'example',
      'render element' => 'form',
     ),
  );
}

```

What can I do to solve this?

# Answer
> 5 votes
As you rightly say you can't pass variables to a theme function that uses a `render element`, but then you don't need to.

One of the points of the render element is that the element already contains all of the properties/variables that it needs to perform the render, without having to get them from anywhere else.

A themed form is actually a good example for this: if you need to add extra variables in order to render that form, then they should be arguments to the form function itself. e.g.:

```
function deductible_form($form, &$form_state, $var1, $var2) {
  $form['#theme'] = 'deductible_form';
  $form['#var1'] = $var1;
  $form['#var2'] = $var2;

  // etc...

  return $form;
}

```

Then in your form's theme function you can easily access those vars:

```
function theme_deductible_form($vars) {
  $form = $vars['form'];

  $var1 = $form['#var1'];
  $var2 = $form['#var2'];

  // Render the form
}

```

All you need to do to get that form to render properly now is to call `drupal_get_form()` with your extra variables:

```
$form = drupal_get_form('deductible_form', $var1, $var2);

```

---
Tags: forms, theming
---


# Question
Title: CCK checkbox or dropdown widget as a field?
I am trying to setup a new CCK field for a content type to display as a checkbox but I see I don't have that option in the widgets type. Shouldn't that be included in the default CCK?

I am using the latest CCK for Drupal 6.

# Answer
> 0 votes
The checkbox field is provided by the "Options Widget" sub-module included with CCK. From the .info file:

> Defines selection, check box and radio button widgets for text and numeric fields.

If you're not seeing checkbox as an available type you probably don't have that module enabled.

---
Tags: entities, 6
---


# Question
Title: How do I limit the number of Views results on specific pages?
I have a Views-generated block which lists news. I would like the number of items to depend on the page it is displayed on - for instance: on the front page there's a place for 3, on another one - even 10. Is there a way to do that via a View tpl or template.php code?

I would rather not have an almost-identical copy of the View just for a different purpose.

# Answer
> 5 votes
This works for me:

```
function MYMODULE_views_pre_build(&$view) {
  if ($view->name == 'view_name') {
    $view->items_per_page = 5;
  }
}

```

# Answer
> 2 votes
I can think of two ways.

The best one, requires Page manager and Panels. Using those is to large a discussion to fit in here, but when a View is rendered with those tools, you can override the actual pager on a case by case basis. Page manager gives you a large set of conditions to manage when and where this happens.

The second solution uses a custom module:

```
function hook_views_pre_build(&$view) {
  if ($view->name == 'view_name' && $is_front) {
    $view->items_per_page = 5;
  }
}

```

# Answer
> 0 votes
In your views tpl check for page arguments or `$is_front` And apply limit vars to `foreach` or whatever loop you're using.

see Using Views templates

# Answer
> 0 votes
Well, hook\_views\_pre\_build should be the hook to be using if you want to alter paging, etc.. maybe you could try to post some code you've tried ?

if i recall correctly, you can set the items per page like this:

```
MYMODULE_views_pre_build(&$view){
$view->pager["items_per_page"] = 0;
}

```

use your own logic to alter the items per page as you wish.

---
Tags: 7, views
---


# Question
Title: How to access boolean field in content node template?
I've created a content type (event) that has a boolean field (status). I've created a template in my theme called node--event.tpl.php and I've got just about everything working as intended, but I want part of the template to be conditional based on that boolean.

How can I access that boolean in the template so I can use it in an if/else statement?

# Answer
> 0 votes
Probably the same way as other fields: http://api.drupal.org/api/drupal/modules!node!node.tpl.php/7

---
Tags: 7, theming
---