title: Add PHP code to a node

text:
# Question
Title: Add PHP code to a node
Is it possible to add PHP code to a node? I have enabled the Context and Context PHP modules.

May anyone please tell me how I can do?

# Answer
> 3 votes
Enable PHP Filter module comes with Drupal core

> The PHP filter core module adds the ability to include PHP code in posts. PHP is a general-purpose scripting language widely-used for web development; the content management system used by this website has been developed using PHP.

The following is a guide to add a new text format filter in Drupal 7:

1. Navigate to the Text formats page *Administer » Configuration » Content authoring » Text formats* (/admin/config/content/formats).
2. Click **Add Text Format** (admin/config/content/formats/add).
3. Enter the following information:
    * **Name**: The name of the filter as it will appear in the administration interface.
    * **Roles**: Select one or more roles that will be able to use the format.
    * **Enabled filters**: Enable one or more filters. ***Note**: As filters are selected, items are added to the Filter Processing Order and Filter Settings sections.*
    * In the **Filter processing order** section, drag the four-headed arrow to rearrange the order in which the filters will be applied.
    * In the **Filter settings** section, specify the settings for the selected filters. Some filters do not have settings.
4. Click **Save Changes**

**WARNING**: Some HTML markup should only be available to authenticated and trusted users. **The PHP option should not be enabled unless it is necessary and care should be taken to limit access to a role representing trusted and knowledgeable users.**

---
Tags: 7
---


title: Write Drupal Code online

text:
# Question
Title: Write Drupal Code online
Is there any website that allows to write and test Drupal Code online ? Like this one for PHP writecodeonline.

# Answer
> 4 votes
There's Simplytest.me, but that's really for testing existing module to see if you like them (e.g. never used Panels before, select Panels from the list and hit Launch Sandbox to give it a go).

You could set up a test site with Devel and hit *devel/php*. However this isn't really any different from running a local sandbox site and doing the same thing.

Apart from that, I've not seen anything like what you're looking for. Sorry :(

# Answer
> 0 votes
I am not familiar with any public accessible online version, but if you set up a local sandbox install of Drupal and enable the core PHP filter you basically have that.

---
Tags: testing
---


title: Product questions in Ubercart

text:
# Question
Title: Product questions in Ubercart
I need some guidance in how to go about this.

I have some products (ubercart using Drupal 7) for which the users need to answer some questions with yes and no, before buying the product.

How can I achieve this?

# Answer
> 3 votes
You can use the Ubercart Webform Checkout Pane module.

> This module allows you to define Webform nodes as checkout/order panes in Ubercart.
>
> This is useful if you want to collect additional information during the checkout process. For example, you may want a quick survey or require additional fields that apply to the entire order.

---
Tags: ubercart
---


# Question
Title: How to print Promoted to front page to new block?
I have article,news,video types for content. Now I checked `Promoted to front page` for print article/news/video, etc content to any block. Now, how to print `10` result `Promoted to front page` article/news/video to new block of index using views Module?

# Answer
If I understood you correctly, you want to show 10 posts promoted to the front page in a block.

The Views module comes with a "Front page" view. By default, it is disabled, and you need to enable it. Once you did it, you can edit it: Click on *edit*.

On the next page, click on the "Add" button you see on the top left, and select *Block*.

On the next page, select "Access: None" under *Block settings*. (The link is just the *None* word.) Change the access to *Permission* (first page), and *View published content* (second page). (To pass to the second page, click on *Apply*.)

Save the view. (The button is on the top.)

On admin/structure/block, select the block you just created, and assign it a region where it should appear. Its name is *View: Front page*, if you didn't change the default one, which is *None*.

This is the result.

I changed the access settings because I enabled the view which was not enabled, yet. If you are already using the *Front page* view is not necessary to change the access settings, if not in the case you want the access settings for the block to be different from the page settings. In this case, be sure to select "This block (override) as in the fourth screenshot.
> 1 votes

# Answer
These are the steps that you need to follow to achieve your task:

1. Add a new content view with fields (block display)
2. Add the filter criterion "Content: Promoted to front page = YES"
3. Add the filter criterion "Content: Type Is one of article/news/video"
4. Change "Display a specified number of items" to 10
5. Navigate to "admin/structure/block"
6. Find the view, and place it where you want it to be displayed
> 0 votes

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


title: Entity Field Query - Type of the Field

text:
# Question
Title: Entity Field Query - Type of the Field
How do I determine the individual field type using an `EntityFieldQuery`?

Here is the sample code for extracting the fields of a content type named 'digital\_iq\_test\_2012', which contains many fields. How do I determine the type of each field?

```
$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'digital_iq_test_2012')
  ->propertyCondition('status', 1);
$result = $query->execute();

```

Any help?

# Answer
`EntityFieldQuery` essentially just prepares an SQL query and gives you the results, it doesn't return any meta information about the fields themselves.

To get that you can use the Field Info API, e.g.

```
// Get all fields attached to your bundle.
$fields = field_info_instances('node', 'digital_iq_test_2012');

// Loop through
foreach ($fields as $field_name => $instance) {
  // Load up field info for this field.
  $field_info = field_info_field($field_name);

  // Get the type
  $type = $field_info['type'];
}

```
> 1 votes

---
Tags: database
---


title: Planning for migration to version 7

text:
# Question
Title: Planning for migration to version 7
I am just taking on responsibility for a Drupal 6.2 site. It has some custom modules and some quite poorly organised code which I am working with developers to improve alongside developing new features to the site. And being fairly new to Drupal I am just getting my head around how it all hangs together.

One of the things I want to assess is when we should be planning to migrate to Version 7.

1. Is it a reasonable assumption that, as a commercial website, we *should* upgrade to version 7 as support for 6 drops away over the next year or so?
2. Is it possible to develop and refactor on version 6 in such a way to make that migration as painless as possible when we get to it?
3. Is there anything else I should consider as I plan the development roadmap over the next 12 months?

# Answer
**Should you upgrade?**

All contrib modules will slowly shift major version. If you don't follow suit, you risk needing to re-invent the wheel more often than otherwise necessary. Most module maintainers have since long ago shifted focus to D7. A few have even begun maintaining their D8 version.

D6 will become unsupported, and have no more security updates after D8 is released.

**How do we make it painless?**

I don't think there's an answer that can be applied across all sites, but here are some general guidelines.

1. Features needs to be "released" (warning, lots of reading), and then upgraded by their providing module, and finally re-added to their respective features.
2. Use the Migrate module to easily test getting content over.
3. If possible, *run both versions at the same time*. Hide the fact as well as you can, possibly using a reverse proxy. This is non-trivial to accomplish, but ensures that when you move your last piece of functionality from D6 to D7, parts of your D7 site has been live for a long while already, and you know that it's stable. As one quick example of a relatively general measure one can take to ease this, Entity API can allow you to redefine where an entity reads/writes its data.
4. Often Contrib-space will solve a common problem that Core later decides to incorporate. Switching to these techniques for problem solving everywhere it's relevant will allow you to "partly" upgrade a current DX site to DX + 1, making the gap during the complete upgrade much smaller. Two examples of this are below, but this list could probably be much longer:
    1. Use Panels and Page manager instead of modules like Context and Spaces. The Pm+P approach to site building is the foundation of a huge re-write of core for D8.
    2. Use Guzzle instead of Http Client. Guzzle is the official http-client for Drupal 8.

**Anything else?**

Nothing that comes to mind at the moment.
> 0 votes

---
Tags: migrations
---


title: Problem with drupal_valid_path

text:
# Question
Title: Problem with drupal_valid_path
In my custom module I'm using `drupal_valid_path` to check if a given alias exists before I create such.

```
$target_alias = 'some/path';
if(drupal_valid_path($target_alias, FALSE) === FALSE){
  // create 'some/path'
}

```

The function **always** returns FALSE and thus creates tons of identical aliases. What could be wrong?

I have tried various boolean expressions, such as: `!drupal_valid_path` or weak type test `==`. To no avail.

# Answer
I would guess the problem is that `drupal_valid_path()` is expecting a system path, and you're passing it an alias.

Fortunately there's a function to determine the system path from the alias, `drupal_lookup_path()`. I would have thought a simple change to your code like this would make it work:

```
$target_path = drupal_lookup_path('some/path');
if(drupal_valid_path($target_path, FALSE) === FALSE){
  // create 'some/path'
}

```
> 3 votes

---
Tags: path-aliases
---


title: Dynamic view per taxonomy term

text:
# Question
Title: Dynamic view per taxonomy term
I'm really stuck on a problem that I'm seeking assistance on. I currently have 3 content-types (`Article`, `Photo` and `Video`) and all of them use the same Taxonomy Vocab I've called `Category`. I've configured the ***PathAuto*** module:

* for Category terms: `[term:name]` --\> CCK Field created and shared across content-types called: `field_category`
* for Articles: `[node:field_category]/articles/[node:title]`
* for Photos: `[node:field_category]/photos/[node:title]`
* for Videos: `[node:field_category]/videos/[node:title]`

The problem I'm experiencing is having to create a dynamic **View page** for each term. Basically, if from the root I navigate to a particular category (eg: `/politics`), I expect to see a page with all content under that term, plus allow me to then filter by content-type.

Similarly, if I navigate to articles under a particular category (eg: `/politics/photos`), I expect to see a page showing me all photos under that category.

I don't know if I've chosen a very elaborate (and unnecessary!) organisation of content, but this makes sense to me. I'm probably going to kick myself, for I feel that there is a simple solution to this! This is my first time using Views-3 UI, having only minor experience with Views-2 in D6. I'm currently using **Views 7x-3.5**.

I thank you much in advance for any assistance you can provide!

**EDIT**: I'm going through whatever online documentation I can find for Views-3, and so far it's quite overwhelming. I do know that I need to use contextual filters and view page paths with `%`.

# Answer
Okay, I have figured out a solution, although its a bit crude. Before I continue, I should mention that my aim was to also to create hackable URLs.

Installed the Taxonomy\_Display module. Created a Content View, and immediately added a contextual filter `Content: Has taxonomy term ID` with the following configuration:

**WHEN THE FILTER VALUE IS NOT IN THE URL:**

```
Provide default value
    --> Type = Taxonomy term ID from URL
    --> Load default filter from node page, that's good for related taxonomy blocks
    --> Vocabularies = Category

```

**WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED**

```
Specify validation criteria
    --> Validator = Taxonomy Term
    --> Vocabularies = Category
    --> Filter value type = Term Name converted to term ID (got this from the Taxonomy_Display module)
    --> Transform dashes in URL to spaces in term name filter values = Checked
    --> Action to take if filter value does not validate = Show "page not Found"

```

I then added a relationship: 'Content: Taxonomy terms on node`on my vocabulary, to give me access to the Taxonomy filters, and added a field filter on`Term = Category\` through the relationship created.

Finally, I cloned 3 pages based off the above config, with a page path to `categories\%\articles`, `categories\%\photos`, and `categories\%\videos`, and on each of these added a further filter by the respective content-type.

Well, it does what I want it to, but it somehow still doesn't strike me as an ideal solution ... I think it could be simpler, whilst also allowing for dynamically identifying the content-type from the URL. Therefore, I won't mark this yet as the answer, until someone can critique my approach. :)
> 1 votes

