# Question
Title: Display different fields based on a URL parameter
I have a content type called **section** with 5 custom fields, and I need to display each field as a different page, e.g. section/1/fieldA, section/2/fieldB.

I would like to override node.tpl.php, and output the desired field based on the third parameter (fieldA, fieldB, ...).

How can this be done? Do I need to create a custom module or can be done via theming?

What should I do if I wanted to replace the node ID with a string?

# Answer
Use a custom module. Implement hook\_menu to declare a page handler for your path pattern that return the value of `field_view_field()`.

```
function MODULE_menu() {
  $items = array();
  $items['section/%node/%'] = array(
    'title callback' => 'node_page_title',
    'title arguments' => array(1),
    'page callback' => 'MODULE_node_field_page_view',
    'page arguments' => array(1, 2),
    'access callback' => 'node_access',
    'access arguments' => array('view', 1),
  );
  return $items;
}

function MODULE_node_field_page_view($node, $field_name) {
  if ($node->type !== 'section' || !field_get_items('node', $node, $field_name)) {
    drupal_not_found();
  }
  else {
    return field_view_field('node', $node, $field_name)
  }
}

```

Then use alias and pathauto to use path like `section/{node-title}/{field_name}` instead of numeric node id in URL.
> 1 votes

---
Tags: 7, entities
---


# Question
Title: What is the purpose of url('', array('prefix' => &$prefix)) in drupal_add_js()?
I was looking at the code of drupal\_add\_js(), and noticed the following code.

```
  // url() generates the prefix using hook_url_outbound_alter(). Instead of
  // running the hook_url_outbound_alter() again here, extract the prefix
  // from url().
  url('', array('prefix' => &$prefix));

```

I tried executing the following code, from the Devel module.

```
dsm(url('', array('prefix' => &$prefix)));
dsm($prefix);

```

The output was "/dr72/" for the first `dsm()`, but nothing for the second one.

Looking at the HTML of the front page in my test page, I notice the following JavaScript code.

```
jQuery.extend(Drupal.settings, {"basePath":"\/dr72\/","pathPrefix":"", /* … */ });

```

What is the purpose of that code in `drupal_add_js()` work? How it is supposed to work?

# Answer
> 4 votes
Modules can implement hook\_url\_outbound\_alter() to change to change generated URL's. The most typical example of that are language prefixes.

If you have two languages enabled with path prefixes, english at /en and german at /de, then pathPrefix will either be /de or /en. Since there is no actual API to get that prefix, it uses that trick.

The hook invokes locale\_url\_outbound\_alter(), which in turn invokes the defined url\_rewrite callbacks of the enabled language negotation types. In case of the path prefix, that is locale\_language\_url\_rewrite\_url which changes the prefix at the end of the function.

The reason for doing this is that it allows ajax calls and other javascript requests (for example the admin overlay) to do that request in the current language, so that strings returned by those requests are in the expected language.

---
Tags: javascript
---


title: Drupal GPL Questions

text:
# Question
Title: Drupal GPL Questions
I'm planning a new project that will require a great deal of custom code that must remain proprietary to my client. I found the licensing FAQ http://drupal.org/licensing/faq to be unclear. I know this is primarily a coder as opposed to legal Q&A forum, but hopefully some experienced Drupal developers can shed more light on this issue.

1. What constitutes distribution? For example, if the code is used on two unique domains owned by the same client, is that considered distribution? Page 533, Chapter 24 of *The Definitive Guide to Drupal 7* states "Modules built for ourselves or a single client are not considered distributed", but that isn't very clear.
2. If a module has been distributed and you have a copy, are you obligated to give me a copy, or is it up to you? (In other words, could I demand a copy from you?)
3. If custom javascript is called from a Drupal javascript object (such as Drupal.behaviors), is it considered GPL'd and distributed? The licensing FAQ Answer #7 states "Drupal's JavaScript, including the copy of jQuery that is included with Drupal, is itself under the GPL as well, so any Javascript that interacts with Drupal's JavaScript in the browser must also be under the GPL or a GPL compatible license." That's a major non-starter for this particular project. The client obviously doesn't want competitors walking off with highly specialized javascript that took months to develop with no legal recourse.
4. What is the legal status of modules that are not for distribution? Are they license-free, or are they automatically GPL'd even if not intended for distribution? For practical purposes, in a module that is not for distribution, would the following language have any legal effect: "This module is copyright Company XXX and is not intended for distribution. This software is not licensed and you may not use this module for your own purposes."

Apologies if these questions aren't as precise as they could be; I'm obviously not a lawyer. I really want to use Drupal for this project, but if I can't offer an assurance to the client that the custom code (module code and javascript) will remain proprietary it's a non-starter.

# Answer
(Disclamer: As usual with legal questions, I am not a lawyer, only a lawyer can give you a definitive answer).

Every Drupal module that is written and every javascript code that directly interacts with Drupal (or any other GPL code, but note that jQuery is dual-licensed and also available under the MIT License, this is not relevant when used with Drupal, though), automatically falls under the GPL. That's why GPL is also called a viral license. Everything it "touches" is GPL'ed automatically.

*If* you give the source code to someone, then he has every right the GPL grants him, including giving the source code to anyone he wants to, modify it and so on. However, viewing a website alone does *not* distribute your PHP code. JavaScript is a tricky question, see for example https://softwareengineering.stackexchange.com/questions/125955/using-gpl-licensed-jquery-scripts-on-website-with-ads and http://www.gnu.org/philosophy/javascript-trap.html. As far as I understand these, you always distribute the JS code.

So, obfuscating the JavaScript without providing a way to get the unmodified source code or adding a statement like the one you suggested above is in fact a direct violation of the GPL and someone could attempt to sue you.

Also note that there is an extended version of the GPL, the Affero General Public License, which explicitly includes viewing of a website as distribution. CiviCRM for example uses that license, so if you are required to allow visitors access to your custom adjustments/extensions of your website, when using a software like that.

Given the way the Ajax system in Drupal works, most relevant things usually happen on the server side, so that is usually not a big problem. Also, most GPL related lawsuits are usually related to companies selling products which run GPL software (e.g. routers) which don't provide access to their customized source code. I've never heard of a lawsuit against a website violating the GPL, but that could just be ignorance on my side, don't count on that ;)
> 2 votes

---
Tags: 7, javascript
---


# Question
Title: Problems with extreme slow database queries in Drupal 7
I have a problem with extreme slow database queries that make my site loading for more than a minute. I am not able to locate the source of that problem. I'm using devel to control the queries and I found out that mostly the functions saving or updating the cache or session tables are the cause. Here is one example of devel's output:

```
19622.34 1 _drupal_session_write P A UPDATE users SET access=:db_update_placeholder_0 WHERE (uid = :db_condition_placeholder_0)
10442.86 2 DrupalDatabaseCache::clear P A DELETE FROM cache_bootstrap WHERE (cid = :db_condition_placeholder_0)

```

I do not have an idea what I could do to find the cause of that problem.

# Answer
> 1 votes
When a server's I/O performance (especially its disk write performance) reaches its limit, it'll probably show first with cache queries because they're frequent and can contain some quite big chunks of serialized data.

I recommend you take a look at your disk I/O while you're waiting for a page to render, by using `iotop` for example.

The best way to prevent those I/O bottlenecks is to keep page requests from even reaching Drupal by putting a Varnish cache in front of the webserver. If they need to be answered by Drupal, though, at least take the cache load from the database by using Memcache.

# Answer
> 1 votes
Look at this answer I recently gave: Do Drupal websites have bad performance or are heavy? In short you might need to tune MySQL a little bit. What does `SHOW VARIABLES LIKE 'innodb_buffer_pool_size'` say?

---
Tags: performance, database
---


# Question
Title: Scanner module triggers call to node.admin.inc (require_once(), trying wrong path)
All of a sudden, for no reason (favorite kind of problem) Scanner stopped working. I can access the configuration at `/admin/config/search/settings` but trying load the scanner at `admin/content/scanner` fatal errors:

```
Fatal error: require_once() [function.require]:
Failed opening required '/public_html/sites/all/modules/scanner/node.admin.inc'
(include_path='.:/usr/lib/php:/usr/local/lib/php') in
/home/moondev/public_html/includes/menu.inc on line 514

```

Notice the path is wrong where it's trying to load node.admin.inc