---
Tags: 7, views, path-aliases, navigation
---


title: Get submission values from a Webform

text:
# Question
Title: Get submission values from a Webform
I've got two fields in my form which are called *geographicarea* and *specialty*.

I'd like to use these values in an SQL query when the form is submitted.

How can I do it?

# Answer
> 2 votes
If I understand you correctly, you'd like to get a hold of the data before it gets inserted in the database so you can do something else with it?

If this is the case, hook\_webform\_submission\_presave is your friend. The $submission object will hold the submission data. This lets you change it before it's inserted in the database or, as in your case, just do something else with it.

Here's a list of all the webform hooks for D7 (with a link to D6 hooks as well if that's what you're using).

---
Tags: webforms
---


title: Drupal Adding Font Style to Date Fields

text:
# Question
Title: Drupal Adding Font Style to Date Fields
Sorry i thought i should ask this here as apposed to your CSS site as ive a feeling its something that Drupal is doing and not just a general css question.

When viewing the last comment time on the right of the main table of this page (and taxonony table pages) you will see that something is adding an tag to my date field. My site with the em added

The norm12 span class is what i have added and you can see that even making the font-style: normal with important added its still showing it with tags and style about it.

Its only a minor problem but its driving me mad.

Can anyone see where the problem may lie?

Thanks

# Answer
> 1 votes
Reg your trying override this on the span but the em tag has the style defined on it.

Should be...

```
.norm12 em {
//...
}

```

---
Tags: theming
---


# Question
Title: Drupal 7 views: Get NID in views using contextual filters
Does anybody know how to get the `nid` from a node using contextual filters or filter criteria in views

**WITHOUT** using "Get id from url"? I was thinking about using PHP or getting it from a node-field.

My view is a block of comments that is to be placed together with a node. The comments needs to belong to the node and linked by node ID. In this case the "Get ID from url" wont work since the node itself is listed in another view.

It is a view-block (containing comments) inside of a node that is listed in a view.

# Answer
> 3 votes
If you are loading and displaying your view in the `node.tpl` or `node--<content-type>.tpl` file, you could supply the current node `nid` as an argument to your block view, then you can setup a contextual filter for `Content: Nid`. I would do something like this:

```
 // get view
 $view = views_get_view('YOUR_VIEW_NAME');
 // set display for view
 $view->set_display('YOUR_VIEW_BLOCK_NAME');
 // set current node nid as argument to view
 $view->set_arguments(array($node->nid));
 // execute view
 $view->execute();
 // render view
 print $view->render();

```

You could also try to use `views_embed_view()` which I think would be the preferred way to do this. It takes two parameters, `name` and `display_id`, any additional parameters will be passed as arguments to the view:

```
print views_embed_view('YOUR_VIEW_NAME', 'YOUR_VIEW_BLOCK_NAME', $node->nid);

```

I'm not sure that this helps, the question is a little vague=)

---
Tags: views, nodes
---


# Question
Title: Properly handling menu items in a custom module
In my module I need to install custom menu items (add to existing `main-menu`) on the front-end side. So basically it's a simple one-time operation, yet it rises some questions about the proper way to deal with programatic menu items in general.

1. `hook_install` \+ `menu_link_save` sounds good for installing the items, `hook_uninstall` \+ `menu_link_delete` \- for uninstalling, but how am I supposed to find out the `$mlid` parameter of the menu link - required by the `menu_link_delete` function?
2. Would `hook_enable` and `hook_disable` be more suitable?
3. How do I protect my module's menu items from deleting on the admin UI side?

# Answer
You can programatically add/remove menu items on install/uninstall and/or enable/disable events. But that's *not* how we do usually.

Implement hook\_menu and you will be fine to go with almost any menu item implementation.

A few points. Set menu router item's `'type' => MENU_NORMAL_ITEM` and it will now be in a menu. Unless you set `'menu_name'`, it will be placed in the "navigation" menu. See the huge (and very helpful) text on the page. Also, have a look at examples module for high-quality hook\_menu examples.

Good luck!
> 1 votes

---
Tags: 7, routes
---


title: table view tr class row numbering

text:
# Question
Title: table view tr class row numbering
I would like to have row numbers in my tr classes when displaying my view as a table. My rows seem to have only classes saying they're even and uneven.

Only possible in a tpl file?

# Answer
Why dont you just override views-view-table.tpl.php by copying/pasting this to your template folder in your theme, then use $row\_count for your classes.

```
<tr <?php if ($row_classes[$row_count]) { print 'class="' . implode(' ', $row_classes[$row_count]) .' row-' . $row_count . '"';  } ?>>

```
> 2 votes

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


# Question
Title: How can I show a view in panel with argument in drupal 7
I am using panel to show the content and i am using view.I am creating a forum and want the link based upon argument when i am creating view and giving some context ,in preview it is working fine but when i am trying to rum wirh url no value is coming can any one tell what I am doing wrong.thanks in advance.

# Answer
> 3 votes
In order to use "contextual filters" for a view within a panel, you need to change the style of the panel. It seems that even though they are called contextual filters, they expect an argument. Make sure you have the view panes enabled in modules and create the same view with the style of view pane. You will then get an additional menu called "pane settings". One of the settings is "argument input", select "from context" and the required context, and it should work fine. This was something I was really stuck on till found this solution.

also, if you are trying to pass a taxonomy term, you have to make sure it is formatted correctly to use in the filter. See this post for details

Views contextual filters taxonomy name

# Answer
> 2 votes
If you don't want to recreate your view then an easy way around this is simply to set the Panel Page's argument to a generic string type, so that the unformatted taxonomy term name from the URL is passed directly to the View's contextual filter, and the hyphens in the URL are converted to spaces by Views (assuming you have that contextual filter option enabled) and not touched by Panels.

---
Tags: views, panels
---


title: D7 Search Form Template override

text:
# Question
Title: D7 Search Form Template override
Ok so this is my first D7 project. Im stuck with the Search Block. First there is no way of customizing the search form block template to make the the search form input field and button inline to be displayed in one row. Ok i can live with that. But i cant live with not at all being able to overwrite the search result template. Neither does the preprocess\_search\_results() work nor do i find a way to overwrite the template for the search results. All i find is suggestions for D6 which all do not work.

Can please somebody tell me how to override theses templates and i am not talking about the form\_ hooks like form\_alter. I do not want to design forms by endless PHP Arrays. I want to template.

Thanks

# Answer
Go to /modules/search/ to find the templates you want to override. Copy/paste them to the 'template' folder inside your 'theme' folder. Make sure you clear the caches so Drupal knows what you have done. Thats all there is to it.
> 2 votes

---
Tags: forms, search
---


title: Hook isn't printing

text:
# Question
Title: Hook isn't printing
I've this hook.

```
function modsubmit_webform_submission_insert($node, $submission) {
  $value = array_shift($submission->data);
  $value = array_shift($value['value']);
  print ($value);
  //$value is now the first value entered (in the case of multi-entry fields) or only value entered.
}

```

It does not print the message. Can anyone see what is wrong? Of course, the hook is called when the form is submitted.

# Answer
> 1 votes
**Where are you wanting $value to be printed at?**

Since this function runs in the background when a webform submission is inserted into the webform\_submissions table, you need to be explicit about what you want to have happen. Try drupal\_set\_message() instead, to print a message into the $messages region upon the next successful page callback, which is likely the "submission successful" page:

```
function modsubmit_webform_submission_insert($node, $submission) {
  $value = array_shift($submission->data);
  $value = array_shift($value['value']);
  drupal_set_message("The value inserted was: {$value}");
}

```

Make sure you've installed this module and make sure that you've cleared your cache (admin/config/development/performance) if you've added this function to an existing, already-installed module.

---
Tags: hooks
---


# Question
Title: Statistics per node only visible to node author
I want a simple block (or it could be attached to the content, I don't really care) displaying how many hits a node has had, visible on the node itself, and only visible to the user who created the node (and admins obviously).

Any easy way to do this?

# Answer
It should be somewhat easy to do using the statistics module. I wouldn't recommend this, is it requires a database write on each page view, with is quite a performance hit.

A better solution would be to do some integration with GA or similar and get the data from there, but that would obviously require much more work.
> 1 votes

# Answer
The Google Analytics Reports modules offers blocks that will report on individual pages. Wouldn't this off-load the stat works to Google?
> 2 votes

---
Tags: 6, nodes
---


# Question
Title: How can I manually add a subscription to an account using Commerce Subscription Product module?
I am using the Commerce Subscription Product module 1.x and I would like to add a few accounts manually that have a subscription. How do I achieve this?

# Answer
I've honestly only quickly glanced at it right now, but as far as I can tell, a valid subscription is simply the field `field_commerce_sp_time` having a value, in number of weeks the subscription is valid from today.

Thus, you should be able to simply edit the `user entity` as you usually would, and set any number of week you want. Note that the module ships with relevant permissions for editing the field, so you need to have the `field_commerce_sp_validity` permissions.

Similarly, you could directly insert the relevant value into the database with

```
db_insert('field_commerce_sp_time', 'fcst')
  ->fields(array(
    'entity_id' => $uid,
    'entity_type' => 'user',
    'value' => $number_of_weeks,
  ))
  ->execute();

```
> 2 votes

---
Tags: commerce
---


# Question
Title: Using commerce module for online payment for just 4 product/services?
I starting a website which is offering 4 Apartaments to rent. The visitor will be able to make online payments. My question: Should I use the Drupal Commerce module for this ?

Will I be able to treat each Apartment as a product? I need to include a map and a calendar for each one. Can I accomplish this with the commerce module.

There is no much documentation about this module and it seems complicated....

# Answer
> 2 votes
If all you'd do was display the rooms and manage their bookings, then I would say Commerce was not only excessive, but perhaps even entirely wrong.

However, since you mention online payments, I think it could be a good fit, for managing of those. No other contrib module is likely to have as many "out of the box" solutions for payment today, or developed tomorrow.

---
Tags: commerce
---


# Question
Title: Somebody is trying to brute force the password
Looking at the site log, I found, that somebody with IP address: 91.236.74.135 is methodically sending requests to the page: /user?destination=node/add of my Drupal website. He does it once in every hour. It's definitely a bot. I think, he's trying to brute force the password. For now I banned him in .htaccess with

```
deny from 91.236.74.135

```

Can anybody give an advice, how to protect the site from brute force attacks on logins?

# Answer
> 14 votes
I have two ideas to help with this problem.

There are tools and services you can use to look for brute force attacks. The security review module and droptor tools both look in your watchdog (at Administer \> Reports \> Recent log messages) to see if you have a lot of failed logins for one user. You can also do that manually.

In Drupal 7 the "access rules" feature was removed from core but moved to a contributed module - User Restrictions. Using that module you can block users from a specific IP address. Apache deny rules will be slightly faster if you have relatively small number of rules but the Drupal rules are easier to add/update/remove.

# Answer
> 2 votes
Check into fail2ban (http://www.fail2ban.org/wiki/index.php/Main\_Page) if you have access to the server. It will let you put limits on how often someone can bang on the front door before you get blocked (temporarily or permanently).

E.g. from the website:

> Fail2ban scans log files (e.g. /var/log/apache/error\_log) and bans IPs that show the malicious signs -- too many password failures, seeking for exploits, etc. Generally Fail2Ban then used to update firewall rules to reject the IP addresses for a specified amount of time, although any arbitrary other action (e.g. sending an email, or ejecting CD-ROM tray) could also be configured. Out of the box Fail2Ban comes with filters for various services (apache, curier, ssh, etc).

# Answer
> 2 votes
Also, check out the Login Security module.

> Login Security module improves the security options in the login operation of a Drupal site. By default, Drupal introduces only basic access control denying IP access to the full content of the site.
>
> With Login Security module, a site administrator may protect and restrict access by adding access control features to the login forms (default login form in /user and the block called "login form block"). Enabling this module, a site administrator may limit the number of invalid login attempts before blocking accounts, or denying access by IP address, temporarily or permanently.

# Answer
> 1 votes
I don't think there's a good way to do it within Drupal.

You should look at configuring your web server and/or firewall settings to enforce request limits.

---
Tags: security
---


# Question
Title: How to completely remove Drupal from system to start over!
I am an apprentice and am using Drupal for work it installed Drupal on to my machine and got it all up and running then I accidently logged out and now I can't log back in. I have tried to send a password reset but Drupal doesn't like the email address or username that I put in. I'm relatively new to this so I ask to keep it simple! :) What can I do?? Thanks in advance

# Answer
> 1 votes
This is easiest using Drush http://drupal.org/project/drush

```
drush user-password username --password="new_password"

```

# Answer
> 1 votes
An alternate method without using Drush. Open your preferred mysql client(PhpMyAdmin/Adminer/MySQL GUI) and run these queries. Substitute letters in BLOCKS with actual values.

```
use `MY_DATABASE_NAME`;
update `users` set pass = md5('MY_NEW_PASSWORD_WHICH_I_CANNOT_FORGET_AGAIN') where uid = 1

```

If you are not sure of the username that you used you can run this query to retrieve it.

```
select name from users where uid = 1;

```

# Answer
> 1 votes
As you installed Drupal on your computer, you can follow this method to change the password for the account with which you are trying to log in. Create a changepass.php file in the same directory containing the index.php file used from Drupal. The following is its content.

```
// Drupal 7.

define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

if ($account = user_load($uid)) {
  $edit['pass'] = $new_password;
  user_save($account, $edit);
}

```

```
// Drupal 6.
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

if ($account = user_load($uid)) {
  $edit['pass'] = $new_password;
  user_save($account, $edit);
}

```

Replace `$uid` with the user ID (1 in the case of the first user created when Drupal is installed), and `$new_password` with the new password.
Connect the browser to `http://localhost/changepass.php`, and the password will be updated with the one you choose. (Replace localhost with what is appropriate to connect to the web server on your computer, if localhost doesn't work.)

This method saves the password using the correct value, and the correct hashing which (on Drupal 7) can be changed by a module.

---
Tags: users
---


title: Using webform variables

text:
# Question
Title: Using webform variables
I've this hook that gets submitted values from my form which as 2 select options elements and prints the 2 values submitted.

```
function modsubmit_webform_submission_insert($node, $submission)
{
$cont=0;
foreach($submission->data as $val) {
      $value = array_shift($submission->data);
        $value = array_shift($value['value']);
        $data[$cont] = $value;
        $cont=$cont+1;}

drupal_set_message("The value inserted was: {$data[0]},{data[1]}");
}

```
Now i want to use this two values to make a sql query in db, and the result showed in a table. I can't get this to work, solutions needed

Thanks

# Answer
If you want to alter how a submission is rendered, for example adding a table, you need to implement hook\_webform\_submission\_render\_alter(). The hook receive the data for the submission in `$renderable['#submission']`, and the node in `$renderable['#node']`.

An example of `hook_webform_submission_render_alter()` is webform\_webform\_submission\_render\_alter(), which contains the following code.

```
function webform_webform_submission_render_alter(&$renderable) {
  // If displaying a submission to end-users who are viewing their own
  // submissions (and not through an e-mail), do not show hidden values.
  // This needs to be implemented at the level of the entire submission, since
  // individual components do not get contextual information about where they
  // are being displayed.
  $node = $renderable['#node'];
  $is_admin = webform_results_access($node);
  if (empty($renderable['#email']) && !$is_admin) {
    // Find and hide the display of all hidden components.
    foreach ($node->webform['components'] as $cid => $component) {
      if ($component['type'] == 'hidden') {
        $parents = webform_component_parent_keys($node, $component);
        $element = &$renderable;
        foreach ($parents as $pid) {
          $element = &$element[$pid];
        }
        $element['#access'] = FALSE;
      }
    }
  }
}

```

The purpose of hook\_webform\_submission\_insert() is inserting the submitted data in a database. You can use that hook to save the data in a database, and show those data in a page rendered from your module, but `hook_webform_submission_insert()` is not thought to render any data.
To make a paragon, `hook_webform_submission_insert()` is equivalent to `hook_node_insert()` that is invoked when a new node is saved, but that should not render any page.
> 1 votes

---
Tags: forms
---


# Question
Title: How to view nodes that only you have published?
I need to be able to incorporate into my system a method for which users can view nodes that only they have created. How can this be done?

# Answer
Basically, you need to implement `hook_node_access()` in a custom module. Something like

```
function MYMODULE_node_access ($node, $op, $account) {
  if ($op == 'view' && $node->uid != $account->uid) {
    return NODE_ACCESS_DENY;
  }
  else {
    return NODE_ACCESS_IGNORE;
  }
}

```

should be a start.
> 1 votes

# Answer
I've found the content\_access module to be pretty helpful for this kind of thing.

Just enable this on the content type you want to control, and make sure that "view any content" is unchecked for authenticated users, and that "view own content" is checked for authenticated users.
> 2 votes

---
Tags: 7, users
---


# Question
Title: How do I implement Ctools plugins from other modules?
I have a module which defines a plugin. Using this code, I can easily load the plugin:

```
ctools_include('plugins');
ctools_get_plugins('mymodule','myplugin');

```

That works great, but I would like my module to use plugins from other modules of type 'myplugin'.

I can only seem to get it to load plugins defined by the module provided in the first argument whereas I want to get all modules that provide plugin "myplugin", is there any way to do this?

# Answer
With the code you shown, you get all the plugins of that type implemented by any module, not just from one module. In fact, when I execute the following code, I get the plugins implemented also from the Views UI module.

```
ctools_include('plugins');
dpm(ctools_get_plugins('ctools', 'export_ui'));

```

The module name passed as first argument to `ctools_get_plugins()` is used to namespace the plugin type: There can be other modules that implement a "export\_ui" plugin type, and that is the reason why the function requires the name of the module defining the plugin type.

See also the description given for hook\_ctools\_plugin\_directory():

> This hook is used to inform the CTools plugin system about the location of a directory that should be searched for files containing plugins of a particular type. CTools invokes this same hook for all plugins, **using the two passed parameters to indicate the specific type of plugin for which it is searching**.
> 2 votes

---
Tags: 7, chaos-tool-suite
---


# Question
Title: Drupal adding some sort of hash on end of clean URL?
The site is working normally otherwise, but junk like this: #.ULQf0OOe90s is added onto the end of every URL.

Any ideas why this might be?

Thanks

# Answer
> 3 votes
This seems very similar to this topic in Wordpress:

http://wordpress.org/support/topic/random-hashtag-strings-added-to-url-in-firefox

Did you had the "Share this" module installed?

---
Tags: uri
---


title: Help Needed on Views UI in Drupal 7

text:
# Question
Title: Help Needed on Views UI in Drupal 7
I have two content types in my application:- Student Teacher

Teacher-Student has parent child relationship. Inside Student there is a node reference field to Teacher which means that when creating a student user needs to provide one or more Teacher's before saving content type. So one student is related to multiple Teacher here.

Suppose X is a student. Y and Z are teachers of X. Now when I opened the student(X) page then I want to see all the related students in a block who belongs to either (Y or Z) or Both.

Can it be possible using Views UI?Please let me know your suggestion on this.

# Answer
Your invaluable suggestion moved me for searching deeply in the relationship of Views UI and guess what? I solved the problem after the hours of study in Views UI. Here in this case there are two relations involved. The 2nd relation is involving the first one. This will not be possible to sort out if I didn't know how to turn on the SQL query in Views UI. This link also helped me.

Use of relationships (joins) in Views

Thanks You Nikhil!
> 0 votes

---
Tags: views
---


# Question
Title: XML feed data's are importing with the XML tags
I have created a XML feeds by the tutorial, but I have found one problem that the XML tags are also appending to data, ie title, description and salary tags are also there The output is following

```
<title>Drupal Developer 100</title>

<description>A job creating applications with Drupal.</description>

salary:
<salary ccy="usd">60,000</salary>

```

The output shows like below, I want to remove `<title>`

**EDIT 1**

I get the answer by this tutorial, just uncheck the check-box under **"Select the queries you would like to return raw XML or HTML"** in **XPath XML parser settings**

# Answer
You could use -

> tag/text()

This worked for me. It retrieves all the data that matches the tag.
> 1 votes

---
Tags: 7, importing-exporting, feeds
---


# Question
Title: For each row in a view, show a list of entities with entity reference field pointing to that row's content?
For instance, say I have an Author node and multiple Books with entity-reference to that Author. How can I make a view showing each author with a list of their books?

# Answer
To create a list of referencing content for each row in a view, use views\_field\_view to pull a secondary view into the row.

Add a secondary view with the fields to list and a contextual filter to receive the nid of the content being referenced from each primary view row.

Add a "Global: View" field to the primary view and use \[!nid\] for the contextual filter in View Settings to pass each row's nid to the secondary view.
> 0 votes

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


title: How do I override the login function

text:
# Question
Title: How do I override the login function
I have inherited an outdated Drupal 6 site with hacked modules. I did update core and all the modules that I could.

This php code is from a block for logging in. This redirects an authorized user to be directed to node-20.tpl.php.

```
<?php  global $user; ?>
<form action="<?php print "/{$base_path}user/login/?travelagents"?>" method="post" id="user-login">
  <div class="restrictedloginwrapper">
    <div class="restrictedlogin">
      <h4>CLIA number or Agent key:</h4>
      <input type="text" maxlength="60" name="name" id="edit-name" size="22" value="" tabindex="1" class="form-text required" />
      <input type="hidden" name="pass" size="20" value="password" />
      <input type="hidden" name="form_id" value="user_login" />
      <br>
      <input type="submit" align="middle" name="op" class="form-submit" id="edit-submit" tabindex="2" value="Log in" src="/<?php print path_to_theme() ?>/images/login.gif" alt="Submit" />
</form>

```

My client asked me to override the login for users without authentication (ultimately allowing anonymous users to login and see what authorized users see). The other requirement is that authorized users with their unique ID must still be able to use the login box and get redirected appropriately.

I have been able to create a way to automatically login using **00407606** (a special functional generic ID) in the *value=field* and if I change the *text field* to **hidden** a user can click the submit button and be logged in automatically and redirected appropriately. But applying this *removes* the ability for *registered* users to input their unique ID and login normally. This login is not the username-password of Drupal, it is a unique 8 digit number in a created table in the database.

Is there a php solution to do this? Is there some code in logintobbogan I could mimic/use? Am I looking for a javascript solution?

# Answer
Hey if you have any idea about drupal form alter then go with http://api.drupal.org/api/drupal/developer!hooks!core.php/function/hook\_form\_alter/6.

hope this will help you.
> 1 votes

---
Tags: users
---


title: How do I get my blog on Feed Burner?

text:
# Question
Title: How do I get my blog on Feed Burner?
I'm trying to get my blog onto Google Feed Burner. I've read all about this, but there doesn't seem to be a clear answer. I just get this error.

> Received HTTP error code 400 while fetching source feed.

I then validate my blog feed through feedvalidator.org. It says it's validated, but it shows the following message.

> This feed is valid, but interoperability with the widest range of feed readers could be improved by implementing the following recommendations.
> line 38, column 0: Missing atom:link with rel="self" \[help\]

The help link seems useless, and I don't think this "recommendation" from the feed validator is my issue. Nonetheless, I've installed http://drupal.org/project/views\_rss as well as http://drupal.org/project/feedburner.

I've tried burning my feed through the Feed Burner module, but nothing seems to be validated. It looks like there's a lot of Drupal folks having similar problems without a clear answer/tutorial.

Here's what I have:

1. Drupal6 site. A blog page with numerous blog posts, each with a teaser. URL example.com/blog
2. What appears like a valid RSS feed when I type in example.com/blog/feed. This spits out some text which looks like.

```
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xml:base="https://example.com"
xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:media="http://search.yahoo.com/mrss/">
<channel>
<title>Example blogs</title>
<link>https://example.com/blog</link>
<description></description>
<language>en</language>
<item>

```
3. I've set up a google Feed Burner account.
4. I installed the RSS Views and the Feed Burner modules.

I don't know what else to do. I keep getting that awful error.

Hopefully someone out there can help.

# Answer
This one is ugly on google's part. My site is https, and feedburner doesn't support SSL... I figured that out the hard way. I didn't want to muck around with my SSL settings given that it's a wildcard cert, so I figured out a painless workaround. 1. Subscribe to your blog feed through Google reader. 2. Create a bundle folder with your blog feed. 3. Grab the bundle URL (not https, which is the workaround) 4. Paste it into feedburner.

Done, google accepts that, and gives you a branded feedburner url.

I'm sure there's a better approach, but this was an easy workaround for those with https sites.
> 0 votes

---
Tags: feeds
---


# Question
Title: What are the best ways for creating galleries from images stored as entities?
I have a gallery attached to node that allowed tagging of single picture. I used Field Collection for that job.

Now I need to display those images in different structure:

User when creating a node may choose prefered display.

Also same types of displays may be used for display all images from all nodes.

Could someone give me any advice?

# Answer
Hey you can use the Galleria module in D7. Here is a quote about it (from the module's project page):

> ... allows users to create image galleries using the Galleria jQuery plugin, found on http://galleria.aino.se.
>
> There are several different approaches of using this module to create Galleria image galleries. The most typical and easiest way to do so is to use it as a field formatter for image or media fields. All images uploaded to such a configured field will then be displayed in a Galleria gallery.
>
> You can also use it in conjunction with the References module to build a gallery of image nodes, referenced by a 'Node reference' field; or you can use the Views module to gather a list of images to display in a Galleria.
> 1 votes

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


# Question
Title: How to remove 'Message log' tab from profile page?
I've got this tab on profile pages of all users and for whoever I've tested, pressing this tab just yields:

> No logged messages

So it seems a real glitch that comes with some module which I've no clue of. So just wondering how can I remove the tab?

# Answer
It's part of the Messages modules; it has nothing to do with Private messages.

It's not a glitch, it's what this module does: a simple example of a way to deliver messages (notifications) to users.
> 2 votes

# Answer
I am not sure which module causing this, but this Tab Tamer module is always helpful. You can hide any tabs with Tab Tamer.

> Tab Tamer is an administration utility that provides easy re-ordering, hiding, and deactivation of tabs and subtabs. You can also **rename** tab labels.
> 1 votes

---
Tags: privatemsg
---


# Question
Title: Apache SOLR + Facet API + Taxonomy terms
I want to create a product catalog and I have been told that apache SOLR could be the best way to go. I installed Drupal Commerce, Apache SOLR Integration (7.x-1.0-rc2) and Facet API (7.x-1.0). I added a custom field "category" to my product display content type which refers to a hierarchical taxonomy vocabulary.

* Clothing
    + Tops
    + Dresses
    + Skirts
* Accessories
    + Bags
    + Jewelery
* Shoes
    + Pumps
    + Sneakers

On my products page I would like to see a facet block where I can select my categories. I want to show my top level categories without their children at first, but when you select a category I also want to see its' children. You can achieve this functionality with the standard installation I believe.

BUT when I select one top level category (Clothing) my other top level categories disappear (Accessories, Shoes). I don't want to be able to select multiple top level categories at once, I just want them to be visible...
Is that possible in any way?

# Answer
Although I've not tried the recipe I believe that this article over at wunderkraut is an exact match for what you are after. There is a lot of custom coding involved.
> 1 votes

---
Tags: taxonomy-terms, search
---


# Question
Title: DrupalGap response is HTML instead of JSON
I want to build a restful service to communicate with my Android app.

* System: Drupal Commons with Drupal 6
* Module for restful service: DrupalGap
* Test tool: Poster plugin for Firefox

I do everything like in the tutorial from Tyler, but I got my login screen as HTML, instead of correct login; I can't get the system connect states as anonymous user. If I am already logged in so the login functionality says "you alread logged in" and the system connect state shows correct data.
The Views module has a setting to enable "Views API Mode" to wrap JSON in HTML, but this setting is disabled and so this can't be problem.

Does anybody know a solution for my problem?

If I follow the installation instructions for DrupalGap on a fresh Drupal 6 site, everything works out of the box. I can also access the DrupalGap demo site.

# Answer
> 1 votes
We found the solution for our problem. Under admin -\> settings -\> commons uncheck the box "Force users to login". Now it is possible to get json responses from connect and login actions.

---
Tags: views, 7, mobile-tools
---


# Question
Title: Can't acces field collection with $content
I try to render a field collection in my node--1.tpl.php template with `print render($content['field_image_teaser'])` with no succes. I followed the example at http://drupal.org/node/1155752

The strange thing is, when I do a print of `$content` width `var_dump ()` my field is listed:

```
var_dump ($content);
//...
["field_image_teaser"]=>
      array(1) {
        ["und"]=>
        array(2) {
          [0]=>
          array(1) {
            ["value"]=>
            string(1) "1"
          }
          [1]=>
          array(1) {
            ["value"]=>
            string(1) "2"
          }
        }
      }
//...

```

but when I do a print of `$content ['field_image_teaser']` the var\_dump print out a `NULL`.

**Edite:** I'm using the current recommended version 7.x-1.0-beta4.

With the answer of Neograph734 I spot that the the dump of the field "field\_image\_teaser" cames not direct form "field\_image\_teaser". It cames from the $node Object (which is referred in every field), but I can't render that value. There is no output with: `print render($node->field_image_teaser);`

So is there a way to get the field collection in a renderable form to use the regular template system, or is something else wrong?

# Answer
> 2 votes
`field_view_field()` would probably do the trick:

```
$rendered = drupal_render(field_view_field('node', $node, 'field_image_teaser'));

```

There are other options you can pass to the function (display mode for example), so it might be worth checking out the docs to see exactly how you want to use it.

# Answer
> 0 votes
var dump can dump arrays and objects. You are assuming it is an array by using array syntax `$content ['field_image_teaser']`.

However you probably get presented an object. Give `$content->field_image_teaser` a try.

---
Tags: 7, entities
---


title: Question about the templates

text:
# Question
Title: Question about the templates
I create a module and implement hook\_menu():

```
function mymodule_menu(){
  $items['mymodule/list']=array(/*...*/);
  return $items;
}

```

then I create a theme and create page.tpl.php and page--mymodule-list.tpl.php at the same directory.

now I can access http://localhost/?q=mymodule/list, but it use page.tpl.php to render the page, instead of page--mymodule-list.tpl.php.

How should I do to make it render the page with page--mymodule-list.tpl.php?

# Answer
The 'rules' for the page.tpl.php template suggestions state you need to substitue each `/` in the page for **2** dashes, so your template file needs to be called:

> page--mymodule--list.tpl.php

Remember to the clear the cache again once you've made the change
> 1 votes

---
Tags: 7, theming
---


# Question
Title: Variables available on display suite php field
I'm using Display Suite module to create custom fields.

I've to add a code field (php), that calls a function that has `$nid` as argument. I've added this field to node entity but I can't understand if there are variables available on this field.

Adding a php field I've a textare where I can add php code.ù I've a custom functions that retuns html and require a nid as argument.

so in my custom field I should have something like:

```
<?php
print my_function($nid);
?>

```

The problem is that I don't know where find the $nid: $object? $node? $entity? $context?

This field is added on an node entity.

# Answer
You can get access to the node via the $entity variable within the "Field code" text area.

This will only work for the Display Suite "Code Field". If you are using Display Suite 7.x-2.x, you'll have to enable the "Display Suite Format" module.

If anything is setup properly, you should see this help text below the "Field code" text area:

> You may post Display Suite code. You should include tags when using PHP. The $entity object is available.
> 8 votes

---
Tags: 7, display-suite
---


# Question
Title: Separate home page per domain in multilingual setup (i18n)
I have a multisite Drupal with **2 domains**, that should have **separate home pages**, but I can't get it working. I've created a node for each.

Now, I've tried to configure it in the Configuration \> Site information \> **Default Home Page** panel. There is note on top of the page: "This form is domain-sensitive, be sure you select the proper domain before saving." ; Therefore I guess that "home page" parameter is per domain?

But it doesn't work : each time I change this field (value : node/92), **all domains are affected**.

Is it supposed to work? Is there another way to do it?

# Answer
After some search, it is a known conflict between Domain Access and **I18N** : http://drupal.org/node/1650498

As written, the fix is to :

* upgrade i18n to version 1.6 (or latest)
* upgrade Variable to 2.0 (or latest)
* upgrade Domain Access to latest
* **enable and set Domain Variable module.**

Then,

* Go to Domains List \> Variables Tab \> Site Informations \> Check "Default Home Page"
* Go to your domain \> You have 2 parameters tabs \> Go to the * *2nd* * Parameters Tab \> Site informations \> set your Default Home Page for this domain.

That should work perfectly !

---

NOTE : There are 2 others ways of setting different frontpages that DOES NOT WORK (at least for me) :

* Configuration \> Site information \> Default Home Page
* Domain \> 1st Parameters Tab \> Site Home Page

Don't use them.
> 3 votes

# Answer
I would

1. Setup a "Page manager"-page, and call it "Front".
2. Set the homepage to "/front".
3. Create one variant for every domain in the front-page. Fill with relevant content.
4. Create a ctools "Domain access plugin". That wouldn't be many rows of code, see my brief tutorial
5. Use the access plugin to setup a selection rule for every variant/domain.
> 5 votes

---
Tags: 7, i18n-l10n, domain-access
---


# Question
Title: Delete the content of a field from all the node under a specific content type
What would be the best approach (preferably with GUI) to delete the content of certain fields from certain content types.

I am thinking of using rules but I cant configure to do it.

Ny ideas? Thanks

# Answer
Views Bulk Operations, using the "Modify entity values" action.
> 1 votes

# Answer
You can easily do this with a little piece of code - just use field\_attach\_update () function.

Here is very good article "Saving node's fields without saving the node itself" that will help you.

Your code can be as follow:

```
$nids = db_query(
  'SELECT nid FROM {node} WHERE type in (:node_types)',
  array(
    ':node_types' => array('TYPE1', 'TYPE2'),
  )
)->fetchCol();
$nodes = node_load_multiple($nids);

foreach ($nodes as $node) {
  $node->field_fieldname[LANGUAGE_NONE][0]['value'] = 'some value';
  field_attach_presave('node', $node);
  field_attach_update('node', $node);
}

```
> 0 votes

---
Tags: entities, nodes, rules
---


# Question
Title: I save form data using hook_form_alter() but the data don't appear when editing the node from the UI
I implemented `hook_form_alter()` to insert few fields. I implemented `hook_node_insert()` to save the field data, `hook_node_load()`, and `hook_node_view()`.

Everything works fine, but when I edit the node, the edit form appears with no data.

How can I fix this?

```
function mymodule_form_ABC_node_form_alter(&$form, &$form_state, $form_id) {
  $options_first = _mymodule_get_first_dropdown_options();
  $selected = isset($form_state['values']['filed_1']) ? $form_state['values']['field_1'] : key($options_first);

  $form['field_1'] = array(
    // …
  );
  $form['field_2'] = array(
    // …
  );

  return $form;
}

/**
 * Implements hook_node_insert().
 */
function mymodule_node_insert($node) {
    db_insert('my_custom_table')
      ->fields(array('nid' => $node->nid, 'field_1' => $node->field_1, 'field_2' => $node->field_2,))
      ->execute();
}

/**
 * Implements hook_node_load().
 */
function mymodule_node_load($nodes, $types) {
  foreach ($nodes as $node) {
    $nids[] = $node->nid;
  }

  $result = db_select('custom_table', 'e')
    ->fields('e', array('nid', 'filed_1', 'field_2'))
    ->where('e.nid IN (:nids)', array(':nids' => $nids))
    ->execute();

  foreach ($result as $record) {
    $nodes[$record->nid]->field_1 = $record->field_1;
    $nodes[$record->nid]->field_2 = $record->field_2;
  }
}

/**
 * Implements hook_node_update().
 */
function mymodule_node_update($node) {
  if ($node->type == 'abc') {
    // Delete the existing values.
    db_delete('custom_table')
      ->condition('nid', $node->nid)
      ->execute();

    db_insert('custom_table')
      ->fields(array('nid' => $node->nid, 'field_1' => $node->field_1, 'field_2' => $node->field_2,))
      ->execute();
  }
}

```

# Answer
What your code does is similar to what the Book module does with book\_form\_node\_form\_alter(), book\_node\_load(), and book\_node\_insert().

What is wrong in your code is that:

* In `mymodule_form_ABC_node_form_alter()`, you don't initialize the form fields from the values you loaded with `mymodule_node_load()`, which means the form fields you are using are always set to an empty string. The Book module uses `$form_state['values']['book']` to initialize `$node->book`, but the comment on \_book\_add\_form\_elements() explains why that is done.

```
// If the form is being processed during the Ajax callback of our book bid
// dropdown, then $form_state will hold the value that was selected.
if (isset($form_state['values']['book'])) {
  $node->book = $form_state['values']['book'];
}

```
* You implement hook\_node\_insert(), but not hook\_node\_update(). This means the value of the node properties you are using are saved when a node is created, not when a node is updated.

It is true that the Book module implements hook\_node\_prepare() (book\_node\_prepare()), but its purpose is only setting the default value for the node properties it handles, which is useful in the case a node is not created through the user interface.

Since you are interested in saving those node properties when the content type is *abc*, I would implement the code as follows.

```
function mymodule_form_abc_node_form_alter(&$form, &$form_state, $form_id) {
  $node = $form['#node'];
  $options_first = _mymodule_get_first_dropdown_options();
  $selected = !empty($node->field_1) ? $node->field_1 : key($options_first);

  $form['field_1'] = array(
    // …
  );
  $form['field_2'] = array(
    // …
  );

  return $form;
}

function mymodule_node_prepare($node) {
  if ($node->type == 'abc') {
    $node->field_1 = '';
    $node->field_2 = '';
  }
}

function mymodule_node_load($nodes, $types) {
  $nids = array();

  foreach ($nodes as $nid => $node) {
    if ($node->type == 'abc') {
      $nids[] = $nid;
    }
  }

  if (!empty($nids)) {
    db_query('SELECT e.nid, e.field_1, e.field_2 FROM {custom_table} e WHERE e.nid IN :nids'), array(':nids' => $nids), array('fetch' => PDO::FETCH_ASSOC));

    foreach ($result as $record) {
      $nodes[$record['nid']]->field_1 = $record['field_1'];
      $nodes[$record['nid']]->field_2 = $record['field_2'];
    }
  }
}

/**
 * Implements hook_node_insert().
 */
function mymodule_node_insert($node) {
  // hook_node_insert() is called for any node.
  // Check the content type of the node is the one for which the form fields have been added.
  if ($node->type == 'abc') {
    $values['field_1'] = !empty($node->field_1) ? $node->field_1 : '';
    $values['field_2'] = !empty($node->field_2) ? $node->field_2 : '';

    db_insert('my_custom_table')
      ->fields(array('nid' => $node->nid, 'field_1' => $values['field_1'], 'field_2' => $values['field_2']))
      ->execute();
  }
}

/**
 * Implements hook_node_update().
 */
function mymodule_node_update($node) {
  if ($node->type == 'abc') {
    db_update('custom_table')
      ->condition('nid' => $node->nid)
      ->fields(array('field_1' => $node->field_1, 'field_2' => $node->field_2))
      ->execute();
  }
}

```

Dynamic queries should be used when strictly necessary, for example because another module alters them. If you need to use a dynamic query, I would rather rewrite it as the following one.

```
$result = db_select('custom_table', 'e')
  ->fields('e', array('nid', 'filed_1', 'field_2'))
  ->condition('nid', $nids, 'IN')
  ->execute();

```

To update the values in a database, you should use db\_update(), not deleting the values already present in the database, and inserting the new values. `db_update()` looks for the database rows matching the condition expressed in `$query->condition()`, and updates the fields given in `$query->fields()` with the new values.

As side note, if you are editing a module that is already installed, and enabled, you need to disable, and re-enable it, or Drupal will not notice the code has been changed, and it implements new hooks. Drupal keeps the list of implemented hooks from the enabled modules in cache; disabling a module, and re-enabling it, forces Drupal to update that cache.
> 1 votes

# Answer
You need implement hook\_node\_prepare. This hook is used to load additional data before a node object is shown on the add/edit form.
> 1 votes

---
Tags: 7, nodes, forms
---


# Question
Title: Requirements issues while setting up a D7 website
I'm trying to set up an old D7 website, but I stumble upon some issues.

As you can see in the image below, I work with PHP 5.4.8 and Apache 4.2.3.

I don't use things like XAMPP. I've configured Apache, MySQL and PHP myself on my Windows 7 machine.

In my `php.ini`-file I've enabled all the necessary extensions I believe...:

```
extension=php_bz2.dll
extension=php_curl.dll
extension=php_gd2.dll
extension=php_gettext.dll
extension=php_imap.dll
extension=php_mbstring.dll
extension=php_mysql.dll
extension=php_mysqli.dll
extension=php_openssl.dll
extension=php_pdo_sqlite.dll
extension=php_pgsql.dll

```

But still, I get the errors above. What should I do next?

# Answer
> 1 votes
Looks like you're missing some PHP components.

Try the following on the command line:

```
sudo apt-get install php-gd php5-common php5-mysql
sudo service apache reload

```

**EDIT**

I've just realised I've COMPLETELY assumed you're running \*buntu - if you're not then please let me know!

---
Tags: 7, installation
---


# Question
Title: limitation on "add more" button: Drupal 7
I am using add more for a field which provide only maximum limit But I want to add by default two fields with "add more" button up to a maximum number of 10 fields.

How can I achieve this ?

# Answer
Sounds like you're after the Multivalue Settings module.

> So you can create fields where, for instance, users have to input at least 5 values but can input up to 10 values. Or you can create fields that allow 100 values, but only display 20 fields to start with.

**HOWEVER** (and this is a big however - if I could change the font size I would)

This module should probably only be used as a starting point, and should not be used in production. I'm sure you can get the code you need from it.

> Warning: this module is still very buggy. Actually, it only works in very few use cases. I suggest to only attempt using it with core fields (not fields from contrib modules). Even this may not work. I'm working on fixing things, but don't have much time. Help is welcome.
> 2 votes

---
Tags: forms
---


# Question
Title: DB log message: login failed for user xxx
Does anyone ever get "Login failed by user xxx" messages in their recent log entries? I have been getting the same message over and over for the past several days, always from the same IP address and user trying to access node/add. It's kind of freaking me out. Anything to be done about it?

# Answer
> 2 votes
That means some spam robots trying to access your add form. But since only logged in user can post content, this wont be a big problem. But make sure every permission is okay and also use captcha module to secure forms.

Also use strong passwords for all users

# Answer
> 3 votes
These are often spammers, but might also be malicious users who are trying to break into your site (for example, to use it to post malware, distribute files, or as an email relay). If your set of users is small and well known then you should only be worried about these messages if they are for actual accounts on your site - that would be an indication of a brute force attack.

If your site is Drupal 7 then you already have some built in protection against brute force.

Some modules that might be useful to improve the overall login security of your site.

# Answer
> 0 votes
You can also use Restrict IP module to restrict the IP from which the `node/add` was visited.

Here's an excerpt from module's project page:

> ... allows administrators to restrict access to the site to an administrator defined set of IP addresses. Anyone trying to access the site from an IP address not in the list of allowed IP addresses will be redirected to an access denied page with the message "Your address is not in the list of allowed IP addresses". No blocks will be rendered, and no javascript will be added to the page. This will happen for any and all pages these users try to access.

---
Tags: security
---


# Question
Title: trigger attribute AJAX using custom select element
I'm currently theming the product page for a Drupal Commerce site. Our frontend developer has insisted we use his custom "fancy" select dropdown for the attributes, which is causing a bit of a theming headache!

I have implemented his jQuery successfully, and when a user changes the fancy select option, it changes the "selected" option of the hidden select element too.

The problem is that none of the Drupal AJAX calls to update the price are fired when we change the selected attribute option via jQuery.

Does anyone know how I can force the onChange AJAX call for attribute options via jQuery?

Thanks in advance!

# Answer
> 2 votes
I had the same problem and I managed to find the solution.

You need to call .attr and .trigger

```
    $('ul.choose-product-quantity li').click(function(){
      var quantity = $(this).children('.product-quantity').text();
      $('.form-item-attributes-field-product-qty input')
      .filter(function(index){
        return $(this).attr("value") == quantity;
      })
      .attr('checked', 'checked').trigger('change');
    });

```

See attached screenshot as well. Good luck. !

Custom attributes selector (image)

---
Tags: ajax, commerce, javascript
---


title: SelectQuery, db_query() and pager

text:
# Question
Title: SelectQuery, db_query() and pager
I have a long query with sub-queries using `db_query()`.
So far I know SelectQuery of D7 comes with Extenders. Example extenders are `PagerDefault` (replaces Drupal 6 `pager_query()`).

I need my query with pager. Can I use `PagerDefault` with `db_query()`?
If I have to use `db_select()` for pager, how can I implement my query with sub-queries using `db_select()`?

```
$result = db_query("SELECT leg.*,
    ( SELECT COUNT(*)
    FROM {field_data_field_leg}
    WHERE field_leg_nid = leg.nid AND bundle = :bundle ) AS reviews
FROM
    ( SELECT
        n.nid, n.created, title, field_from_value origin, field_to_value destination,
        field_price_value price, term.name transport
    FROM {node} n
        JOIN {field_data_field_leg} l ON n.nid = l.field_leg_nid
        JOIN {field_data_field_from} ff ON n.nid = ff.entity_id
        JOIN {field_data_field_to} ft ON n.nid = ft.entity_id
        JOIN {field_data_field_transport} t ON l.entity_id = t.field_transport_nid
        JOIN {field_data_field_price} p ON t.entity_id = p.entity_id
        JOIN {field_data_field_transport_type} ttype
            ON t.field_transport_nid = ttype.entity_id
        JOIN {taxonomy_term_data term} ON ttype.field_transport_type_tid = term.tid
    WHERE n.type = :type
    ORDER BY n.created DESC, field_price_value ASC
) AS leg
GROUP BY nid
ORDER BY created DESC",
array(':bundle'=>'review', ':type' => 'leg'));

```

# Answer
> 1 votes
The short answer is that subqueries is not possible with `db_select()`, and pagers are only created through the query builder, either `SelectQuery` or `EntityFieldQuery`.

So you can't the above query and utilize Drupal's pager system, you would have to manage the pager yourself if you want the above query, or rewrite the query into several queries.

# Answer
> 1 votes
This should be possible.

Have a look at SelectQuery::countQuery() which is building a similar query.

Basically, instead of a table string, you can pass a full SelectQuery object to db\_select().

So, you will first need to build up your inner query and then create another instance and pass the first query to it.

You might want to provide a custom count query because you can probably build one that will be much faster than having two nested subqeries.

# Answer
> 0 votes
Following up on googletorp's answer, it can't hurt to have a minimal example. (In my case I don't need to do any fancy grouping of items, so I just provide links for the next/previous page; it would be nice to see this extended to provide the "standard" grouping at the bottom of the page however!)

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

  $items['somepath'] = array(
      'title' => 'Some stuff',
      'type' => MENU_CALLBACK,
      'page callback' => 'mymodule_show',
      'page arguments' => array(1)
  );

  return $items;
}

function mymodule_get_data($page = 0){
  // change this number to suit
  $num_per_page=20;
  $offset=$num_per_page*$page;
  $results = db_query("BLA BLA ORDER BY created DESC LIMIT $offset, $num_per_page");
  $return = array();
  foreach ($results as $result) {
    $return[] = $result;
  }
  return $return;
}

function mymodule_show(){
  $page = arg(1);
  $data = mymodule_get_data($page);

  // set up your table here as usual

  $retval=theme('table', array(
                'header' => $header,
                'rows' => $rows
                 ));
  $prevpage = $page-1;
  $nextpage = $page+1;
  if($page> 0){
    $retval = $retval . l("« Newer","somepath/".$prevpage). "  ";
  }
  $retval = $retval . l("Older »","somepath/".$nextpage);
  return $retval;
}

```

---
Tags: 7, database
---


# Question
Title: Trouble adding JavaScript inside a custom module
I’ve got a question about module development that I need some help with.

I’m building a module which needs to have multiple JS files connected to it. The first file, which has the same name as the module works just fine. But the rest of the JS files, attached the same way are being ignored. For example:

```
function mymodule_init() {
  drupal_add_js(drupal_get_path('module', 'mymodule') .'/js/mymodule.js');
  drupal_add_js(drupal_get_path('module', 'mymodule2') .'/js/mymodule2.js');
}

```

I’m not sure what I’m doing wrong, if anyone has a suggestion or can point me to some documentation it would be appreciated.

Thanks Stephanie

# Answer
It looks like it's due to the second implementation of `drupal_get_path()`.

You're passing through `mymodule2` as the argument, where it should just be `mymodule`.

e.g.

```
function mymodule_init() {
  drupal_add_js(drupal_get_path('module', 'mymodule') .'/js/mymodule.js');
  drupal_add_js(drupal_get_path('module', 'mymodule') .'/js/mymodule2.js');
}

```

On another note, if the JavaScript needs to be added on every page (as I'm guessing it does with the implementation of `hook_init`) then you might be better off adding your scripts in using `scripts[]` in the module's `.info` file

> ***scripts (Optional)***
>
> You can now add Javascript in the module's .info file if it should be added on every page. This allows Javascript to be aggregated in an optimal way, and is the preferred method of adding Javascript that most visitors will need on a typical site visit

Source: Writing module .info files

**References:**

`drupal_get_path();` API Docs

Managing JavaScript in Drupal 7

Writing module .info files
> 1 votes

---
Tags: 7, javascript
---


# Question
Title: Is there a easier way to disable and enable module for module development?
I'm finding that every small change I make to the hooks I have to disable and re-enable a module. Is there a easy way to do this than having to go through to the module menu, uncheck the module, click save configuration and wait for a while, then recheck the module, and click save configuration again?

# Answer
The devel module includes a page that will let you disable and re-enable modules in a single step. The page can be hard to find though, but if you enable one of the Devel blocks, it's listed in there.

You can also do it relatively easily from the command line using Drush.
> 6 votes

# Answer
For quick disabling and re-enabling of modules, try `drush dre module1, module2`.

This is a Devel command, so you need to have that installed, and enabled. You just need to be sure you put them in the right order according to their relative dependencies; should module1 be dependent on module2, it wouldn't work.
> 16 votes

# Answer
Using Drush from the command line saves a lot of time, not only with enabling and disabling modules, but installing, updating, and many other tasks. It's a very powerful tool useful for many Drupal development tasks.

For example, to enable the module using drush you'd type (in terminal) `drush en modulename`. To disable same module you'd enter `drush dis modulename`. Much quicker than going through the admin UI.

However, your problem may be resolved by clearing the cache as the only hooks directly effected are `hook_schema`, `hook_enable`, `hook_disable`, `hook_uninstall`, and `hook_install` (you can also clear the cache in Drush using the command `drush cc all`).
> 11 votes

# Answer
If you have lots of modules to enable and disable, just create a module that will enable/disable a selection of modules all in one go. Then use drush dis on that module do disable all the modules.
> 2 votes

---
Tags: 7
---


# Question
Title: Why do Drupal Form Builder properties have hash marks (#) in the key?
> **Possible Duplicate:**
> What are “#” properties?

This one's more out of curiosity than anything.

If you look at the Form API Reference, you can see that all properties have number signs/hash marks (#) at the start of the key.

My question is, why is it like this? Why bother having these hash marks in front of property names, other than "That's the convention somebody somewhere decided", and to occasionally cause people grief when they forget to add one?

Quite curious. Thanks!

# Answer
It's a convention to add a hash tag to properties that correspond to a setting rather than an element. This is done to avoid namespace collisions.
> 1 votes

# Answer
If you don't add a hashmark you're not setting that property, but are instead defining another level of a render array element. Consider this example:

```
$form['your_name'] = array(
  '#type' => 'textfield',
  '#title' => 'Your Name',
  'title' => array( // I am an entirely new element, whose key is "title".
    '#type' => 'textfield',
    '#title' => 'Your Title',
    '#description' => 'Example: Sir, Mr, Bossman, Chieftan',
  ),
);

```

This example is silly, but it should describe why a hashmark is used to set a property. If your question is really "why use a hashmark instead of an exclamation point, an ampersand, or some other random character?", well, I don't know. I've seen the hash symbol used to define properties in other languages and APIs.
> 2 votes

---
Tags: forms
---


# Question
Title: What are the implications of duplicate content issues with Drupal comments?
Say we have a node called node/123 with comments enabled. When comments are made, additional URLs are generated /comment/1, /comment/2 ... and /comment/reply/2/1 etc. Unfortunately, these new URLs are a page that contains a full copy of the content in the original page /node/123 or the comment in reply. Core's robots.txt only has `Disallow: /comment/reply/`

Would there be any implications to adding the following to the robots.txt file? Would this be recommended (or even post a core issue pointing this problem out?)

```
# Paths (clean URLs)
Disallow: /comment/
Disallow: /comment*/
Disallow: /comment/reply/
Disallow: /comment/reply*/
...
# Paths (no clean URLs)
Disallow: /?q=comment/
Disallow: /?q=comment*/
Disallow: /?q=comment/reply/
Disallow: /?q=comment/reply*/

```

# Answer
> 5 votes
I'm the author of that sandbox module(Permalink to Nodepath) mentioned in the first comment for the question. Mario's answer is well described regarding canonical URLs - but unfortunately it's not the *only implication*.

These comment/\* URLs are from Drupal 7. In Drupal 6, comments did not have their own URLs. Canonical URLs can solve the problem with duplicate contents which is perfectly fine for most sites IMO. But spam comments can add 404 and 403 errors to your site errors list as they wish. This was my personal experience that my spam hunting service couldn't delete some of the comments so I had to manually delete them. But Google had them already indexed.

The actual problem is that anonymous users can post any type of comments and if they were deleted or unpublished, Google (and other search engines) logs them as crawl errors which is quite annoying and probably it will affect your page rank as well.

In other hand, most link sharing sites, including facebook do not respect the canonical URL. For an example, `http://example.com/node/1` can have 56 (facebook) likes but they are not synced if the user liked `http://example.com/comment/5` (assume comment 5 is a comment made to node 1). From facebook view, they are 2 different URLs (actually they are) so like counts are different.

Also, modules like Boost rely on the actual request URI setting from $\_SERVER which is still `comment/5` (even though canonical URL is `node/5`). You can however change configuration of Boost module to overcome this.

It's quite popular to use `arg(1)` to get the node ID in custom blocks, modules, Views, etc. They will **work**, because in the callback function of comment/% URLs, that function sets `$_GET['q']` to the canonical URL. This $\_GET change solves most of the problems in progrmable stuff.

# Answer
> 5 votes
After investigating, I don't think there's an SEO problem here. It's an annoyance for sure but it's not a problem and here's why:

As per Google's recommendations here http://googlewebmastercentral.blogspot.com/2009/02/specify-your-canonical.html on canonical URLs and duplicate content, you will not have any problems if you have duplicate content only if you properly specify your canonical URLs. Also, Google (and most probably all other search engines) will only display the canonical URL in search results and not the other URLs.

In Drupal's case, the canonical URLs are properly set. For example, I have created a test article (node/2) and added comments and replies to it and got the following pages:

* /node/2
* /comment/2
* /comment/3

After inspecting their generated source code, they all have the same `<link rel="canonical" href="/node/2" />` in their source code properly created. So basically only the main article page will display in the search results.

Now, whether to modify core to only generate a single page or to have the robots.txt file patched as you specified is beyond me. I'm sure there will be lots of considerations and special cases to consider before implementing any of the above and since there really isn't a problem maybe it's best to keep things as is.

Cheers!

Note: I'm using Drupal 7.17 (latest version as of today).

---
Tags: comments, 7
---


title: Alias path precedence rule?

text:
# Question
Title: Alias path precedence rule?
I just checked that an alias path named, say, `any/path` can point to N different existing paths. Is there any fixed precedence order as per which one will be processed? Or is it a random order?

# Answer
Using the user interface, it is not possible to set the same alias pointing to different destinations for the same language.
If a module would execute code similar to the following one, it would be possible to have two records for the same alias.

```
$path = array(
  'alias' => 'homepage',
  'source' => 'node/1',
);
path_save($path);

$path = array(
  'alias' => 'homepage',
  'source' => 'node/2',
);
path_save($path);

```

drupal\_lookup\_path() contains the following code to retrieve the internal path associated with a path alias from the database. `$path_language` is the last argument passed to the function; when the function doesn't get that argument, it uses the value of `$GLOBALS['language_url']->language`.

```
    if ($path_language == LANGUAGE_NONE) {
      unset($args[':language']);
      $alias = db_query("SELECT alias FROM {url_alias} WHERE source = :source AND language = :language_none ORDER BY pid DESC", $args)->fetchField();
    }
    elseif ($path_language > LANGUAGE_NONE) {
      $alias = db_query("SELECT alias FROM {url_alias} WHERE source = :source AND language IN (:language, :language_none) ORDER BY language DESC, pid DESC", $args)->fetchField();
    }
    else {
      $alias = db_query("SELECT alias FROM {url_alias} WHERE source = :source AND language IN (:language, :language_none) ORDER BY language ASC, pid DESC", $args)->fetchField();
    }

```

If `$path_language` is equal to `LANGUAGE_NONE` (i.e. you are looking for the internal path associated with the language-independent alias), `drupal_lookup_path('source')` returns the internal path which is saved in the path\_alias table with the higher pid (which normally is the latest created row).
If `$path_language` is not equal to `LANGUAGE_NONE`, the database rows are ordered to get the language-specific alias before the language-neutral, and then by pid. Also in this case, the returned internal path would be the last created one.

Suppose url\_alias contains the following values.

```
pid   | source    | alias      | language
4     | node/1    | homepage   | und
5     | node/2    | homepage   | und
8     | node/21   | homepage   | it
9     | node/22   | homepage   | it
10    | node/31   | homepage   | xx-lolspeak
11    | node/32   | homepage   | xx-lolspeak

```

What I would get from that table is:

* `drupal_lookup_path('source', 'homepage')`: node/2
It returns the last created alias that is language-independent.
* `drupal_lookup_path('source', 'homepage', 'es')`: node/2
There isn't an alias for Spanish, and the function fallback to the language-independent alias. It gets the last created alias.
* `drupal_lookup_path('source', 'homepage', 'xx-lolspeak')`: node/32
It returns the last created alias for Lol Speak.
> 0 votes

---
Tags: path-aliases
---


# Question
Title: What is the difference between drupal_get_form and drupal_retrieve_form?
What is the difference between `drupal_get_form()` and `drupal_retrieve_form()`? Can someone explain the difference? I look at the API, but the description seems similar to me.

# Answer
> 11 votes
The difference is that `drupal_get_form()` handles retrieving, processing, and displaying a rendered HTML form for modules automatically, while `drupal_retrieve_form()` returns the structured array that defines a form.

### Retrieving the form

`drupal_get_form()` first checks if the form is present in the form cache with form\_get\_cache(); if it isn't present, it calls drupal\_retrieve\_form(), and drupal\_prepare\_form().

### Processing the form

`drupal_get_form()` calls drupal\_process\_form(), which is the function that calls drupal\_validate\_form(), and that invokes the submission handlers with form\_execute\_handlers().

### Rendering the form

The rendering is done from `drupal_process_form()`, which calls form\_builder().

In most of the cases, `drupal_get_form()` is the function to use, such as in the following code.

```
function node_menu() {
  $items['admin/content'] = array(
    'title' => 'Content',
    'description' => 'Find and manage content.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('node_admin_content'),
    'access arguments' => array('access content overview'),
    'weight' => -10,
    'file' => 'node.admin.inc',
  );

  // …

  return $items;
}

```

The only module I found that is calling `drupal_retrieve_form()` directly is the Mollom module in mollom\_moderate(), which uses it for automatically submitting a form. The code could use drupal\_form\_submit(), but (as a comment says), "Programmatic form submissions are not able to automatically use the primary form submit button/action, so we need to resemble `drupal_form_submit()`."

```
  $form_id = $form_info['delete form'];
  $form_state = form_state_defaults();
  // We assume that all delete confirmation forms take the fully loaded
  // entity as (only) argument.
  $messages[] = "Attempt to load $form_info[entity] entity via entity_load().";
  $entities = entity_load($data->entity, array($data->id));
  $form_state['build_info']['args'][] = $entities[$data->id];
  $form = drupal_retrieve_form($form_id, $form_state);

  $form_state['values'] = array();
  $form_state['values']['mollom']['feedback'] = '';
  // Take over the primary submit button of confirm_form().
  $form_state['values']['op'] = $form['actions']['submit']['#value'];

  $form_state['input'] = $form_state['values'];
  $form_state['programmed'] = TRUE;
  // Programmed forms are always submitted.
  $form_state['submitted'] = TRUE;

  // Reset form validation.
  $form_state['must_validate'] = TRUE;
  form_clear_error();

  drupal_prepare_form($form_id, $form, $form_state);
  drupal_process_form($form_id, $form, $form_state);

  $result = $form_state['executed'];

```

---
Tags: 7, forms
---


title: Error while creting field help needed

text:
# Question
Title: Error while creting field help needed
I am trying to create a field in `hook_install()` using the following code.

```
$field = array(
  'field_name' => 'unit_count',
  'type' => 'text',
  'cardinality' => FIELD_CARDINALITY_UNLIMITED,
);

field_create_field($field);

$instances = array();

$instances['unit_count'] = array(
  'field_name' => 'unit_count',
  'label' => $t('unit_count'),
  'description' => $t('unit_count'),
  'widget' => array(
    'type' => 'text_textfield',
  ),
  'required' => TRUE,
  'settings' => array(
    'text_processing' => 0,
  ),
);

foreach ($instances as $instance) {
  $instance['entity_type'] = 'node';
  $instance['bundle'] = 'first_example_bundle';
  field_create_instance($instance);
}

```

I am getting the following error:

> Notice: Undefined index: id in field\_create\_field() (line 173 of /Library/WebServer/Sites/Dev/Public/Peirce/modules/field/field.crud.inc).

What is wrong with the code I am using?

# Answer
Im not sure what your error is. Every field has different widget settings and differing options ... keeping all the options you can set straight in my head is beyond me ... I have created fields in install profiles and using hook\_install. I tend to build the fields using the Field UI found at `Structure -> Content Type -> then add/edit Fields` then export those settings to code for use in a module.

I found this blog post immensely helpful:

Exporting and creating field definitions in Drupal 7

From the blog post you can get a field and its instance config with:

```
$field_data = field_info_field('field_article_image');
$instance_data = field_info_instance('node', 'field_article_image', 'article');

```

You can create a field and instance(s) in PHP using the Field API:

```
field_create_field($field_data);
field_create_instance($instance_data);

```

You can use Devel or Drush with `drush php-script or eval` and the following code nabbed from the blog post. It will generate the above 2 lines of code with the `$config` and `$instance` data all filled out for you to use in your custom code:

```
$entity_type = '';
$field_name = 'field_';
$bundle_name = '';

$info_config = field_info_field($field_name);
$info_instance = field_info_instance($entity_type, $field_name, $bundle_name);
unset($info_config['id']);
unset($info_instance['id'], $info_instance['field_id']);
include_once DRUPAL_ROOT . '/includes/utility.inc';
$output = "field_create_field(" . drupal_var_export($info_config) . ");\n";
$output .= "field_create_instance(" . drupal_var_export($info_instance) . ");";
drupal_set_message("<textarea rows=30 style=\"width: 100%;\">". $output .'</textarea>');

```

**EDIT:**

Once you see a valid export from an example field you are trying to create. It can be easy to re-use, tweak, or fix small parts of that field configuration to use in the same project or other projects. But I never sit down from scratch and try to code it all by hand for every field.
> 0 votes

---
Tags: entities
---


# Question
Title: Drupal 7, Dev Site, will not Aggregate Javascript or CSS
I have two installations of the same site. The first is sub.website.com, and is the main website. The second is sub.website.com/drupaldev. On the /drupaldev site I cannot get the javascript or CSS to aggregate, which is causing myriad odd problems. I have checked the tmp directory, changed it, modified permissions and re-installed the site from scratch. None of these things has allowed me to get the website to aggregate.

Is the problem that I am hosting the development site as a folder of the main site?

# Answer
This could really be a myriad of problems. More than likely, your files directory isn't writable. Browse to the Status Report (admin/reports/status) and make sure the File System section says Writable. While you are at it, make sure everything on the report is green.

Running a second Drupal site in a subdirectory of the first site is a tricky situation. The main concern is the way Apache handles .htaccess files in a directory tree. htaccess rules apply to the directory that the file is in, plus all subdirectories. This means that your site in /drupaldev is going to inherit the directives from the root htaccess file. This may or may not cause problems, but in general, this is a big red-flag.
> 3 votes

---
Tags: 7, performance
---


# Question
Title: Writing a news ticker module. It works, but it's sloppy as hell. Is there a better way to do this query?
I've got three pre-existing websites that use the story module, the path module, and CCK to produce customized news stories in Drupal 6. I wanted to create a news ticker module, to consolidate the news from all three sites, and replace the per site views based approach we're using now.

Studied the entire schema that the sites use, and dissected Drupal to see if there was a relatively straight forward way to do this. Turns out, there isn't. Architecturally, Drupal is all over the place.

So what I came up with was a situation where I do a crazy join between the nodes table and the the url\_alias table, then union the whole thing together because the tables are identical between schemas.

Like this:

```
            SELECT
                   'site1' as disposition,
                   url_alias.dst as destination_url,
                   node.sticky,
                   node.promote,
                   node.created
              FROM    site1.node node
                   INNER JOIN
                      site1.url_alias url_alias

                   ON (node.nid = substring(url_alias.src,6,15) )

              WHERE substring(url_alias.dst,1,5) = 'news/'

              UNION

              SELECT
              'site2'  as disposition,
              url_alias.dst as destination_url,
                   node.sticky,
                   node.promote,
                   node.created
              FROM    site2.node node
                   INNER JOIN
                      site2.url_alias url_alias

                   ON (node.nid = substring(url_alias.src,6,15) )

              WHERE substring(url_alias.dst,1,5) = 'news/'

              UNION

              SELECT

              'site3'  as disposition,
              url_alias.dst as destination_url,
                   node.sticky,
                   node.promote,
                   node.created
              FROM    site3.node node
                   INNER JOIN
                      site3.url_alias url_alias

                   ON (node.nid = substring(url_alias.src,6,15) )

              WHERE substring(url_alias.dst,1,5) = 'news/'

              ORDER BY 4 DESC

```

But it seems to me that this is incredibly sloppy, and that there has to be a better way to do basically the same thing by depending on correctly formed relationships and keys, rather than using SUBSTRING to parse url aliases.

What do you think?

# Answer
Two things jump out at me, both related to the use of `{url_alias}`:

* I don't see why you need to do the string shenanigans in the `WHERE`. You should be able to to use `node.type` to limit yourself to the subset of nodes you want, especially if you are primarily using Pathauto settings.
* I don't see why you explicitly need to return `url_alias.dst` in the result set. If you have the nid, then you can just use `$path = url('node/' . $nid);` to build up paths (or use `l()`).

I think this means that you should be able to eliminate the `JOIN` on the `{url_alias}` altogether, which should make the query much faster.
> 1 votes

---
Tags: database
---


title: Admin approval of Commerce order

text:
# Question
Title: Admin approval of Commerce order
I am building a proof of concept ecommerce solution using commerce kickstart v2

I wish to implement a system where a user can submit an order but an admin must approve orders before the customer can pay - I have a feeling I can do this with rules & extra order statuses but I cannot figure out which part of the checkout process to intervene in. Heres what I have so far:

1. extra order status "Awaiting Admin Approval"
2. extra order status "Approved by Admin"
3. Rule that fires when order status changes from 'shopping cart' to 'checkout' and sets order as "Awaiting admin Approval"
4. Rule that fires when order status is "Awaiting Admin Approval" and path contains 'checkout'. this rule redirects user to a page that says 'your order is awaiting approval'
5. *Rule that should allow user to checkout once admin has changed order status to "Approved by admin"*

Rule 5 above (in italics) is giving me problems, no matter what I try - rule # 3 always fires, even after the order has been approved, which results in the user being redirected.

The problem arises because once the order has been set as "Approved by Admin", it must then go back to "shopping cart", then "checkout"... which then fires rule 3, which brings me nicely back around in a circle.

Any tips or suggestions?

# Answer
> 0 votes
You might consider one of two methods:

1. Define another status/branch in the checkout logic (approved shopping cart -\> checkout) wherein Rule 5 would redirect to the approved cart step instead of the standard shopping cart.

or

1. Implement an "admin approved" flag on the Order that you could set in your actions for Rule 5 and then test in your conditions for Rule 3, redirecting the user only if that flag was false. That flag could be implemented as a new field on the Order entity (assuming Order is an entity).

Method 1 might be somewhat redundant and more work than method 2, but I think it's the better of the two because it extends the current shopping cart/checkout/Rules logic and workflow. I think there's merit in that.

In addition, method 2 would bury a critical aspect of that logic into a field on the Order. I think the state of an Order in a checkout process should be defined separately from the Order itself.

Perhaps there's a third way that uses a little bit of both methods.

Hope this is helpful.

---
Tags: rules, commerce
---


# Question
Title: Join a user field to a profile2 field in a view
What I am trying to do is to join fields that are a user type (e.g. image, and username) to Profile2 fields. In the example I want to join:

* teacher name (teacher profile2)
* teacher date (teacher profile2)
* username (drupal registration)

What I mean by Drupal registration is the fields used to register an account.

# Answer
If you have to the display profile fields using the Views module, then follow these steps:

1. Add "User:profile" under "RELATIONSHIPS".
2. Select "Profile types" in which type you have your fields to be display (teacher name, teacher date), as you may have more than one profile types.
3. You can add the selected profile fields under "Fields".
> 2 votes

---
Tags: views, users
---


title: Carry a field in WebForm

text:
# Question
Title: Carry a field in WebForm
I would like to carry a field (i.e. Name) entered on the 1st page of a multi-page WebForm and reflect that field on the Confirmation (Thank You) page.

How would I go about doing this?

I am using Drupal 7.

# Answer
You can achieve it as follows:

* Copy webform-confirmation.tpl.php from /webform/templates and into your theme's template folder
* Rename it to webform-confirmation-{nid}.tpl.php to apply the template to a specific webform
* Make sure you clear Drupal's cache after placing or renaming the template file
* Add the following snippet

```
include_once drupal_get_path('module','webform') . '/includes/webform.submissions.inc';
$submission = webform_get_submission($node->nid, $sid);
// All the submitted values will be here, access the necessary values from this object.
// print_r($submission);

```

I tried this snippet, and it works. It was taken from Print submitted data on confirmation page.
> 2 votes

---
Tags: webforms
---


# Question
Title: Organic group request membership email issue
Can anyone recommend how I can get an emailing system working for when users request to join an organic group on my system?

Right now, my users click the "request membership" links and then provides a message and click a join button. But then nothing else happens.

Neighter the user nor the admin get any email confirmation.

Please help.

# Answer
For OG 7.x-1.x, I discovered that simply by enabling the Rules module, email notification Rules from OG are made active. That did the trick for me.

(Not sure about OG 7.x-2.x, which makes mention of the Message\_Notify module on the OG project page...)
> 4 votes

---
Tags: organic-groups, emails, notifications
---


# Question
Title: How to process the data which type is BLOB?
I get the following data from MySQL by `db_query()`. The type of the column is BLOB.

> a:2:{s:10:"attributes";a:1:{s:5:"title";s:0:"";}s:8:"langcode";s:7:"zh-hans";}

How should I process it?

# Answer
> 4 votes
Pass it to unserialize(). That is the string obtained from serialize(), when the argument is the following array.

```
$array = array(
  'attributes' => array('title' => ''),
  'langcode' => 'zh-hans',
);

```

`serialize()` is the function used from Drupal when the data to save in the database is an array.

---
Tags: database
---


title: Missing 'Input format'

text:
# Question
Title: Missing 'Input format'
On my inherited Drupal 6 site when I go to edit or add a news story 'Input format' is available for the Teaser, but not for the Body. I would like it for both or if it can only for one, have it on the Body so that I can choose an option such as 'Full HTML' so that images display. How do I achieve this?

# Answer
> 1 votes
check your CKeditor settings in the following path:

*yoursitename*/admin/settings/ckeditor/editg

If you find anything related to this

**"*your content type*@node/add/*your content type*.edit-body"** in the "Fields to exclude/include: " textarea, just remove.

---
Tags: input-formats
---