Scanner used to work as expected so I suppose either an update changed something or a conflict with another module (or it's settings) is happening.

Anybody experience something similar before, where a core include is trying to be loaded from the wrong path?

# Answer
> 1 votes
Turns out to be a conflict with Administration Views (7.x-1.0-alpha1).

Disable admin views & functionality is restored. Not sure where the blame is yet because I haven't pinpointed the conflict. But it does make sense at face value because admin views replaces the `/admin/content` and scanner is located at `admin/content/scanner`

---
Tags: 7
---


title: Custom View Filtered by Taxonomy Term

text:
# Question
Title: Custom View Filtered by Taxonomy Term
I've been reading sites all day trying to figure out what I'm doing wrong or missing, perhaps you can help me. I can't seem to find the right explanation or tutorial.

Situation:

I have a custom View (Content Pane) that generates a Grid of nodes from my Video content type (we'll call it Video Gallery). I created a Page at /videos which includes that Video Gallery content pane in one of the Panels. This is all working very nicely.

I want to be able to filter the results though based on the url, so if they browse to /videos/foo then I'd like to show only the Video nodes which are tagged with the term "foo". This seems to work just fine when I preview the results on the View screen. I've added a Relationship to the Term and added a Contextual Filter on the term id (converted from name). When I type "foo" in the Preview with Contextual Filters box and click Update, then the preview grid below shows exactly what I'd expect (only the Videos tagged with "foo").

My problem:

The view seems to work just fine, but I can't seem to get it to work when actually viewing the page. How do I get my Page configuration to pass along the term argument to the View so that the View can properly filter the results?

I set the path on my custom Page to be `/videos/!videotype`, I've set the %videotype argument so the Context is "Taxonomy term: ID" (with Argument Type = "Term name").. but I can't seem to figure out the rest of the settings.

In my view, I've named my contextual filter "Video Tag Filter" and in my Page configuration, when I edit the Settings on the above View Content Pane, it gives me a dropdown labeled "Video Term Filter" (which is different from Video Tag Filter, I'm not sure where the Video Term Filter name comes from, I've looked through all the menus I can).

It doesn't seem to work though. Can you help me out?

# Answer
Finally found it! In my Views configuration, under the Arguments configuration the incoming Argument was set to use the "Second" argument but the Term Id was the First argument.

I have a different problem now... but I'll post another question.
> 1 votes

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


title: Drupal 7 - Video Contest Website

text:
# Question
Title: Drupal 7 - Video Contest Website
I'm new to drupal and I'm trying to create a video contest website. Each contest will have a time limit (Say 1 month). I need the following basic functionality.

1. Disable upload function after the contest ends.
2. People can vote during the contest but the total rating should be revealed only after the contest ends.

Is there a module for that purpose ? Or should I create a custom module?

Sorry if this is a silly question. I searched everywhere but couldn't find a solution.

Thanks In Advance.

# Answer
> 1 votes
1. You can do this with the Rules module, which includes a Rules Scheduler submodule. (Node One tutorial on Rules Scheduler)
2. You can use Fivestar for voting. To hide the votes, you should be able to use Views.

These are very general suggestions but it sounds like you're in the very early stages of your planning; if you have specific questions, you're welcome to post those later. Basically, you should be able to use existing, well-tested modules for what you're trying to do, although you may need to customize them from time to time to match your specific use case. It's generally not worth your time to write modules from scratch, except as a learning exercise.

---
Tags: 7
---


# Question
Title: How to theme simplenews newsletters in D7?
I'm looking for something like a walk-through. (The guide here, http://drupal.org/node/268404, was apparently written before the D6 rewrite).

The reason I'm after this is that when I use the default simplenews newsletter format, and enter for the subject "test" and for the body "test content" my resulting emails look like this:

```
-------- TES
-----------------------------------------------------------------
Test content**myReport taxonomy**
**myURL**

-- Unsubscribe from this newsletter:
**myUnsubscribeURL**

```

(The contents between the \** are correct, I've left them out for privacy). But you can see the issues are things like:

1. The "t" at the end of "test," the last letter of the header, is left off for some reason.
2. I'm not sure where the hyphens are coming from, or how to modify that formatting decision. I'd like to eliminate the hyphens both before the heading, and between the heading and the body.
3. The body of the email abuts the name of the report taxonomy without space or break.
4. The body of the email comes before the name of the report taxonomy, I'd rather reverse the order.

Can anyone point me to a simple guide to alleviate at least these four problems? Greater customizability would be helpful, but I need to address these for a minimum viable newsletter before getting fancy.

# Answer
This happens because this is the default HTML to Plaintext conversion that Drupal is applying to all mails.

If you don't want this, either adjust the templates (you can find them in the theme folder, just copy to your theme and start adjusting it) to avoid HTML or enable a module like Mime Mail that allows to send HTML formatted mails.

No idea why the title is cut off.
> 1 votes

# Answer
Berdir is right, but I like to use the HTML Mail module instead of Mime Mail. (I show how to do this in a video series, but it's a paid series. If you want, you can check it out at http://modulesunraveled.com/simplenews. But basically you want to use the HTML Mail module.)
> 1 votes

---
Tags: 7, theming, emails
---


# Question
Title: How can I obscure what I am using to run my site?
Is there anything I can do to prevent somebody from knowing my site is using Drupal by looking at the source code of the front page? I am referring to people who scan sites using software that detects the software used to run the website to be able to attack it using any known weak point.

If it is not possible to completely hide the fact that the site is using Drupal, is it at least possible to confuse them (e.g., by aliasing the node pages with URLs like `http://example.com/servlets/<node-id>.jsp`)?

# Answer
> 53 votes
This is an old and already answered question, but I recently put some effort into writing up a description of *all* the things you would need to change:

* Remove the meta generator for Drupal 7
* Remove tell-tale-text like CHANGELOG.txt
* Check the Expires header
* Walking directories for HTTP 200/404/403 status codes
* Look for default text messages - tweak all user-facing messages
* Look at the HTML - default html from core and modules is a telltale sign

Basically: it might technically be possible to hide the fact that your site runs Drupal, but you would spend so much time on it that it's not worth it. You should instead focus on making it secure and on secure operations (e.g. the ability to deploy updates quickly, monitoring logs, etc.).

# Answer
> 100 votes
You can't hide it completely. Most of what's needed to do it, would require hacking core. The biggest tell, is the `Drupal` JavaScript variable which is readable from the front page, or any page for that matter.

If you want to improve your sites security by hiding that it's a Drupal site, your effort is better spent on code reviews than it is on trying to hide the fact that the site is made with Drupal.

# Answer
> 42 votes
It's too easy to do!

* Use a reverse proxy or customize your http daemon to filter the annoying Drupal http header
* Deny http access to any Drupal default folders
* Use PHP output buffering to rewrite and obscure your HTML source, remove unnecessary data
* Use path alias or custom\_url\_rewrite\_in/outbound to make your URLs a mess
* Change the default 404 error, remove/change update.php
* Make any other changes if someone finds out

Last but not least, make sure that your site is so simple that doesn't require JavaScript or CSS for normal behaviors, doesn't use modules like Views, doesn't support user authentication, etc. that means your site should be as simple as a static HTML site.

Anyway, security by obscurity is useless.

# Answer
> 35 votes
There is an official article and discussion regarding the same.

> ## You can't. Do not try
>
> * **Automated attacks (by far the most common attacks) *do not even inspect the server before trying their exploits*.**
> Inspecting the logs of any high-profile site will show thousands of fruitless requests for `/AspBB/db/betaboard.mdb` `_private/cmd.asp` `/scripts/../../winnt/system32/cmd.exe` `/wp-login/` `/administrator/components/com_wmtgallery/admin.wmtgal`, `/cgi-bin/ip.cgi` ... and any number of attempts at historical exploits on any unrelated system.
> *Attacks on exploits happen even if the exploits do not exist on your OS or CMS.* Whatever you do to mis-identify your site will be ignored anyway by amateur hackers.
> * **Whatever you think you can hide, there are other clues** for any system.
> Simply removing the some of all strings that contain 'drupal' does not disguise your site to any reasonable snooper. There are dozens of ways that can be used to guess what is serving your pages, even dedicated services to tell Is that site running Drupal. Just the keywords that *you* recognize and think are a threat are a minor subset of the real indicators.
> Ask for index.php/?q=user . Then try to disable that response without crippling your site.
> * Security by obscurity is no security. It gives a false impression of being 'safe' when you are only hiding vulnerabilities behind a smokescreen that any attacker that posed any real threat would be able to see through.
> * Although it's not entirely impossible to hack the code to the point where *most* traces of Drupal are hidden from the HTML source, (It's Open source after all) the steps required to do so would necessarily break core so badly that **your hacked branch of the code would be incompatible with the *real* security updates** that you could not patch and would genuinely be open to any real future threats identified by the security team. This is a true route to system vulnerability.
> * Most significant or useful modules have their own code 'signature' that is hard to hide without significant rewrites. If you are using 'views', 'cck', 'ad', 'imagecache', 'jquery', css-aggregation, contributed themes or anything useful on your site - *someone can tell*. Hiding that entirely would usually require a total conversion of the theme functions - at least. Even then, obsfucation *probably won't work*.
> * To remove identification of many of the advanced features, like even the easy install of Google Analytics that may use Drupal Libraries to work, you must necessarily either forgo those features altogether, or rewrite them in a way that does not take advantage of the Drupal infrastructure. Sometimes this is possible, but in all cases it is counter-productive.

You may be interested in reading Securing your site too.

Remember Never hack core

# Answer
> 1 votes
I agree with other people that you can't hide it entirely. If you look at the HTML source, you will notice that many times CSS and JavaScript files haven't been aggregated. CSS and JavaScript aggregation should be enabled.

# Answer
> 1 votes
There is no point in hiding that your site runs Drupal. It is the wrong way to look at developing websites. What you should be focusing on is security. Make sure you implement all securities measures and everything will be fine. There is not one reason in the world to hide that you are using a certain cms or other piece of software. With FF addons like Wappalyzer, you can tell in an instant if a site uses Drupal, so the question is pretty moot.

# Answer
> 1 votes
An extra thing you may do is using also the File Aliases module to change the default file structure.

> The File Aliases module allows you to use token customisable aliases for your uploaded files, giving you the ability to keep your file system organised as per usual while providing clean looking paths (i.e., no more /sites/default/files/).

# Answer
> 0 votes
In that past I've swapped my fonts for the typical Ruby project fonts like Lucida Sans, also increasing input sizes like all the hip kids do.

Another give away is the "throbber" graphic for autocomplete fields. It also doesn't work when you increase the input size. Here's one you can steal: http://beta.seattlebedandbreakfast.com/misc/throbber.gif

---
Tags: hooks
---


# Question
Title: How to store some info while user is submitting rating with Fivestar module?
I want to store this rating on different site and I am doing this with the help of RESTful api. I have altered "fivestar\_custom\_widget" form with hook\_form\_alter. My call is not working beacuse it is not removing div which has 'field-name-field-fivestar-rating' class and not adding div which has 'rating-wrapper' id.

```
function recipe_form_alter($form, $form_state, $form_id) {
  if ($form_id == 'fivestar_custom_widget') {
    $form['#submit'][] = 'fivestar_rest_api';
  }
}

function fivestar_rest_api($form, $form_state) {
   $ch = curl_init("http://www.example.com/");
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   curl_setopt($ch, CURLOPT_HEADER, 0);
   $data = curl_exec($ch);
   curl_close($ch);
   $json = json_decode($data,true);
   $errorMessage = $json['errorMessage'];
   $errorCode = $json['errorCode'];
   $commands[] = ajax_command_remove('.field-name-field-fivestar-rating');
   $commands[] = ajax_command_append('#rating-wrapper', 'Thankyou for your rating.');
   return array('#type' => 'ajax', '#commands' => $commands);
 }

```

# Answer
> 1 votes
Submit handler was not working so I have decide to do it with validate handler like this

```

function recipe_form_alter($form, $form_state, $form_id) {
  if ($form_id == 'fivestar_custom_widget') {
    $form['#validate'][] = 'fivestar_rest_api';
  }
}

function fivestar_rest_api($form, $form_state) {
   $ch = curl_init("http://www.example.com/xxx");
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   curl_setopt($ch, CURLOPT_HEADER, 0);
   $data = curl_exec($ch);
   curl_close($ch);
   $json = json_decode($data,true);
   $errorMessage = $json['errorMessage'];
   $errorCode = $json['errorCode'];
   $commands[] = ajax_command_remove('.field-name-field-fivestar-rating');
   $commands[] = ajax_command_append('#rating-wrapper', 'Thankyou for your rating.');
   return array('#type' => 'ajax', '#commands' => $commands);
 }

```

Now it is working fine form me.

---
Tags: forms, ajax, rating
---


# Question
Title: Deleted my secondary_links block; where to find another?
How would I re-add a copy of "secondary links" to my Bartik-themed installation? I seem to have deleted it a year ago when I didn't think I'd want a blogroll, but would like one now.

# Answer
Just create a new menu and add your new links to that you can call it secondary links if you like. Then add it to a region via the blocks menu or with php through your page.tpl.php
> 1 votes

---
Tags: blocks, navigation, nodes
---


# Question
Title: theme('table'...) function doesn't print the table header
I need to generate a table using `theme('table',array('headers'=>$header,'rows'=>$rows));`

The table is printed but with no header. This is the code: I don't see any error nor missing part for the theme function

> ```
>     $header = array(
>     // creating array that contains data from first cell
>     array('data' => t('Header cell1')),
>     // second cell
>     array('data' => t('Header cell2')),
>     // and third cell
>     array('data' => t('Header cell3'))
>   );
>   // creating first row
>   $rows[] = array(
>     // output of first cell in 1 row
>     array('data' => t('Row 1 – Cell 1')),
>     // second cell
>     array('data' => t('Row 1 – Cell 2')),
>     // third cell
>     array('data' => t('Row 1 – Cell 3'))
>   );
>   //second row output
>   $rows[] = array(
>     array('data' => t('Row 2 – Cell 1')),
>     array('data' => t('Row 2 – Cell 2')),
>     array('data' => t('Row 2 – Cell 3'))
>   );
>
>   echo theme('table',array('headers'=>$header,'rows'=>$rows));
>
> ```

# Answer
You are using `theme('table',array('headers' => $header,'rows' => $rows))`, while you should be using `theme('table',array('header' => $header,'rows' => $rows))`. theme\_table() looks for a property called *header*, not *headers*.

> ### Parameters
>
> **$variables**: An associative array containing:
>
> * **header**: An array containing the table headers. Each element of the array can be either a localized string or an associative array with the following keys:
>
> + **"data"**: The localized title of the table column.
>     + **"field"**: The database field represented in the table column (required if user is to be able to sort on this column).
>     + **"sort"**: A default sort order for this column ("asc" or "desc").
>     + Any HTML attributes, such as "colspan", to apply to the column header cell.
> * **rows**: An array of table rows. Every row is an array of cells, or an associative array with the following keys:
>
> + **"data"**: an array of cells
>     + Any HTML attributes, such as "class", to apply to the table row.
>     + **"no\_striping"**: a boolean indicating that the row should receive no 'even / odd' styling. Defaults to FALSE.
>
> Each cell can be either a string or an associative array with the following keys:
>
> * **"data"**: The string to display in the table cell.
> * **"header"**: Indicates this cell is a header.
> * Any HTML attributes, such as "colspan", to apply to the table cell.
> 2 votes

---
Tags: theming
---


# Question
Title: Adding Where clause in Views Query using a custom filter Handler
How can I add a where clause in custom filter handler for views query.

I need to add where clause to alter views query using custom filter handler.

My code in custom filter:

```
class fee_management_handler_filter_payment_status extends views_handler_filter_many_to_one {
  function get_value_options() {
    $this->value_options = array('1' => 'Paid', '0' => 'Unpaid');
  }

    /**
        * Called to implement a payment status.
    */
    function query() {

        if filter = unpaid or 0

        view conditions  + = ' AND pid IS NULL';

        parent::query();
    }
}

```

# Answer
```
function query() {
        parent::ensure_my_table(); #$this->ensure_my_table();
        $alias = $this->table . '_' . $this->view->base_table;
        $operator = ($this->value['0']) ? 'IS NOT' : 'IS';
    $this->query->add_where(0, $alias . '.pid', NULL, $operator . ' NULL');
        #debug($this->query);
        parent::query();
    }

```
> 1 votes

---
Tags: views
---


title: LDAP integration with drupal

text:
# Question
Title: LDAP integration with drupal
I have a LDAP server and my website runs on drupal 6. So i want users from LDAP to access my website using their login details. Which module is preferable for this. i want users to be created on drupal and authentication to happen with LDAP server.

# Answer
Have you already tried this module? http://drupal.org/project/ldap\_integration

We use this on our (drupal) user control panel to let user authenticate from our LDAP database. Personally I haven't installed it myself, I'm using the drupal 7 version, which works great to! http://drupal.org/project/ldap
> 2 votes

---
Tags: 6
---


title: Display total in views

text:
# Question
Title: Display total in views
I'm using Drupal 7 with views 3.

I am listing the fee of students in a view developed using views 3. How can I show the total of fee for all records displayed at bottom as Total Fee. I tried Views\_calc module, but this module is with some errors and notices.

Thanks in advance for your help.

# Answer
> 1 votes
Used this hook

```
function fee_management_views_pre_render(&$view) {
  if($view->name == 'payment_schedules' && ($view->current_display == 'receive_payments')) {
        $total_payable_amount = 0;
        foreach($view->result as $key => $payment) {
            $total_payable_amount += $payment->fee_schedule_instalments_amount;
        }
        $view->attachment_after = "<div> Total Payable Amount: $total_payable_amount</div>"; // does not work with fee_management_views_post_render

    }
}

```

---
Tags: views
---


# Question
Title: How to link up a view created page using hook_menu
I have created a page using view and defined a path for the view. I want to add a tab using `MENU_LOCAL_TASK` from `hook_menu()` How can I add a link to the view for the page callback?

EDIT

I have tried this but does not work.

```
$items['user/%/my-fees'] = array(
        'title' => 'My Fees',
        'description' => 'Student Payment Schedule ',
        'page callback' => 'views_embed_view',
        'page arguments' => array('payment_schedules', 'user_fees', 1),
        'type' => MENU_LOCAL_TASK,
    );

```

# Answer
> 1 votes
`hook_menu()` is not required. We can set the tab, or link, in the view itself under page settings -\> Menu.

I have used the menu options of the view to add the item in my user navigation.

# Answer
> 0 votes
Consider if you have `path/my-view` as path for your views' page.

In your custom module implement hook\_menu in this way

```
function example_menu() {
  $items['path/my-view/psudo-subpath'] = array(
    'title' => 'My Views Title',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );

  return $items;
}

```

---
Tags: views, hooks, navigation, routes
---


# Question
Title: how to download zip file through browser
I have written a module that creates a zip file in the /tmp and then downloads the zip file through browser i.e. it will be downloaded in the ~/Downloads directory by itself.

I don't want to use hook\_file\_download() because it executes everytime you try to download a file, but I want to be specific while downloading. The above code snippet is written in the same function that creates the zip file.

I have taken the help of davidwalsh blog to create the zip file.

I can create the zip file in /tmp directory, but how to download the zip file.

My code looks like this:

```
$fp = fopen($filesystem_filepath, 'rb');
header('Content-type: application/octet-stream');
header('Content-Length: '. filesize($filesystem_filepath));
fpassthru($fp);

```

At first I tried downloading simply using `header()` function and then after more googling I took the help of `readfile($filesystem_filepath)` instead of `fpassthru($fp)` but its not working.

# Answer
> 3 votes
You don't mention exactly what's not working, but at a guess it might be that the download works in all browsers except Internet Explorer?

IE is an annoyance when it comes to forcing downloads, you really have to go around the houses to get all versions to respect what you're trying to do.

Here's the code I use to force downloads, and it works cross browser (updated to address @MPD's comment below):

```
function force_file_download($path, $filename) {
  // Most of this is only necessary because of IE
  header("Cache-Control: public");
  header("Content-Type: application/octet-stream");
  header("Cache-Control: no-store, no-cache, must-revalidate");
  header("Cache-Control: post-check=0, pre-check=0");
  header("Content-Disposition: attachment; filename=\"$filename\";" );
  header("Content-Transfer-Encoding: binary");

  $fp = fopen($path, 'rb');
  fpassthru($fp);
  exit();
}

```

You'd use it in a page callback like this:

```
force_file_download($filesystem_filepath, 'file.zip');

```

That code works perfectly for me for any type of file, cross-browser, and if you change the `exit()` to `drupal_exit()`, it will also work great for Drupal 7 (currently it's a Drupal 6 snippet).

---
Tags: 6, files
---


title: Role based content publishing

text:
# Question
Title: Role based content publishing
* Content created by Role A should not be published and only moderator should be able to publish it.
* Content created by A should publish automatically.

How can this be accomplished in Drupal?

Cheers

# Answer
That's a very broad question so I can only really give a very broad answer. There are two options that I know of for this type of workflow:

1. The aptly named Workflow module

> The workflow module allows the creation and assignment of arbitrary workflows to Drupal node types. Workflows are made up of workflow states. For example, a workflow with the states Draft, Review, and Published could be assigned to the Story node type.
2. A combination of the Workbench and Workbench Moderation modules

> Workbench provides overall improvements for managing content that Drupal does not provide out of the box.
>
> Workbench Moderation adds arbitrary moderation states to Drupal core's "unpublished" and "published" node states, and affects the behavior of node revisions when nodes are published. Moderation states are tracked per-revision; rather than moderating nodes, Workbench Moderation moderates revisions.
> 3 votes

# Answer
I use the Revisioning module to do this. Make the necessary content type(s) subject to revisioning and then grant one role permission to publish subject to moderation and grant the other permission to publish without moderation.
> 2 votes

---
Tags: hooks, workflows
---


title: Passing data to an block

text:
# Question
Title: Passing data to an block
I'm building an webinterface for our ticket system and I'm stuck. When you view an ticket and object **Ticket** is being made (containing the mails and etc.). Now on that same page I have enabled block (writen in the same module) to display some extra information.

Now the problem is, that extra information is found in the Ticket object that page creates. It's stupid to let the block fetch the ticket id and create that object all over again.

*My question is, what is the most efficient way to pass that data to my blocks on that same page?*

# Answer
One method would be to create a central function that you can use to store the object you create, and return it from a static cache when required. That way you only need to create the object once, and other methods in the same page build can pick it up when they need it.

The function might look like this:

```
function MYMODULE_new_ticket_cache($new_object = NULL) {
  // Register the static cache with the system
  $object = &drupal_static(__FUNCTION__, NULL);

  // If we've been passed a new object, update the static cache to store that object
  if ($new_object) {
    $object = $new_object;
  }

  // In all cases, return the stored object (if it's NULL, that will indicate the object hasn't been stored yet)
  return $object;
}

```

When you create your object you would pass it to your caching function like so:

```
$ticket = function_to_create_new_ticket();
MYMODULE_new_ticket_cache($ticket);

```

Then in your `hook_block_view()` implementation you can inspect your cache to see if the object has been set, and use it:

```
$cached_ticket = MYMODULE_new_ticket_cache();

if ($cached_ticket) {
  // Build up your block content
}

```
> 1 votes

---
Tags: blocks
---


title: Menus items appear twice in admin menu

text:
# Question
Title: Menus items appear twice in admin menu
The menus menu items appear twice as shown in the image below. I have tried to disable menu items in the Management menu which had no effect. How can I solve this issue?

# Answer
That is the cause of admin\_menu.module. Upgrade it to the the most current version; it will be fixed. That problem was fixed one or two versions ago.
> 5 votes

---
Tags: routes
---


title: Add a JavaScript file without ?hash

text:
# Question
Title: Add a JavaScript file without ?hash
Is it possible?

I am trying to include a JavaScript plugin that works incorrectly when path is /script.js?hAsh.

# Answer
> 3 votes
I found a solution using the following code.

```
global $base_url;
$path = 'sites/xxx/';
drupal_add_js($base_url . '/' . $path . 'script.js', 'external');

```

# Answer
> 1 votes
The query string you notice is added from drupal\_get\_js() using `$default_query_string`. The comment before the code that initializes it, says:

> A dummy query-string is added to filenames, to gain control over browser-caching. The string changes on every update or full cache flush, forcing browsers to load a new copy of the files, as the URL changed. Files that should not be cached (see `drupal_add_js()`) get `REQUEST_TIME` as query-string instead, to enforce reload on every page request.

The purpose of that query string is simply to avoid the browser uses an old version of the file when it has been (possibly) updated. That happens because the browser, when it gets a request for misc/drupal.js?m5261n, it thinks the file is different from misc/drupal.js?m5507x, and it doesn't use the content it has saved in its cache.

If you would need to include a JavaScript file without using `drupal_add_js()` (otherwise the query string would be always added), you could add the following hook to your module, using code similar to the following one.

```
function mymodule_process_html(&$variables) {
  $variables['scripts'] = . '<script type="text/javascript" src="' . url(drupal_get_path('module', 'mydule') . '/script.js', array('absolute' => TRUE)) . '"></script>';
}

```

As alternative, you could implement `hook_process_html()` using code similar to the following one.

```
function mymodule_process_html(&$variables) {
    $variables['scripts'] = preg_replace('/\.js\?.*"/','.js"', $variables['scripts']);
  }
}

```

You can use a regular expression that matches the filenames you need to use without query strings.

I don't see any reason why your JavaScript code should not work, as there are many JavaScript files that are used from Drupal modules, and they all work with the query string added by Drupal.

Alternatively, if your JavaScript has problems with that query string, you could try implementing the following code.

```
function mymodule_library() {
  // Library One.
  $libraries['library-1'] = array(
    'title' => 'Library One',
    'version' => '1.2',
    'js' => array(
      drupal_get_path('module', 'mymodule') . '/script.js' => array(),
    ),
  );

  return $libraries;
}

```

When you call `drupal_add_library('mymodule', 'library-1')`, the HTML that is added to the page will be similar to the following one.

```
<script type="text/javascript" src="http://tero.local/dr72/modules/mymodule/script.js?v=1.2"></script>

```

# Answer
> 0 votes
I'm curious as to why a JavaScript file wouldn't work with the added GET param (it's a clever way to handle cache of the JS file).

Anyways you could add the JavaScript file without using `drupal_add_js`, either in a module or theme, and that way control the url to the JavaScript file.

# Answer
> 0 votes
@googletorp said it. For more information you can look here: Managing JavaScript in Drupal 7

---
Tags: 7, javascript
---


# Question
Title: Displaying arbitrary HTML (or webgl) inside a Drupal frame (Drupal 7)
I would like to have a page inside my drupal site that would show a webGL Canvas but it seems that Drupal tries to shield its user from doing any direct HTML hacking on a page.

How would one embed a webGL Canvas (or any other arbitrary html for that matter) inside a Drupal page?

# Answer
Depending on your needs, you may also not want to create your HTML page containing a WebGL canvas as *content* managed by Drupal. Instead, you can create a custom module providing a single page with your canvas and the additional JavaScript and CSS files.

```
function MODULE_menu() {
  return array(
    'path/to/canvas' => array(
      'title' => 'Awesome WebGL application',
      'page callback' => 'MODULE_canvas_page',
      'access callback' => TRUE,
      'type' => MENU_CALLBACK,
    ),
  );
}

function MODULE_canvas_page() {
  drupal_add_js(drupal_get_path('module', 'MODULE') . '/module.js');
  drupal_add_css(drupal_get_path('module', 'MODULE') . '/module.css');
  return theme('webgl_canvas');
}

function MODULE_theme($existing, $type, $theme, $path) {
  return array(
    'webgl_canvas' => array()
  );
}

function theme_webgl_canvas() {
  return '<canvas id="glcanvas" width="640" height="480">Your browser doesn\'t appear to support the HTML5 <code><canvas></code> element.</canvas>';
}

```

The `MODULE_menu()` is an implementation of `hook_menu()`. It declares a page available at `path/to/cancvs` and handled by the `MODULE_canvas_page()` function. The handler function adds JavaScript and CSS files using the `drupal_add_js()` and `drupal_add_css()` which allow the files to be aggregated into single `.js`/`.css` files (if that feature is enabled for the site). It then return the markup for the WebGL canvas. The markup is produced by a theme hook function (`theme_webgl_canvas()`) declared in `MODULE_theme` which is an implementation of `hook_theme()`. This allow the theme or other modules to change the markup.

Because a WebGL page/application would likely use a lot of custom JavaScript, you may also want to check the Managing JavaScript in Drupal 7 guide.
> 5 votes

# Answer
Drupal uses input filters which can be setup to allow any html or limit the allowed html a user can input. You will need to configure and select a input filter that allows you to enter the html you want to display.

Other than that - Drupal won't do any limitations on the HTML allowed.
> 1 votes

---
Tags: 7, theming
---


# Question
Title: Using theme_username() with no link to user page?
I use this theme function to show the username of user:

```
 theme('username', array('account' => user_load($record->uid)))),

```

It works fine but the username is also a link to the user page. I just need to the username with no link at all.

I read the doc at:

http://api.drupal.org/api/drupal/includes%21theme.inc/function/theme\_username/7

and I see that there is the argument `link_options` to handle this, then I guessed it was a bolean value and tried with (but not working):

```
theme('username', array('account' => user_load($record->uid), 'link_options' => 0))),

```

# Answer
> 3 votes
`theme_username()` will only output the username as a link if the `link_path` variable has been set. This is done by default in `template_preprocess_username()`, and will happen as long as the user viewing the username has access to view the profile.

If you want to change that behaviour you just need to add your own preprocess function which removes the `link_path` variable:

```
function MYTHEME_preprocess_username(&$vars) {
  if (isset($vars['link_path'])) {
    unset($vars['link_path']);
  }
}

```

Bear in mind that the above will remove the link system wide. If you want to remove just for this specific instance, I think the best way would be to pass a custom variable to the theme function and check for it in your preprocess function:

```
$vars = array('account' = user_load($record->uid), 'surpress_link' => TRUE);
$name = theme('username', $vars);

function MYTHEME_preprocess_username(&$vars) {
  if (isset($vars['link_path']) && isset($vars['surpress_link']) && $vars['surpress_link']) {
    unset($vars['link_path']);
  }
}

```

# Answer
> 2 votes
Depending on what you want to do exactly, there's also format\_username() that allows you to return a properly formatted username (e.g. integrated with realname.module), without any kind of link/HTML.

Note that this function returns an unsafe string (as unsafe as $user-\>name is), so you need to check\_plain() it.

---
Tags: theming
---


title: Fill field value automatically

text:
# Question
Title: Fill field value automatically
So let's say I have a content type Product with two fields: name and date. I want to have another field called profit to be filled in automatically according to the name of the product. Any ideas on how I can do that easily?

# Answer
I suggest you to give to the Computed Field module a try. It seems that it does exactly what you need.

> Computed Field is a very powerful CCK field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of CCK fields. So start cooking up your PHP based values!
> 2 votes

# Answer
Here is a javascript solution for this. For instance:

```
(function ($) {
  $("#edit-field-name-und-0-value").change(function(){
      $("#edit-field-profit-und-0-value").val(this.value);
    });
})(jQuery);

```

When the user updates the Name field it will also update the Profit field.
> 0 votes

---
Tags: entities
---


# Question
Title: Menu subitems only displaying on a single page
I have several menu items in our main menu, and each of them has several sub-items. All of them display correctly EXCEPT one - this particular menu only displays the top-level menu item, unless you're actually on the page that the top-level item links to - then it displays all the dropdown sub-items.

The only difference in the non-working menu is that the sub-items link to external sites, rather than internal pages.

Here's the menu setup:

The Featured Exhibitor menu works - i.e. the dropdown displays on all pages. The Contact menu doesn't work - on all pages, all you see is the top-level Contact link. When you click that and are taken to /contact, the menu suddenly displays all the dropdown links. Because the sublinks are to external sites, there are no issues with node permissions or anything, and even if there had been, at least things would have been consistent (they wouldn't have displayed anywhere if the user didn't have access.)

Here's the menu displayed on /contact:

We've tried switching the theme to see if there was something funky about ours, but it does the same thing no matter what template we try. Any idea what would cause this?

**EDITED TO ADD**

When I look at the rendered source, the subitems of the contact menu are not included on pages other than /contact. So it doesn't seem to be a style issue.

# Answer
So it turns out that the particular theme we're using relies on the Show as Expanded option on the top-level menu items to determine that it should display as a fly-out.
> 0 votes

---
Tags: routes, navigation
---


title: Remove only admin info in nodes

text:
# Question
Title: Remove only admin info in nodes
I'm using Drupal 7 and Clean theme. And i want remove only submitted by admin, dont remove date info.

Looked node.tpl.php and node.module files but not seen this fields. How can i remove this info?

# Answer
Remove $submitted from your template and use below code

`$timestamp = $node->created;
print format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL);`
> 0 votes

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


# Question
Title: Using SimpleTest to test an image upload
I have a basic test written (per http://drupal.org/simpletest-tutorial-drupal7) but I am unsure how to proceed to test an image field.

```
public function testSimpleTestExampleCreate() {
    // Create node to edit.
    $edit = array();
    $edit['title'] = $this->randomName(8);
    $edit["body[und][0][value]"] = $this->randomName(16);
    $this->drupalPost('node/add/simpletest-example', $edit, t('Save'));
    $this->assertText(t('Simpletest Example Node Type @title has been created.', array('@title' => $edit['title'])));
}

```

So this will create a node with a title and body. How should I modify this to allow it to test uploading an image as well? Would I just add another key to $edit of 'files\[image\_image\_und\_0\]' with the path to the image to be uploaded? But I think something else needs to be done since you have to click "Upload" before you save the node.

# Answer
There is a base image field test class in image.module, which has a uploadNodeImage() method. You can either re-use that by extending from that class or steal the code there.

See testStyleReplacment() for an example of how it is used.

Edit: The "Upload" is optional and only necessary if you want to upload multiple files. You can always just save the node directly and any selected files will be uploaded and processed.
> 2 votes

---
Tags: media, testing
---


title: Add javascript to a specific node

text:
# Question
Title: Add javascript to a specific node
I want to add some extra javascript (few files stored in my account, and some inline javascript) for a specific node. Based on the answer to this question, I tried adding a few files to the node alias "insert-pub" by doing this in the template.php in /themes/garland (just trying out the garland theme for now):

```
  function garland_preprocess_node(&$vars) {
     // The line below was already there.
     $vars['submitted'] = $vars['date'] . ' â€” ' . $vars['name'];
     // Added the lines below.
     // Want to include my javascript files and inline scripts for specific nodes.
     $node =& $vars['node'];
     debug($node);
     debug($node->type);
     if ($node->type == 'insert-pub')
     {
          drupal_add_js('/sites/all/scripts/MyLib.js', array('type' => 'file', 'scope' => 'header'));
          drupal_add_js('/sites/all/scripts/Utils.js', array('type' => 'file', 'scope' => 'header'));
          drupal_add_js('var MyAjaxLib=new MyLib();
               function loadInput(){ alert("Hello"); }', 'inline');
     }
}

```

But I never see the links to the JS files or inline JS scripts in the source of the page, when I load the page in the browser by going to \[www.mysite.com/insert-pub\]. Where am I going wrong? Even the debug() calls above does not seem to print anything in the browser.

I am a Drupal 7 newbie, so looking forward to some hand-holding. Thanks.

# Answer
> 4 votes
The node type will always have an underscore as the separator (not a dash) between words so the test would be:

```
if ($node->type == 'insert_pub') {
  // ...
}

```

But it seems from your question you want to test the URL alias of the node, not the type. To do that you need to use `drupal_get_path_alias()` to get the node's alias, and see if it matches:

```
$current_node_alias = drupal_get_path_alias("node/$node->nid");
if ($current_node_alias == 'insert-pub') {
  drupal_add_js('...
}

```

Make sure you've cleared Drupal's caches so the new preprocess hook can be picked up by the system. That's the only reason I can think of to explain the calls to `debug()` not working, as they should.

---
Tags: javascript, path-aliases, theming
---


# Question
Title: how to update the form values after pressing the submit button
Below I have written code for update but when I change the value in form and press submit button still those old values goes to the database. My question is how to get current edited value of my form after it is displayed?

```
function upgrade_menu(){
    $items = array();
    $items['upgrade_page'] = array(
    'title' => t('Upgrade'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array(' upgrade_update'),
    'access callback' => TRUE,
    );
    return $items;
}

function upgrade_page($form, &$form_state) {
    if (!isset($form_state['storage']['upgrade_module']['search_criteria'])) {
        return drupal_get_form('upgrade_form');
    }
    $title = $form_state['input']['Name'];
    $query = db_select('form_test', 'n')
    ->condition('name', $title, '=')
    ->fields('n',array('name','Id','age','email','salary'));
    $results = $query->execute();
    $res = $results->fetchAssoc();
    $form['Name'] = array(
        '#title' => t('Name'),
        '#type' => 'textfield',
        '#value' => $res['name'],
    );
    $form['Id'] = array(
        '#title' => t('Id'),
        '#type' => 'textfield',
        '#value' => $res['Id'],
    );
    $form['Age'] = array(
        '#title' => t('Age'),
        '#type' => 'textfield',
        '#value' => $res['age'],
    );
    $form['Emailid'] = array(
        '#title' => t('Emailid'),
        '#type' => 'textfield',
        '#value' => $res['email'],
    );
    $form['Salary'] = array(
        '#title' => t('salary'),
        '#type' => 'textfield',
        '#value' => $res['salary'],
    );
    $form['submit'] = array(
        '#value' => 'Update',
        '#type' => 'submit',
        '#submit' => array('upgrade_update'),
    );
    return $form;
}

function upgrade_form($form, &$form_state) {
    $form['criteria'] = array(
        '#type' => 'fieldset',
        '#title' => 'Update',
        '#attributes' => array('class' => array('container-inline')),
    );
    $form['criteria']['Name'] = array(
        '#type' => 'textfield',
        '#title' => t('Name'),
        '#value' => (isset($form_state['input']['Name'])) ? $form_state['input']['Name'] : "",
        '#size' => 10,
        '#maxlength' => 20,
    );
    $form['criteria']['submit'] = array(
        '#type' => 'submit',
        '#value' => 'search',
        '#submit' => array('upgrade_submit'),
    );
    return $form;
}

function upgrade_submit($form, &$form_state) {
    $form_state['storage']['upgrade_module']['search_criteria'] = $form_state['values'];
    $form_state['rebuild'] = TRUE;
}

function upgrade_update($form, &$form_submit) {
    $name =  $form_submit['values']['Name'];
    $Id = $form_submit['values']['Id'];
    $age = $form_submit['values']['Age'];
    $email = $form_submit['values']['Emailid'];
    $salary = $form_submit['values']['Salary'];
    drupal_set_message(t('You provided a  name',array('name' => $name)));
    drupal_set_message(t('You provided a  Id',array('Id' => $Id)));
    drupal_set_message(t('You provided a  age',array('age' => $age)));
    drupal_set_message(t('You provided a  email',array('email' => $email)));
    drupal_set_message(t('You provided a salary',array('salary' => $salary)));

    $entry = array(
        'name' => $form_submit['values']['Name'],
        'id' => $form_submit['values']['Id'],
        'age' => $form_submit['values']['Age'],
        'email' => $form_submit['values']['Emailid'],
        'salary' => $form_submit['values']['Salary'],
    );
    $table = 'form_test';
    $return_value = db_update($table)
    ->fields($entry)
    ->condition('email',$email,'=')
    ->execute();
    print drupal_set_message('Database is successfully Updated..');
    return $return_value;
}

```

# Answer
You're mixing up #value and #default\_value. If you want to show information in the form but let the user change it, you need to use `#default_value`. If you want the information to always be the same, and never let the user change it, use `#value`.
> 1 votes

---
Tags: updating
---


title: What are "#" properties?

text:
# Question
Title: What are "#" properties?
While reading the Ajax framework documentation I came across mention of the `#ajax` property. I know from poking through the code that there are others of these properties with hash signs in front of them. What does the hash sign signify? What are these properties all about?

# Answer
> 23 votes
This is to do with render arrays in general, it's not just specific to AJAX or the form API (although the form API uses render arrays exclusively for building up it's content).

Put simply, array keys in a render array without a `#` in front of the name are seen as children of the render array, and are subsequently rendered themselves (recursively).

Those *with* a `#` in front of them are seen as meta data/variables for the render array to use as necessary, and are not themselves rendered.

The render array docs (linked to above) actually put this nice and succinctly:

> A render array is a classic Drupal structured array that provides data (probably nested) along with hints as to how it should be rendered (properties, like #type).

The `#` keys are the 'hints' that the above paragraph is talking about, the non-`#` keys are the nested data.

I'd thoroughly recommend giving that page a read, it does a good job of de-mystifying the whole render array thing, and provides code examples.

There's also another small explanation/code example on the Theming the page docs which might be useful.

Render arrays are used all over the place in Drupal (forms, themes, general markup, etc.) so knowing a good bit about them will help a lot with future Drupal development.

# Answer
> 4 votes
The form API uses a # in front of all the properties, to make a distinction between properties, and child elements. In the following code, `$form['choice_wrapper']['choice']` is a child element, while `$form['choice_wrapper']['#tree']` is a property.

```
  // Add a wrapper for the choices and more button.
  $form['choice_wrapper'] = array(
    '#tree' => FALSE,
    '#weight' => -4,
    '#prefix' => '<div class="clearfix" id="poll-choice-wrapper">',
    '#suffix' => '</div>',
  );

  // Container for just the poll choices.
  $form['choice_wrapper']['choice'] = array(
    '#prefix' => '<div id="poll-choices">',
    '#suffix' => '</div>',
    '#theme' => 'poll_choices',
  );

```

All those properties are listed in the Form API reference. There are many properties, but they are all about rendering, validation, and submission.

The reason to use a prefix for properties is to able to quick filter out the properties from the child elements, which is useful when they need to be rendered, for example with drupal\_render(), which contains the following code.

```
  // Get the children of the element, sorted by weight.
  $children = element_children($elements, TRUE);

  // Initialize this element's #children, unless a #pre_render callback already
  // preset #children.
  if (!isset($elements['#children'])) {
    $elements['#children'] = '';
  }
  // Call the element's #theme function if it is set. Then any children of the
  // element have to be rendered there.
  if (isset($elements['#theme'])) {
    $elements['#children'] = theme($elements['#theme'], $elements);
  }
  // If #theme was not set and the element has children, render them now.
  // This is the same process as drupal_render_children() but is inlined
  // for speed.
  if ($elements['#children'] == '') {
    foreach ($children as $key) {
      $elements['#children'] .= drupal_render($elements[$key]);
    }
  }

```

If you look at element\_children(), you will notice the code to filter out properties is the following one.

```
  // Filter out properties from the element, leaving only children.
  $children = array();
  $sortable = FALSE;
  foreach ($elements as $key => $value) {
    if ($key === '' || $key[0] !== '#') {
      $children[$key] = $value;
      if (is_array($value) && isset($value['#weight'])) {
        $sortable = TRUE;
      }
    }
  }

```

---
Tags: 7
---


title: Trying to get a localhost copy working

text:
# Question
Title: Trying to get a localhost copy working
I've transferred all of the files for a Drupal build to my localhost, imported the database into my local WAMP server, however when I try to access the drupal build on my localhost, it keeps giving me an error, saying it cannot connect (connection reset). Other sites on localhost work fine.

What would cause this?

The connection details are the following ones:

```
array('database' => 'default_drupal',
  'username' => 'default_drupal',
  'password' => '1r3s3tM3',
  'host' => 'localhost',
  'port' => '',
  'driver' => 'mysql',
  'prefix' => '',
);

```

I created an account using the account default\_drupal on the default\_drupal database, so it should work.

# Answer
I had the same problem. For me it was due to the "Coder" module. It was caused by a multi-line description in the coder\_upgrade.info file (I don't know why that was a problem). So if you have installed that module, then open coder\_upgrade.info and change the description to fit in one line.

If that's not your problem then try these following steps:

1. Move each module outside the modules folder and reload the webpage each time you do this. If the problem is caused by a module then you can make modifications as necessary.
2. Try upgrading or reinstalling your **WAMP** server.
3. If you had enabled **caching** in your production server, then follow this link.(**Note** : The article is for Drupal-6. You can find the code for drupal-7 in their comments section)
> 0 votes

# Answer
Are you using any Drupal performance optimizations on the site that's the source of your imported database? This article suggests turning them off and gives a query to accomplish that.

Once you've got your local site up and running, I also suggest trying the Backup and Migrate module to manage your data migration. You can create a backup profile that omits your live server's cache data, which makes for a smaller backup file and may mitigate the problem you're having now.
> 0 votes

---
Tags: migrations
---


# Question
Title: Adding stylesheets for an internal page only
I am trying to add a CSS file to a specific internal basic page in Drupal 7 with no success.
After enabling the clean URL paths and add a path for my internal basic page I am able to capture the path using `$path=drupal_get_path_alias();`.

After that, I am trying to put condition statements so when a specific path is loaded a specific CSS file is loaded. I have this piece of code in `ninesixty_preprocess_page(&$vars, $hook)` in the template.php file.

```
if($path == 'about/advantages') {
  drupal_add_css(drupal_get_path('theme', 'ninesixty') . "/page-about.css");
}

```

I have tested the IF-statement by echoing the `$path` variable with total success. The page-about.css file does not load at all, though.

Please note that I am using Drupal with WAMP server, and the page-about.css file is located under drupal/sites/all/themes/ninesixty/styles/framework.

# Answer
The path is incorrect; it should be as in the following code.

```
if ($path == 'about/advantages') {
  drupal_add_css(drupal_get_path('theme', 'ninesixty') . "/styles/framework/page-about.css");
}

```
> 4 votes

# Answer
For adding CSS files to specific pages, you can use the CSS Injector module.

> Allows administrators to inject CSS into the page output based on configurable rules. It's useful for adding simple CSS tweaks without modifying a site's official theme—for example, a 'nighttime' color scheme could be added during certain hours. The CSS is added using Drupal's standard `drupal_add_css()` function and respects page caching, etc.
>
> This module is definitely not a replacement for full-fledged theming, but it provides site administrators with a quick and easy way of tweaking things without diving into full-fledged theme hacking.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Manage custom modules across multiple installations
We have some custom modules which are used for multiple sites. Those can't be released as contributed modules, for example because they are client specific, make assumptions that don't work for contributed modules and so on.

I know about the following possibilities to deal with this:

* copy & paste them around. Makes it obviously hard to keep the module up to date on all installations.
* Have a single multi-site installation, but this isn't always possible.
* Use git submodules, but they can be nasty, it's easy to forget to update them and aren't always supported (e.g. Pantheon)
* Drush make scripts to check out from a common git repository. For this, you AFAIK need to use drush make for the whole site and we don't use it currently.
* http://drupal.org/project/fserver. I haven't tried that out yet, does someone know if it is stable enough? The project description doesn't sound very promising and there is no 7.x version.

Anything else/better? What do you prefer and why?

# Answer
The Drush make approach, as you've already mentioned, is the version my team is using.

Even though you are not currently using drush make for your sites, it should be relatively straightforward for you to move to this workflow if you want as drush also provides drush make-generate which will generate the make file from an existing site. Thus no need to feel like it's only worth it for new sites. :)
> 10 votes

# Answer
If all sites are on the same server, you can use `symlink` to load modules from a central place, or `rsync` if you are dealing with multiple servers.

This will solve the problem of distributing files, but you still need to fire an upgrade. It can be automated with `drush`, along with a simple script that calls upgrade on every sites, one-by-one.
> 1 votes

# Answer
Seems to be that you almost look pretty much to all solutions. When I read it, first what come in my mind its two others solutions like `rsync` or `symlink` but again it's not comfortable to maintain.

Then in remembered about that module Git Deploy that actually be a nice combo with git submodules.

I haven't tried yet this idea, but it could work, or at least give you some clue how to hack it to do your own system.
> 0 votes

# Answer
I use a separate git repository for all contributed/custom modules where each contributed or custom module is in a separate branch (not in a submodule).

here is how the git merge works here:

master

```
      <-- custom
        <-- custom module 1
        <-- custom module 2

      <-- contrib
        <-- contrib module 1
        <-- contrib module 2

```

master --\> release

and a bash/drush script to update the branches
> 0 votes

# Answer
I use SVN instead Git to store our custom developed modules. After I commit change from localhost, I just run the bash script which runs the "svn update" command at predefined server locations. Whenever I deploy a module to a new location, I update the bash script. It is really a simple setup and works without any hassle.
> 0 votes

---
Tags: version-control, deployment, drush
---


# Question
Title: Trimmed body field only show first paragraph
(update: it not a problem relate to uppercases) I think I found a bug but not sure which module is causing it. Maybe CCK...

I have a content type with the body field set (through manage display) to be shown as **Trimmed** to lenght: 400

Then I created a node with 2 paragraphs of text in the body . When I load the full view of the node the trimming only shows the first paragraph

the trimming works fine if I enter this text in the body:

```
some text, some text, some text, some text, some text, some text, some text, some text

```

the trimming also works fine if I enter this text in the body **(notide that the second paragraph is a short paragraph)**

```
both paragraph are shown
some text, some text, some text, some text, some text, some text, some text, some text

```

but only the first paragraph is shown if I enter this text in the body **(notice that the second paragraph is longer)**

```
only this paragraph is shown
some text, some text, some text, some text, some text, some text, some text, some textsome text, some text, some text, some text, some text, some text, some text, some textsome text, some text, some text, some text, some text, some text, some text, some textsome text, some text, some text, some text, some text, some text, some text, some textsome text, some text, some text, some text, some text, some text, some text, some text

```

How can I solve this?

# Answer
> 1 votes
Your best bet is a custom formatter. Create a custom formatter with the custom formatters module:

> The Custom Formatters module allows users to easily create custom CCK/Field Formatters without the need to write a custom module. Custom Formatters can then be exported as CTools Exportables/Features or Drupal API Formatters.

Once installed just write some php code and format and insert the particular text that you're looking for.

---
Tags: views, entities
---


# Question
Title: Getting the number pad to show up for text fields
I would like to make entering data easier for my users who use the mobile version of my site. I've been searching around both Android and Drupal documentation and eventually found this: https://stackoverflow.com/questions/3372380/how-to-force-keyboard-with-numbers-in-mobile-website-in-android

Which says that using

```
<input type="number" />
<input type="tel" />

```

will bring up the number pad for the user.

I would like to figure out the best way to change all of my integer and decimal fields to have `type="number"`.

I'm aware of doing a `hook` to do this but I have a lot of fields which are numbers and I was wondering if there was a more effective way to change ALL the fields rather that me writing a line for each of the fields. Maybe if I had an array of all the fields and then programically went through all the fields in the array?

Thanks

# Answer
hook\_field\_widget\_form\_alter

> Alter forms for field widgets provided by other modules.

or use hook\_field\_widget\_WIDGET\_TYPE\_form\_alter to hook into the Number field specifically.

```
/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 */
function mymodule_field_widget_number_form_alter(&$element, &$form_state, $context) {
  $element['#type'] 'number';
}

```
> 2 votes

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


# Question
Title: mysql_query doesn't work but db_query does on a simple SELECT query
I'm receiving the following warning when I use `mysql_query()` in my modules.

> mysql\_query(): A link to the server could not be established on line 6

If I use `db_query()`, it works fine.

The code is a simple query with no special characters or variables: `mysql_query("SELECT * FROM custom_nodify WHERE nid = 345");`.

I should mention that this happens with any call to `mysql_query()`.

Do you know why this doesn't work?

# Answer
> 7 votes
Just to start with let me very clearly say, never **ever** use `mysql_query` unless you really have to (multiple databases with different backends fx).

Why? `db_query` has a lot of security features built in to help prevent SQL injections, and it makes your site database agnostic (you won't have to change code if you change the database backend) and it allows you to use table prefixes without hardcoding them in the queries.

Anyways the reason why mysql\_query doesn't work is because you need to create a connection to the database first using the database credentials, something drupal does automatically for you, when you use db\_query.

If you really want to throw away all the good Drupal does for you and use mysql\_query anyways, take a look at `mysql_connect`.

---
Tags: 6
---


# Question
Title: What tools do I need to automate my Drupal workflow?
What tools do I need to automate the following tasks:

**Project setup**

1. Generate project wide password
2. Setup prod domain and dev and stage subdomain on server
3. Create user with access to /bin/bash/
4. Add public keys
5. Change open\_basedir and increase memory limit
6. Delete files in document root
7. Initialize Git repo on Git hosting
8. Clone Drupal Repo Recursively
9. Add .gitignore (including Mac, Drupal and SASS specific paths)
10. Create Zen/Omega Subtheme
11. Create drushrc.php & aliases.drushrc.php
12. Commit changes
13. Create dev branch
14. Add Git remote and Push the branch master to it
15. Create databases for prod, stage and dev
16. Run site-install
17. Setup cron
18. sql-sync and rsync from prod to stage and dev
19. Fix file permissions

# Answer
The quickstart project will handle almost all of these tasks. It is basically a preconfigured drupal development environment that you run in a virtual machine.

If you wanted to install the tools locally, you can do almost everything in your lists with drush & make.
> 4 votes

---
Tags: 7, deployment
---


# Question
Title: Seeing if node has been changed in custom submit handler
I have written a custom submit handler that gets called whenever a certain content type is edited.

I was wondering if there was a flag in `$form_state` that indicates whether the node was actually edited vs whether someone is just clicking the `save` button without actually changing anything. I am wondering because I would like to perform an action only if the node is edited. Thank you

```
function hook_form_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = '_unpublish_new_product';
}

function _unpublish_new_product($form, &$form_state) {
   // is there a flag in $form_state that indicates if any fields were changed so I
   // could perform a conditional action??
}

```

# Answer
As far as I know, there isn't such flag, but you can use entity\_load\_unchanged() to get a copy of the entity before any change, and compare the field value with the one you get from the form.

The function is called, for example, from node\_save(), which contain the following code.

```
// Load the stored entity, if any.
if (!empty($node->nid) && !isset($node->original)) {
  $node->original = entity_load_unchanged('node', $node->nid);
}

field_attach_presave('node', $node);
global $user;

// Determine if we will be inserting a new node.
if (!isset($node->is_new)) {
  $node->is_new = empty($node->nid);
}

// Set the timestamp fields.
if (empty($node->created)) {
  $node->created = REQUEST_TIME;
}
// The changed timestamp is always updated for bookkeeping purposes,
// for example: revisions, searching, etc.
$node->changed = REQUEST_TIME;

$node->timestamp = REQUEST_TIME;
$update_node = TRUE;

// Let modules modify the node before it is saved to the database.
module_invoke_all('node_presave', $node);
module_invoke_all('entity_presave', $node, 'node');

```

This means that the implementations of hook\_field\_attach\_presave(), hook\_node\_presave(), and hook\_entity\_presave() will get the unchanged version of the node object in `$node->original` (or `$entity->original`); if you are writing code for one of these hooks, you don't need to call `entity_load_unchanged()` because `node_save()` already did it for you.

Similar code is present in comment\_save(), taxonomy\_term\_save(), taxonomy\_vocabulary\_save(), and user\_save().

```
if (!empty($comment->cid) && !isset($comment->original)) {
  $comment->original = entity_load_unchanged('comment', $comment->cid);
}

field_attach_presave('comment', $comment);

// Allow modules to alter the comment before saving.
module_invoke_all('comment_presave', $comment);
module_invoke_all('entity_presave', $comment, 'comment');

```

```
  if (!empty($term->tid) && !isset($term->original)) {
    $term->original = entity_load_unchanged('taxonomy_term', $term->tid);
  }

  field_attach_presave('taxonomy_term', $term);
  module_invoke_all('taxonomy_term_presave', $term);
  module_invoke_all('entity_presave', $term, 'taxonomy_term');

```
> 9 votes

# Answer
As far as I know there isn't such a flag. You will have to compare the values yourself I think. For node forms I made this first attempt to compare the node data. This is just a quick idea how a solution could be, maybe I am missing some edge cases where this isn't working, but in my tests with a simple default "page" node form it was working well. (I used the "Preview" button for reloading the form and testing.)

As Mohammad Ali Akbari says, `hook_presave()` might be a better place to compare the data, but the comparison of the flatted arrays should work there, too.

Attribution for the flatten function goes to Rob Peck.

```
/**
 * @file mymodule.module
 * Do stuff.
 */

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Proof of concept of checking for changes to a node in form submit.
 * Uses the default "page" content type.
 *
 * You need devel module to see an nice Krumo of the fields that have changed.
 */
function mymodule_form_page_node_form_alter(&$form, &$form_state, $form_id) {
  //Get uncached data of the current node from the db.
  //Cast the node object to an array so we can use the flatten function
  //and php array_diff functions.
  $node_array_db = (array) node_load($form['#node']->nid,NULL, TRUE);

  //Throw away the changed value as this is alwasy different.
  unset($node_array_db['changed']);

  //Cast the node object to an array so we can use the flatten function
  //and php aray_diff functions.
  $node_array_form = (array) $form_state['node'];

  //The $node object from the form holds some metadata. Throw away the fields
  //in the forms $node object/array that are not in the version from the db.
  $node_array_form = array_intersect_key($node_array_form,$node_array_db );

  //Flatten the nested array structure so we can use array_diff for comparing no
  //matter what the fields are structured.
  $result = array_diff(flatten($node_array_form), flatten($node_array_db));

  //Print all fields with differences in the field values.
  dpm($result);

  if (empty($result)) {
    dpm('No Changes');
    //No changes. Just "Save" was pressed.
  }
  else {
    dpm('There are different field values in this form than those in the database.');
    //Do something.
  }

}

/**
 * Function for flattening an array.
 *
 */
function flatten($arr, $base = "", $divider_char = "/") {
  $ret = array();

  if (is_array($arr)) {
    foreach ($arr as $k => $v) {
      if (is_array($v)) {
        $tmp_array = flatten($v, $base.$k.$divider_char, $divider_char);
        $ret = array_merge($ret, $tmp_array);
      }
      else {
        $ret[$base.$k] = $v;
      }
    }
  }
  return $ret;
}

```
> 5 votes

---
Tags: 7, forms
---


# Question
Title: Print out $view object in custom field template
I've created a custom template for a field to display in my view. Based on the view theming information, I've named the file views-view-field--at-a-glance-test--page--field-track-icon.tpl.php (the view is called at-a-glance-test, the display is a page, and the field is field\_track\_icon.

The sample code given for a views-view-field template has the following comments:

```
/**
* Variables available:
  * - $view: The view object
  * - $field: The field handler object that can process the input
  * - $row: The raw SQL result that can be used
  * - $output: The processed output that will normally be used.
**/

```

I want to know what all is coming through in the view object, so I tried to do `print_r($view)`. All I get is a completely blank page - there's not even a single line displayed in the rendered source. Usually this happens if there's a PHP error somewhere - am I doing something wrong? How can I print out the full contents of the view object?

**EDIT**

I just looked at our php error log and saw this:

> PHP Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 117789481 bytes) in /home/www/expo/includes/theme.inc on line 1414

So obviously the view object is enormous... how else can I see what is coming through, since I have no control over our server's memory limits?

**EDIT AGAIN**

Per @Clive's comment below, I tried using dvm() instead of print\_r, and did get some (a ridiculous amount) of output. Given that this is a template to override the display of a single field, I really want to see just the data for that particular field. So I tried dvm($field), and ended up with literally thousands of lines of nested arrays and objects. It's not pulling in just the data for this particular field, it's displaying data for the entire view, even though I passed in the field variable.

So then I tried dvm($row-\>field\_track\_icon), and got about 100 errors (`Notice: Undefined property: stdClass::$field_track_icon in include() (line 28 of /home/www/expo/sites/all/themes/bluemasters/views-view-field--at-a-glance-test--page--field-track-icon.tpl.php).`) The template comments state to use `$data = $row->{$field->field_alias}` as the format; first, what's the difference between field and field alias? I've attached a screenshot of the taxonomy term that the field I need is attached to. The field is called field\_track\_icon. What is the alias? Second, do I need the curly braces?

What do I need to do to get just the data for one specific field?

# Answer
Try to set the memory limit in your settings.php to something like this..

```
ini_set('memory_limit', '128M');

```

The above code will override your server php.ini settings. Take note that this may result instability of server and may attract suspension of your account.

You may need to ask your hosting support if possible.
> 0 votes

---
Tags: 7, views, theming
---


# Question
Title: Date Display: How to hide part of repeat rule?
When displaying recurring event dates for end users I would like to hide a part of the repeat rule (the until date has no meaning for end users):

Current display:

> Repeats every week every Thursday until Mon Dec 31 2012

Expected display:

> Repeats every week every Thursday

How to do this ?

# Answer
The recurrence description is defined in date\_repeat\_rrule\_description() in date\_repeat.module.

At this time, there is no way for themes to change it. See this issue: http://drupal.org/node/342665

**EDIT**

Actually, you may override `theme_date_repeat_field()`, which calls `date_repeat_rrule_description()`. You could call your own version of that function to customize the display.

This would leave the contrib modules untouched, but you would be duplicating some effort and have more code to maintain.
> 5 votes

---
Tags: 7, datetime
---


title: Move CSS and JS cache folder

text:
# Question
Title: Move CSS and JS cache folder
I want to move the CSS and JS cache folders (`sites/default/files/css` and `sites/default/files/js` to another place. Is this possible?

I want to do this because I'm planning to have the `files` folder on a remote file system and I think that accessing the CSS and JS from remote would slow down the site.

Edit: I'm using Drupal 6.

# Answer
I'm not saying this is the best or correct way to do it, but I think you could use `hook_file_url_alter` to change the url for your script and stylesheets:

```
 function hook_file_url_alter(&$original_uri) {
      // rewrite url for your javascript files
      if(strstr($original_url, 'sites/default/files/your-script.js')) {
          $original_url = 'http://example.com/js/your-script.js';
      }
 }

```
> 1 votes

# Answer
Try using File Aliases

> The File Aliases module allows you to use token customizable aliases for your uploaded files, giving you the ability to keep your file system organized as per usual while providing clean looking paths (i.e., no more '/sites/default/files/').

## Features:

* Customizable File Alias field using **Node** tokens.
* Support for:
    + Drupal core Upload module.
    + FileField module.
    + ImageField module.
    + Image module.
    + Comment Upload module.
* Support for Private and Public file systems.
* Support for Views output (Fields and Nodes).
* Support for FileField Paths Retroactive and Active Updating.

## Required Modules:

* FileField Paths (6.14 or greater)
> 1 votes

---
Tags: 6, caching, files
---


title: Form Load and Unload

text:
# Question
Title: Form Load and Unload
What are the functions in Form API that perform the task just like form load and unload I want to perform few checks when the form loads and delete those checks when the form is unloaded.

```
           function form_example_form($form, &$form_state) {
                 $form['search'] = array(
                '#type' => 'textfield',
                '#title' => t('Search for Members'),
                '#size' => 60,
                '#maxlength' => 128
                );
                $form['submit'] = array(
                '#type' => 'submit',
                '#value' => t('Search'),
                '#submit' => array('myform_newform_submit'),
                );
                 $header = array(
                    array('data' => t('ID'), 'field' => 't.id'),
                    array('data' => t('First Name'), 'field' => 't.fname'),
                    array('data' => t('Last Name'), 'field' => 't.lname'),
                    'operations' => array('data' => t('Operations'), 'colspan' => 2),
                  );
                if((variable_get('results'))!="") {

               $query = db_select('myform', 't')
              ->extend('TableSort')        //Sorting Extender
              ->orderByHeader($header)
              ->extend('PagerDefault')
              ->condition('lname',variable_get('results'),'=')
              ->limit(2)
              ->fields('t', array('id', 'fname', 'lname'));
              $results = $query->execute();
              foreach($results as $node)
              {
               $rows[]=array(
                    'id' => $node->id,
                    'first_name' =>$node->fname,
                    'last_name' => $node->lname,
                   'modify' => l('Modify', 'myform/modify/'.$node->id),
                    'delete' => l('Delete', 'myform/delete/' . $node->id));
               }
               }
               else
               {
               $rows = array();
               }
            $form['pager_table'] = array(
              '#theme' => 'table',
              '#header' => $header,
              '#rows' => $rows,
              '#empty' => t('Empty Rows')
              );
              // attach the pager theme
              $form['pager_pager'] = array('#theme' => 'pager');
                return $form;
                                     }

                             function form_example_form_submit($form,&$form_state)
               {
        variable_set('results',$form_state['values']['search']);
                   }

```

Now when I change the link how do I free the variable at form unload

# Answer
Lets try this method

on your form

```
function form_example_form($form, &$form_state) {
  $name = 'myname';
  $value = 'nikhil';
  variable_set($name, $value);
  // Your form elements goes here ...
}

function form_example_form_submit($form, &$form_state) {
  $name = 'myname';
  $myname = variable_get($name, $default = NULL);
  echo $myname; // will print nikhil
  variable_del($name);

}

```

As i dont know any Form Unload event i will do

```
drupal_add_js("jQuery(document).unload(function() {
//make an AJAX call to clear the value });", 'inline');

```

in javascript

Good luck.
> 1 votes

---
Tags: forms
---


title: confirm email form type?

text:
# Question
Title: confirm email form type?
There is a confirm password form type. I don't suppose there is a confirm email address form type available? Possibly as a contributed module?

# Answer
You can try LoginToboggan

You will get a screen like this in example.com/admin/config/system/logintoboggan
> 2 votes

# Answer
I don't think there is any module for this - it's not a part of Drupal core, but it would be relatively simple to create the repeat functionality yourself. Simply add the repeat form field and a validation check that the two values are the same.
> 1 votes

---
Tags: forms, emails
---


# Question
Title: Light box that is compatible with Views?
I've created a content type, let's call it Person. I've got a View which generates a grid of thumbnail images, one for each Person. When the user clicks on one of these thumbnails, I'd like to open that Person node in a lightbox (without all of the header and footer decorations, just the content of the node).

What lightbox modules are compatible with Views? I tried ColorBox, but I'm not seeing a colorbox option in the "Link Image to.." which is where I would expect to see it.

Is colorbox compatible with Views and I'm just looking in the wrong place?

If it's not, what modules are compatible with Views to do something like this?

# Answer
The Lightbox 2 module integrates with Views. I use it on my site. This module is extremely popular (more than 100,000 installs).

Unfortunately, this issue describes why Views and Colorbox are currently not compatible.
> 1 votes

# Answer
Maybe there is way to achieve what you want. Adding a lightbox to an image is as simple as adding 'lightbox' to the link's rel attribute. Since you want to display content in the lightbox then you should go and rewrite your image and select "Output this field as a link". Construct the correct path for the link and add the rel attribute. Take a look at this for more info and examples.
> 1 votes

# Answer
You need to output the image field as a link (there's a checkbox on the setting of this field on Views) and set the `rel` attribute to `lightmodal` according to this page. And you need to write a very small custom module as shown in this comment which outputs your node's content **without** all the other bits (html, body tags, sidebars etc).

Otherwise you can use `lightframe` in the `rel` attribute and just put the link of the node there, which should display the whole page in a lightbox with the sidebars, menus, headers & footers etc.
> 1 votes

---
Tags: views, 7, javascript
---


# Question
Title: How to get video length of a youtube video in drupal7
I created a node in drupal7 which contains a youtube link. I installed `youtube module` in my site. with the help of this module i just created a field for inputting url to youtube video. every thing worked fine. It is showing me the thumbnail,video etc. But the problem is how to get the `length of the youtube video` ?

I am using `views` to generate a json web service the output is

```
{
            "title":"social networking",
            "field_eventcat":"Performing Arts",
            "field_eventdaytime":"06\/06\/2012 - 05:00",
            "field_eventvideos":"http:\/\/sample sites\/sites\/default\/files\/styles\/thumbnail\/public\/youtube\/6a_KF7TYKVc.png",
            "nid":"34"
         }

```

I want to get the video lenght with this object. pls help

# Answer
> 5 votes
You can follow the function youtube\_get\_remote\_image on how to make a call to youtube api and retrieve video length.

Youtube public api provides this info without any authentication, for instance - http://gdata.youtube.com/feeds/api/videos/dc4UltkRJsw contains video length in the tag: yt:duration. I have not tested the below function, but should work.

```
function youtube_get_video_length($id = NULL) {
  $path = 'http://gdata.youtube.com/feeds/api/videos/' . $id;
  $query = array(
   'v' => '2',
   'alt' => 'jsonc'
 );
  $url = url($path, array('query' => $query));
  $result = drupal_http_request($url);
  $data = json_decode($result->data);
  $video_length = $data->data->duration;
  return $video_length;
 }

```

Also I dont suggest that you write this in youtube.inc of youtube module, write in your custom module or template.php of custom theme.

Hope that helps.

---
Tags: views, 7, services, files
---


title: add serial id to content type

text:
# Question
Title: add serial id to content type
How do I add a NUMBER field to my content type? A NUMBER field means a serial id similar to auto incremented primary key on a DB table. I wanna use a unique NUMBER in view related to my content.

# Answer
> 1 votes
The Serial module will be helpful for you.

> This module provides an auto-increment (serial) field.
>
> Unlike Drupal's built-in auto-increment node ID, which is global and shared by nodes belonging to all content types, serial fields are managed per content type (D6)/entity (D7). For example, the serial field of an Invoice instance will generate a unique sequential number (starting at 1, then 2, etc.) exclusively for Invoice instances.

---
Tags: 7, nodes
---


title: Add nodes in grid style

text:
# Question
Title: Add nodes in grid style
I need to add nodes in grid style i.e inline adding of the nodes should be done there only. i.e use can add any number of nodes at a time.

# Answer
> 1 votes
You can use the Views module plus Slickgrid to do that.

The module:

> defines a slickgrid view style, so all data can be output as an editable grid.

And can also be used for data entry/manipulation directly within the grid itself.

# Answer
> 0 votes
Editview module also proved useful for me.

---
Tags: 6
---


# Question
Title: Is bypassing Drupal's #token protection against CSRF safe for search forms specifically?
I see that `$form['#token']` is employed in drupal\_prepare\_form() and drupal\_validate\_form() as a protective measure against cross-site request forgery.

I am wondering about the necessity of this measure on site-search forms specifically, including core's search\_box() and search\_form() as well as a form built from scratch in a module that similarly implements a search by feeding arguments into a view.

I have seen it mentioned (in drupal\_prepare\_form(), in fact, and possibly other places I can't recall) that the search forms would be a viable case in which to work around the token protection. But then, why doesn't core do so by default?

(Note: I'm not asking for help with code to work around it, as I've figured that part out already.)

# Answer
> 3 votes
I think the biggest question when judging a potential CSRF problem is whether some form of damage will be done if a user is tricked into taking the action. If there is a CSRF vulnerability that deletes a user or unpublishes a node, that would be a problem. But being tricked into executing a search is only potentially a problem in terms of the resources a search takes to execute (which is not that much). Even if the core search doesn't bypass the token, it is accessible as a GET url (search/node/keyword) so someone could be tricked into visiting that URL bypassing the form in front.

Another way to think about it is whether the action is idempotent. A search is an idempotent action (by the W3 definition, log records might be created, but that's not a big deal), so it doesn't need CSRF protection.

# Answer
> 0 votes
This seems to bring about reasons why you should never bypass #token: CSRF: Avoid security holes in your Drupal forms.

And the specific instances you've provided don't seem to warrant bypassing #token.

---
Tags: 7, forms, security
---


# Question
Title: How to show and hide menu tabs in module
I have created tabs in module for different functions. As per code shown below, all the tabs are shown simultaneouly when I login to the module. But, I want to show specific modules depending on the play formats, how can I do that? I tried hook for menu\_alter and created custom module but all hides specific menu directly and not condition wise.

# Play URLs

```
$items['abc/play'] = array(
    'title' => t('Welcome Player'),
    'access arguments' => array('administer users'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('score_entry_table'),
    'access callback' => TRUE,
    'file' => 'scoreentry.inc',
);

$items['abc/play/cricket_score'] = array(
    'title'         => t('Cricket Scoreboard'),
    'page callback' => 'cricket_score_table',
    'page arguments' => array(1),
    'access arguments' => array('administer users'),
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
    'file' => 'cricketscore.inc',
    'weight' => 2
);
$items['abc/play/soccer_score'] = array(
    'title'         => t('Soccer Scoreboard'),
    'page callback' => 'soccer_score_table',
    'page arguments' => array(1),
    'access arguments' => array('administer users'),
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
    'file' => 'soccerscore.inc',
    'weight' => 1
);

```

Now it shows both tabs after login, I want to show only one tab as per format. I go to scoreentry page, where I get the format code and I want to hide the tab based on that format.

# Answer
Have a look at the Tab Tamer Module.
> 1 votes

# Answer
If you want to avoid showing both tabs simultaneously then you will need to manage path hierarchy. In a path hierarchy if sibling items are typo of MENU\_LOCAL\_TASK then they always appear in tabs simultaneously.

This is an example to break you path hierarchy in more deeper way.

```
$items['abc/play'] = array(
    'title' => t('Welcome Player'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('score_entry_table'),
    'file' => 'scoreentry.inc',
    'type' => MENU_NORMAL_ITEM,
);

$items['abc/play/cricket'] = array(
    'title' => t('Welcome Player'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('score_entry_table'),
    'file' => 'scoreentry.inc',
    'type' => MENU_NORMAL_ITEM,
);

$items['abc/play/soccer'] = array(
    'title' => t('Welcome Player'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('score_entry_table'),
    'file' => 'scoreentry.inc',
    'type' => MENU_NORMAL_ITEM,
);

$items['abc/play/cricket/score'] = array(
    'title'         => t('Cricket Scoreboard'),
    'page callback' => 'cricket_score_table',
    'page arguments' => array(1),
    'access arguments' => array('administer users'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'cricketscore.inc',
);

$items['abc/play/soccer/score'] = array(
    'title'         => t('Soccer Scoreboard'),
    'page callback' => 'soccer_score_table',
    'page arguments' => array(1),
    'access arguments' => array('administer users'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'soccerscore.inc',

);

```
> 0 votes

---
Tags: 7, routes
---