# Question
Title: What is the fastest way to convert a large volume of documents (.html) to drupal nodes
How would you go about creating a large number of nodes from a large number of html documents?

I am trying to create something similar to a book and have a lot of .docx files on my computer. I am aware I should use a wysiwyg editor to clean up the formatting and make it look like I want saving it as HTML. However there is the issue of getting all the .html files uploaded as nodes without having to copy-paste 200+ times.

Any ideas?

# Answer
> 10 votes
The module that appears as most suitable for you is called **HTML import**. This module will divide one single large HTML document into a structured Drupal book where the heading level hierarchy is respected. This module works with HTML exported from Word; HTML document converted from PDF as well as HTML document exported from Adobe InDesign.

This makes it possible to use a *single* HTML page, created in a word processing program and saved as HTML, or other structured HTML, to create a multipage Drupal book in a single step. You actually need to collate the output from all your `.docx` files into a single HTML-file before converting to HTML to use **HTML import** in a single step.

In case your requirements are beyond what **HTML import** is capable of, below is a list of all the (usable) Drupal modules I am aware of that can be used to bulk import HTML (and some other formats) into a Drupal site:

1. **HTML import** \- Import a *single* HTML page created from MS Word and split it up into an hierarchical Drupal book structure consisting of a set of interlinked Drupal nodes.
2. **HTML2Book** \- This also imports a *single* HTML page and split it up into an hierarchical Drupal book structure consisting of a set of interlinked Drupal nodes, but requires you to clean up the tagsoup created by MS Word first.
3. **Import HTML** \- Import all of an existing, static HTML-site into a Drupal site as nodes.
4. **Feeds** \- Import or aggregate data as nodes, users, taxonomy terms or simple database records.
5. **Migrate** \- Provides a flexible framework for migrating content into Drupal from other sources, including HTML.
6. **Node import** \- Allows users to import content (node, user, taxonomy) from CSV or TSV files. Requires you to convert from HTML to CSV. (no Drupal 7 version)

Of these, the simplest to use are **HTML import** and **HTML2Book**. However, both can only handle a single HTML page. For more complex conversion tasks, where you need to convert a large static HTML-site made up of several interlinked pages, one of the other modules may be more suitable.

**Also:** Whatever tool you use, *never* experiment with bulk import on a production site. Unless you're a lot more clever than me, there are going to be false starts and botched imports. Cleaning up thousands of nodes damaged by an import gone wrong is not fun. Always experiment with bulk import on a throwaway staging site that just can be discarded wholesale when things go wrong. Transfer the settings and do the import on the *production* site when you're sure you have a working set-up.

# Answer
> 3 votes
If you have a lot of docx files(which you do), then it is really worth the effort to write a custom migration class using the migrate module. Something similar has been done before and documented.

# Answer
> 2 votes
Here is a nice tutorial for learning how to use feeds. It is really quite straightforward. http://mustardseedmedia.com/podcast/episode55

Please note that it doesn't cover how to import html docs but it should get you pretty far down the road.

Also, you really should learn how to use backup and migrate module ( https://drupal.org/project/backup\_migrate) so you can easily backup and restore your database if you break something. I would also recommend you take the time to setup an extra copy of your site that you can experiment on. It is very frustrating when you break something and can't find your way back.

Selwyn

---
Tags: nodes, files, theming
---


# Question
Title: Filter date + between dates is not possible
In a view I show content that contain some fields and an entity reference.

In the Fields part of the view I have a field (`Vervaldatum`) like this.

The Vervaldatum field is a date field. I would like to have a "Vervaldatum between \[…\] and \[…\]" filter, but when I add a filter and select the Vervaldatum field, I get this.

I was hoping to get "between \[…\] and \[…\]" in the operator field, but no luck. It's like the field is handles as it is a text field, but the in the previous screen it's clear it is a date field.

These are the operators that I can use.

# Answer
I followed the following steps using a Date field and got the intended result:

**Firstly add your date field as a View filter**

**I left the configure date filter settings as default here**

**Configured the "greater than" exposed filter**

**Configured the "less than" exposed filter**

**Exposed filters appear correctly**

Those are the exact steps I followed to get the two exposed date filters. Hope you come right!
> 1 votes

---
Tags: views
---


# Question
Title: How to force a specific theme for a View's page?
My View page looks rubbish in the site's custom theme so I'd like to force it to use another simpler theme.

Thanks

# Answer
There are two ways to do this.

The easiest is to use ThemeKey:

> ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules.

You could use it to create a rule based on your view's path.

The other method uses `hook_custom_theme()`. Something like this would work.

```
function MYMODULE_custom_theme() {
  $request_path = request_path();

  if ($request_path == 'path/to/my/view/page') {
    return 'the_simple_theme_machine_name';
  }
}

```

You can also use `views_get_page_view()` to check the `$view->name` and `$view->current_display`, for the logic inside the hook.

Of the two solutions, using ThemeKey is best unless you are struggling with the selection rules.
> 5 votes

# Answer
For simple theme switching based on urls etc.. you could look at ThemeKey module

> ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules.

If you are using Drupal 6 and need further properties to decide, if the theme has to be switched, there is ThemeKey Properties (most of the properties are included in the Drupal 7 module)

> ThemeKey Properties provides additional properties for use with the ThemeKey module.
> 3 votes

---
Tags: views, theming
---


# Question
Title: Add css file when editing specific content type
I would like to add a css file when editing content of the content type invoice.

The link is something like this: `node/121/edit` . I've tried it with it with preprocess\_node like this:

```
function themename_preprocess_node(&$variables) {
    $node = $variables['node'];
    if($node->type == 'invoice')
    {
        drupal_add_css(drupal_get_path('theme', 'themename') . "/css/add.css", array('weight' => 1003));
    }
}

```

But he doesn't add the css file. When I do a `die;` in the if structure he executes it...

# Answer
> 0 votes
You're targeting the incorrect preprocess function. By the time preprocess\_node is run all our JS and CSS has been included in the top of our html document already.

Use this function instead:

template\_preprocess\_html

---
Tags: nodes, theming
---


title: Problem with PDO MySQL

text:
# Question
Title: Problem with PDO MySQL
For the last couple of days I've been getting the following error:

> Fatal error: Undefined class constant 'MYSQL\_ATTR\_USE\_BUFFERED\_QUERY' in /home/mydomain/public\_html/drupal/includes/database/mysql/database.inc on line 46

This comes after my Hosting did an upgrade and PHP is now version 5.2.17. From what they have told me, I think I have to enable a PDO MySQL extension in php.ini. The problem is I'm on a shared hosting and I don't have access to the file; also, my Hosting said they can't change it either. My info.php shows:

> PDO
>
> PDO support enabled
> PDO drivers sqlite, sqlite2
>
> pdo\_sqlite
> PDO Driver for SQLite 3.x enabled
> PECL Module version (bundled) 1.0.1 $Id: pdo\_sqlite.c 293036 2010-01-03 09:23:27Z sebastian $
> SQLite Library 3.3.7

I tried modifying the .htaccess file and/or adding my own php.ini file to the root directory per some suggestions I found, but nothing I've tried has worked yet.

Can anyone please suggest what else I could do?

EDIT:

Once again I asked the Hosting to enable PDO\_MySQL extension and their answer was that they could not, that cPanel (to which they migrated from Plesk, causing this whole problem) had this extension disabled by default and changing it would affect their servers. Their solution? That I would change my programming to adjust to these new features, which I wouldn't even know how to go about. Are they right requesting that I do this? Is there any other way?

# Answer
Your hoster needs to enable that extension. I don't think you can do that in a local php.ini file.

I don't believe that they can't do it, they just need to add an extension=pdo\_mysql.so to the php.ini, install the package, depending on whatever setup they are using. It's their job to do that, pdo\_mysql is a hard requirement for Drupal 7.
> 8 votes

# Answer
In my case when I swap PHP version in WAMP this error stopped me. I checked my phpinfo() then i observed PDO is enable but it's value is Blank

Solution : Go to in your php.ini file and find "extension\_dir" and changed it's path to current working php's ext directory.

ex/: extension\_dir = "c:/wamp/bin/php/php5.2.9/ext/"

Restart you wamp, it will start working again ....
> 0 votes

---
Tags: 7, database
---


title: My core Comment module is gone

text:
# Question
Title: My core Comment module is gone
Recently I lost comments and everything related. In the module list I see "Comment (missing)". All I did before:

Manual updating the core from 7.27 to 7.28 didn't help. All comment module files are in the folder they suppose to be (modules/comment/). But Drupal doesn't see the module.

Any help would be appreciated.

# Answer
> 3 votes
If the comment module files are there in `/modules/comment` but not displayed in Admin \> Modules it suggests the folder isn't readable by the webserver user.

Check the permissions are correct on the `/modules/comment` folder to allow read access.

For example:

```
# Run from Drupal root
# Comment module folder ensure readable
chmod 755 modules/comment
# Recursive chmod on files to ensure readable
find modules/comment -type f -exec chmod 644 {} \;

```

# Answer
> 0 votes
If you're unable to rollback your site to the state it was just prior to the last install/update, and its not a permissions problem, my suggestion is to migrate the content into a fresh install.

First check that the comments are not missing from the database: Use *phpMyAdmin* or another database examination tool to check the table `comment` still exists and has usable content). I'll be very surprised if it is gone if you have not actively un-installed the comment module.

Provided comments still are present, do the following:

1. Disable any module you don't need. Disabling a module will not make you lose any data.
2. Uninstall any module that you don't absolutely need. Un-installing *will often cause data loss*, so carefully review your options here.
3. After doing the above, make a full backup of your site using the Backup and Migrate module.
4. Do a fresh install of the latest version Drupal core on a staging server.
5. Roll back the backup created in step 3 above into the fresh install on the staging server (do not touch your production server at this point).
6. Check that the core **Comment** module is present, enabled, and that comments appear as they're supposed to.
7. Carefully re-enable all the other modules on you want to use, one by one. Make sure you do this on the staging server. After each install and configuration, check carefully that all is still fine. Hopefully, this should not cause any breakage, and it should give you a healthy site at the end of the task. If one install breaks something, you at least knows the cause, and can redo the procedure from step 4, skipping the install that causes the problem.
8. After you've restored your site to full health on a staging server, take a full backup of that, and then repeat the successful procedure on the *production server*.

Hope this helps.

# Answer
> 0 votes
Solved.

The problem was in the traces of my old experiments: there was a folder `sites/all/modules/my_comments` with almost empty `comment.module` file inside. I have no idea why didn't that thing come up earlier (I was playing with 'module customization' a while ago and cache has been cleared many times) but now my comments are back.

Thanks everybody who where trying to help. And my apologies for my English.

---
Tags: comments
---


# Question
Title: Organic Groups admin has can't edit roles and permissions in groups
I have a user who is an "administrator member" of a group called "Fancy group".

"Administrator members" of this group have permission to administer roles and permissions within the group.

but my user, an administrator of Fancy group, can only view the roles and permissions, not administer them:

Is this a bug in OG or am I doing something wrong?

# Answer
The problem is probably that the group doesn't have it's own role/permission settings. It's using the global og roles/permissions, and so the settings within the group are all read-only.

One of the fields you can add to group entities via the OG Fields settings is a "Group Roles and Permissions" field. Once that field is added, you can edit the group entity and set the field to "Override default roles and permissions".

Once that's done, the group will have it's own permissions, and users within the group who have permission to edit the groups permissions will be able to.
> 4 votes

# Answer
You'll want to checkout the organic groups documentation on roles & permissions.
> 0 votes

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


# Question
Title: How to fix incorrect forum post count when using internalization and locale?
Using (among several other contrib modules)

* Forum
* Locale
* Advanced Forum
* Internationalization

My forum topic nodes are set to be localized and I've set translations for the Forum Vocabulary and all the terms. The forums work well with Internationalization after I modified some of the views and added a 'Content: Language (= Current user's language)' filter.

However the Topics count in the main forum page is incorrect, it doesn't take into account the language, so we see a higher count than we should.

For example: https://freshwaterwatch.thewaterhub.org/forum

The 'Meet & Greet' forum has five topics but when you enter you only see two topics: https://freshwaterwatch.thewaterhub.org/forums/meet-and-greet

What happens is that if you click on the French language you see one and two more in the Spanish language, that's why the count for the forum is 5 but you should instead see a count of 2 when browsing the site in the default english language.

Does anyone know how to solve this or a workaround?

# Answer
> 1 votes
Look at advanced\_forum\_statistics\_topics (check your `advanced_forum` version)

```
return db_result(db_query('SELECT COUNT(DISTINCT(nid)) FROM {forum}'));

```

You can use preprocess forum\_statistics and instead of `advanced_forum_statistics_topics();` use your own function to select only nids which relate to the current language.

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


# Question
Title: Why can 'Others' read settings.php by default?
By default, `settings.php` has its permissions set to 404, which means 'Others' can read the file. Why not set it to 400, so that only the user can read the file? Thanks.

# Answer
The reason for this default, I believe, is because on some hos plans (e.g. bargain basement shared hosting), the web server user is *not* by default the owner of the file. On some hosting plans, it may not even be an option to use commands such as `chown` and `chmod` to set up things exactly the way you want.

The web server user *must* be able to read this file to get access to DB credentials, and on such hosting plans, allowing "Other" to read is the only way to achieve that. (Having `400` as the default would most certainly create a deluge of support requests from people unable to figure out why Drupal can't access their database.)

If you know what you're doing, it is OK to 1) make sure the file is owned by the web server user, and 2) set permissions to `400`.
> 2 votes

# Answer
settings.php should be chmod 644 according too https://drupal.org/documentation/install/settings-file

It's more of a general rule then a requirement. Really it depends how apache runs itself (ie. what user they run as). What ever user they run as needs to have read permissions to that file.
> 1 votes

---
Tags: configuration
---


title: Preventing webform saving in database

text:
# Question
Title: Preventing webform saving in database
Is there a way to prevent a webform submission to be saved in the database?

I have added a custom submit handler to my webform but I don't want to save in the DB but send it to an external webservice.

```
function MY_MODULE_form_alter(&$form, $form_state, $form_id)  {

    if ($form_id == "MY_WEBFORM_ID")  {
        $form['#submit'][] = "_MY_MODULE_webform_handler";
    }

}

function _MY_MODULE_webform_handler($form, &$form_state) {
    // How do I stop data being saved in DB?
}

```

How do I do that? Thanks!

# Answer
There is a module that's compatible with the 7.x-3.x branch that gives you the option to do just that:

> This module adds the ability to choose whether a webform should be saved to database or not. Within settings of each webform you can choose the option.

There is also a related issue in Webform's queue that is tracking the progress of getting the functionality into the webform module.

If you don't want to use the sandbox module, I'm sure you could check out the source and see what they're doing differently from what you have posted above.
> 3 votes

---
Tags: webforms, forms
---


# Question
Title: What is the 'Drupal way' to create a menu callback and display a rendered page of JSON?
I have created a new menu item and a callback function.

```
  ...
  $items['user/%user/enquiries'] = array(
    'title' => t('Enquiries'),
    'page callback' => '_client_enquiries',
    'access callback' => 'user_access',
    'access arguments' => array('view enquiries'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 1
  );
 ...
 function _client_enquiries() {
   return t('Enquiries');
 }

```

I am now going to CURL some json from a published google spreadsheet, and cherrypick, and then print some of it out in a table. My question.. what is the drupal way to do this? I think it would be to create a custom theme function which makes my processed json data available to a template, which I can somehow load onto my menu callback and output. If that is the case, could anyone give me some pointers/examples or a point in the right direction.

# Answer
> 2 votes
Much simpler:

```
function _client_enquiries() {

  $var_to_output = caculate_value_to_return();

  drupal_json_output($var_to_output);
  drupal_exit();
}

```

---
Tags: theming
---


title: cron_last vs node_cron_last variable

text:
# Question
Title: cron_last vs node_cron_last variable
I wanted to get the **time** of last node update (any node). So, then I thought I could simple pick **last cron run time** ( because I am using feeds module to pull the RSS feeds so nodes will be updated on every cron run ). but then I discovered another variable "node\_cron\_last".

Can anyone explain me the difference between two variables, what value they contain?

# Answer
The only place `node_cron_last` is set is in `_node_index_node()`, which is run when indexing a node for search results.

Its purpose, per the comments:

> Save the changed time of the most recent indexed node, for the search results half-life calculation.

`cron_last` is simply used to

> Record cron time.

per `drupal_cron_run()`

Given that `REQUEST_TIME` is used for all values (cron variables + node changed date) in the same request, you might well expect those two variables to contain the same value.
> 0 votes

---
Tags: 7, cron
---


# Question
Title: Field Collection with Date for Calendar View
I'm working on the content design for a new site, but I'm having a major hangup with some of the connections between the data types, especially when it comes to Dates and Calendars. Here's the rundown:

* Films share a many to many relationship with Programs.
* Programs can have one or many Screenings.
* Screenings each have one Date and Venue.

I've successfully accomplished this using Node Reference and Field Collection. There is a node reference between Films and Programs. Programs contains a field collection called Screenings. The field collection Screenings contains the fields Date and Venue.

The functionality I love from this setup is that each Date and Venue pair is grouped, and I can just click the Add button to generate another pair within that Program. This satisfies the one or many requirement for Screenings.

Unfortunately, when I start to build this all into a Calendar view (Date module, Calendar module), it breaks terribly. Depending on how I set things, I end up with SQL errors or index errors within Drupal. None of it works. Reading through issue posts, I've gathered that this is probably some sort of complexity added by Field Collection which is not handled in Calendar.

Short of getting Field Collection to play nice with Date and Calendar, can anyone suggest another method for implementing this? My next thought would be to move Screenings off into its own node and create another node reference between that and Programs. However, that would mean I lose the clean and simple Add button to generate a new Screening within a program.

Perhaps a custom add/edit form is all I really need. Unfortunately, that road seems rather perilous for me without some clear guidance.

# Answer
I couldn't get Calendar to play nice with Field Collections. It seems like I needed to somehow provide for the custom calendar row plugin or calendar items within the field collection view (it's too complicated).

Ultimately, I went with the FullCalendar module, which is built on the FullCalendar jQuery plugin.

It's very clean, simple to setup, and it plays very nicely with everything I'm throwing at it. If Calendar and Field Collections make any further progress with their development, I might revisit them, but for now this fits the bill.
> 4 votes

# Answer
I was up against this exact problem, but kept banging away at it until I figured it out.

It doesn't work by default because views is looking for nodes, and fields in field collections aren't recognized as part of a node. You need to be very explicit with views as to where to find the date field.

1. Install Field Collection Views module, which will create a "field collection views" view. Clone that, don't edit it directly in case you need to come back to it.
2. Change the format to Calendar
3. Create a relationship to the entity that contains the field collection items
4. Create a contextual filter for the date field in your field collection
5. create contextual filters for other fields in the content type with the field collection
6. add those fields to the field section.

It was complicated and took me hours to figure out. I gave up several times. I stayed up way too late. I THINK I have outlined all the steps. Hopefully it will help someone a little bit.
> 1 votes

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


# Question
Title: Emails are not being processed in hook_node_presave and hook_node_insert
I'm using htmlmail module. I'm trying to send an email after node save. So I put drupal\_mail() into hook\_node\_insert() or hook\_node\_presave(), but when I'm doing this, the body of my emailes are empty.

The source looks literally like this:

```
<div class="htmlmail-body">
</div>

```

The templates are not processed. The hook\_preprocess\_htmlmail() function in template.php is not beeing invoked. I'm using different templates for different mail keys.

Now the funny thing is that when I'm using the same drupal\_mail() in hook\_cron() it just works as expected. I have no idea how I can debug this. Any ideas (for example where to put a debuggers break for further diagnosis)?

**Added #1**: It appears that only htmlmail.tpl.php is being used instead of my module and key specific templates that works when I'm sending mails from cron.

**Added #2**: Code in hook\_cron() and in hook\_node\_presave() is the same:

```
$receipents = array( variable_get('site_mail', 'example@example.com') );
$params = array();
drupal_mail('bonds_cron', "create_payments__client", implode(', ', $receipents), language_default(), $params, variable_get('site_mail', 'example@example.com'), true);

```

The difference is that in hook\_cron() it works, and in hook\_node\_presave() it doesn't. I was trying to change double "\__" into one, thinking that maybe it's something with picking up templates, but without success. I'm searching now for place in core code, when I could put a break to see what is going on when picking up those templates but I cannot find it. :/

**Added #3**: template\_preprocess\_htmlmail() run just fine. The proper template suggestion is added there.

**Added #4**: I added `var_dump($items)` before the end of htmlmail\_theme() function. When clearing cache I got this output:

```
array(11) {
  'htmlmail__bonds-cron__create_payments__admin' =>
  array(4) {
    'variables' =>
    array(1) {
      'message' =>
      array(0) {
        ...
      }
    }
    'template' =>
    string(44) "htmlmail--bonds-cron--create_payments__admin"
    'path' =>
    string(35) "sites/default/themes/bond/templates"
    'theme path' =>
    string(25) "sites/default/themes/bond"
  }
  'htmlmail__bonds-cron__create_payments__agent' =>
  array(4) {
    'variables' =>
    array(1) {
      'message' =>
      array(0) {
        ...
      }
    }
    'template' =>
    string(44) "htmlmail--bonds-cron--create_payments__agent"
    'path' =>
    string(35) "sites/default/themes/bond/templates"
    'theme path' =>
    string(25) "sites/default/themes/bond"
  }
  'htmlmail__bonds-cron__create_payments__client' =>
  array(4) {
    'variables' =>
    array(1) {
      'message' =>
      array(0) {
        ...
      }
    }
    'template' =>
    string(45) "htmlmail--bonds-cron--create_payments__client"
    'path' =>
    string(35) "sites/default/themes/bond/templates"
    'theme path' =>
    string(25) "sites/default/themes/bond"
  }
  'htmlmail__bonds-cron__payments_alert__admin' =>
  array(4) {
    'variables' =>
    array(1) {
      'message' =>
      array(0) {
        ...
      }
    }
    'template' =>
    string(43) "htmlmail--bonds-cron--payments_alert__admin"
    'path' =>
    string(35) "sites/default/themes/bond/templates"
    'theme path' =>
    string(25) "sites/default/themes/bond"
  }
  'htmlmail__bonds-cron__payments_alert__agent' =>
  array(4) {
    'variables' =>
    array(1) {
      'message' =>
      array(0) {
        ...
      }
    }
    'template' =>
    string(43) "htmlmail--bonds-cron--payments_alert__agent"
    'path' =>
    string(35) "sites/default/themes/bond/templates"
    'theme path' =>
    string(25) "sites/default/themes/bond"
  }
  'htmlmail__bonds-cron__payments_alert__client' =>
  array(4) {
    'variables' =>
    array(1) {
      'message' =>
      array(0) {
        ...
      }
    }
    'template' =>
    string(44) "htmlmail--bonds-cron--payments_alert__client"
    'path' =>
    string(35) "sites/default/themes/bond/templates"
    'theme path' =>
    string(25) "sites/default/themes/bond"
  }
  'htmlmail__bonds-cron__tax_alert__admin' =>
  array(4) {
    'variables' =>
    array(1) {
      'message' =>
      array(0) {
        ...
      }
    }
    'template' =>
    string(38) "htmlmail--bonds-cron--tax_alert__admin"
    'path' =>
    string(35) "sites/default/themes/bond/templates"
    'theme path' =>
    string(25) "sites/default/themes/bond"
  }
  'htmlmail__htmlmail' =>
  array(4) {
    'variables' =>
    array(1) {
      'message' =>
      array(0) {
        ...
      }
    }
    'template' =>
    string(18) "htmlmail--htmlmail"
    'path' =>
    string(26) "sites/all/modules/htmlmail"
    'theme path' =>
    string(25) "sites/default/themes/bond"
  }
  'htmlmail__simplenews' =>
  array(4) {
    'variables' =>
    array(1) {
      'message' =>
      array(0) {
        ...
      }
    }
    'template' =>
    string(20) "htmlmail--simplenews"
    'path' =>
    string(26) "sites/all/modules/htmlmail"
    'theme path' =>
    string(25) "sites/default/themes/bond"
  }
  'htmlmail__user__password_reset' =>
  array(4) {
    'variables' =>
    array(1) {
      'message' =>
      array(0) {
        ...
      }
    }
    'template' =>
    string(30) "htmlmail--user--password_reset"
    'path' =>
    string(35) "sites/default/themes/bond/templates"
    'theme path' =>
    string(25) "sites/default/themes/bond"
  }
  'htmlmail' =>
  array(4) {
    'variables' =>
    array(1) {
      'message' =>
      array(0) {
        ...
      }
    }
    'template' =>
    string(8) "htmlmail"
    'path' =>
    string(35) "sites/default/themes/bond/templates"
    'theme path' =>
    string(25) "sites/default/themes/bond"
  }
}

```

Seems ok for me.

# Answer
Ok, after digging VERY deep in theme.inc code I found the problem. I named my templates "htmlmail--bonds-cron--create\_payments\__client" and I should "htmlmail--bonds\_cron--create\_payments\__client" (notice underscore instead of dash). Replacing underscore with dash made anomalies in ThemeRegistry storage, probably caused by string translations (of template names) in theme.inc . The consequence was this very strange different drupal\_mail behaviour in different hooks. I hope it will help someone.
> 0 votes

---
Tags: 7, emails
---


# Question
Title: View contextual filter only applies to first filter AND/OR group
I have a view that returns two different content types in its results. Each content type needs different filters, so I group them using OR and AND. See below:

This view represents a category page and filters the results using a contextual filter. Both content types share the same category field. However, the contextual filter (a taxonomy term based on the URL) only applies to the first group of filters before the "OR". This shows up in the query it generates:

```
SELECT DISTINCT node.nid AS nid, node.created AS node_created, node.title AS node_title, node.sticky AS node_sticky, node.nid AS node_nid, 'node' AS field_data_field_image_node_entity_type, 'node' AS field_data_field_duration_node_entity_type, 'node' AS field_data_field_slug_node_entity_type, 'node' AS field_data_field_stickybit_expiretime_node_entity_type, 'node' AS field_data_field_ribbon_color_node_entity_type, 'node' AS field_data_field_ribbon_text_node_entity_type, 'node' AS field_data_field_blog_thumbnail_node_entity_type
FROM
{node} node
LEFT JOIN {field_data_field_segment} field_data_field_segment ON node.nid = field_data_field_segment.entity_id AND (field_data_field_segment.entity_type = 'node' AND field_data_field_segment.deleted = '0')
LEFT JOIN {field_data_field_submitted} field_data_field_submitted ON node.nid = field_data_field_submitted.entity_id AND (field_data_field_submitted.entity_type = 'node' AND field_data_field_submitted.deleted = '0')
WHERE (( (node.type IN  ('story')) AND (node.status = '1')
        AND (field_data_field_segment.field_segment_value IS NULL )
        AND (field_data_field_submitted.field_submitted_value NOT IN  ('2'))
        AND (node.nid IN
          (SELECT tn.nid AS nid FROM {taxonomy_index} tn
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th ON th.tid = tn.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th1 ON th.parent = th1.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th2 ON th1.parent = th2.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th3 ON th2.parent = th3.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th4 ON th3.parent = th4.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th5 ON th4.parent = th5.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th6 ON th5.parent = th6.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th7 ON th6.parent = th7.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th8 ON th7.parent = th8.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th9 ON th8.parent = th9.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th10 ON th9.parent = th10.tid
          WHERE ( (tn.tid = '205') OR (th1.tid = '205') OR (th2.tid = '205')
            OR (th3.tid = '205') OR (th4.tid = '205') OR (th5.tid = '205')
            OR (th6.tid = '205') OR (th7.tid = '205') OR (th8.tid = '205')
            OR (th9.tid = '205') OR (th10.tid = '205') )
        ))
      )
      OR ( (node.type IN  ('blog')) AND (node.status = '1') ))
ORDER BY node_sticky DESC, node_created DESC, node_nid DESC
LIMIT 12 OFFSET 0

```

You can see that the contextual filter is applied only to the first group, not both. Is there any way to get the contextual filter to apply to both?

```
Drupal 7.8
Views 7.x-3.0-rc1
Views UI 7.x-3.0-rc1

```

# Answer
Updating Drupal to 7.28 and the Views module to 7.x-3.7 solved the problem, as barraponto suggested it might.
> 0 votes

---
Tags: 7, views
---


title: I can't move blocks

text:
# Question
Title: I can't move blocks
I currently have a site that has quite a lot of blocks (about 120 in 1 region and many others in other regions).

Recently the Block admin page stopped working for me. I can't add any blocks through that screen, however when I go to the block detail page, I can.

All new blocks are handed the weight 0, and I cant change that (not by drag and drop, neither by manually entering the weight).

Anyone who know how I can fix this? Is it because there are too many blocks?

# Answer
> 1 votes
120 blocks in one regions seems to be excessive, you may want to attempt to consolidate them into a custom block and use context to set those. Also may want to look at creating multiple regions that reside in the same area

# Answer
> 0 votes
I had a similar issue, where I couldn't change the weight of my blocks and all new blocks had a weight of 0. I deleted a bunch of old blocks (about 50) and I was then able to assign weight to them again. I assume the issue was I had too many.

---
Tags: 7, blocks
---


# Question
Title: How do I only allow authenticated users to interact with Organic Groups "groups"?
Organic Groups 7.x-2.6 Domain Access 7.x-3.11 Domain Access Bridge (module that ties DA and OG together)

Hello, I am using Organic Groups with Domain Access. I found I was unable to only allow authenticated users to see/post/subscribe to groups.

Someone mentioned Access Control. I am using Domain Access and tried installing Access Control on top of Domain Access and Organic Groups. I was able to only allow authenticated individuals to interact with groups, but I ran into an issue where if a group was set to "private" only group admins could see the group, even if the non group admin was actually a member of the group. With Domain Access and OG it is not recommended to install another access control module, so it is not surprising this combination failed.

This really seems like this should be a part of OG (a sentiment that I have heard quite a bit on the net).

# Answer
> 0 votes
I ended up answering my own question. There is no access control with organic groups which disallows anonymous users from seeing public organic groups. You can use the "Domain Strict" module and have the website that the organic groups is to be hosted on not allow "Anonymous" users to view that domain. This is a configuration option with Domain Strict.

This has the desired effect. The only downside is that your domain which hosts your organic groups will not allow anyone who is not authenticated to view any content on said domain.

To change this go to Structure--\>domains--\>User Defaults find your domain that will hold your OG groups and uncheck "Anonymous User" Click save configuration.

Tada!

---
Tags: 7, organic-groups, users, domain-access
---


# Question
Title: How can I parse JSON data from a website and import them as nodes?
I am using the Drupal 7 releases of the *Feeds* and *FeedsJSONParser* modules, but I can't seem to figure out how to configure this to parse the feeds.

I want to parse this feed into their own nodes.

```
{
    "BTC_LTC": {
        "last": "0.0237",
        "lowestAsk": "0.02383797",
        "highestBid": "0.0237",
        "percentChange": "0.00642712",
        "baseVolume": "5.69603109",
        "quoteVolume": "240.78778654",
        "isFrozen": "0"
    },
    "BTC_NXT": {
        "last": "0.00007000",
        "lowestAsk": "0.00007350",
        "highestBid": "0.00007000",
        "percentChange": "-0.06542056",
        "baseVolume": "0.84850609",
        "quoteVolume": "12014",
        "isFrozen": "0"
    },
    "BTC_NMC": {
        "last": "0.00403",
        "lowestAsk": "0.00489",
        "highestBid": "0.00404001",
        "percentChange": "-0.04952830",
        "baseVolume": "0.27214383",
        "quoteVolume": "64.24716761",
        "isFrozen": "0"
    }
}

```

I have the following settings for JSONparser, but it doesn't seem to do anything. Would someone be kind enough to take a snapshot of there setup?

>

>

# Answer
> 5 votes
I think you have a problem with the "context", and title query. I've tried this configuration and worked for me.

The context is the first query and in this case just selects all the nodes, the second one takes the value of the key "last" ant put it on the node title.

Then you can play with other querys, to create the nodes, but at least this one works.

# Answer
> 4 votes
Why not just do it custom? Here is an example to get you started. Set your cron on the server to run every hour. This requires entity api

```
/** implements hook_cron **/
function poloniex_cron(){
 poloniex_get_feed();
}

function poloniex_get_feed(){
 //Get the feed and turn it into json
 $feed = file_get_contents("https://poloniex.com/public?command=returnTicker");
 $feed_json = json_decode($feed);

 foreach($feed_json as $item){
  poloniex_create_node($item);
 }
}

/**$item should be an array from the json feed**/
function poloniex_create_node($item){
  //Create an instance of the node and wrap it
  $node = entity_create('node', array('type' => 'content_type'));
  $node_wrapper = entity_metadata_wrapper('node',$node);

  //Set properties
  $node_wrapper->author = 1; // Admin as the author
  $node_wrapper->title->set("String");  //Title
  $node_wrapper->field_name->set("String"); //Textfield
  $node_wrapper->save();
}

```

# Answer
> 0 votes
The problem is that the JSON isn't structured in a way to make a easy mapping to a node. If the record were more like:

`"record": {"name": "BTC_LTC", "last": "0.0237", etc }`

...it would be much easier. You could then use angoru's answer and just parse `$.name` for a value like BTC\_LTC and put that in the title.

The other problem is that by the time you learn enough JPath to extract an individual record and its name, you could have written your own Feeds parser. :-)

I recently had to do something similar, and used Feeds: Meetup as a template.

---
Tags: 8, feeds
---


# Question
Title: One taxonomy term in multiple vocabularies
Is there is a way to refer to one term in more than one vocabulary?

e.g. i have 2 vocabularies ... Properties for sale and Properties for rent

Properties for sale:
**-Apartment**
-House
-Land
Properties for rent:
**-Apartment**
-summer house
-Room

So, how can i have the term (Apartment) in both vocabulary

# Answer
Well you could combine them in a single vocabulary and then your term can have two parents:

Properties
-Properties for sale
--Apartment
--House
--Land
-Properties for rent
--Apartment
--summer house
--Room
> 1 votes

---
Tags: taxonomy-terms
---


title: Disable shipping on checkout page

text:
# Question
Title: Disable shipping on checkout page
How to disable shipping or delivery pane by rules on checkout page? i am developing a sytem using ubercart in drupal 7.

# Answer
1. You can hide it dynamically if no products in the order are shippable. We are using ubercart 7.x-3.4 and on the Checkout settings page /admin/store/settings/checkout (Home » Administration » Store » Configuration » Checkout) there is an checkbox 'Hide delivery information when carts have no shippable items.' Then, when you edit each product, the Product information vertical tab contains a checkbox 'Product is shippable.'
2. You can hide it completely on the Checkout settings page /admin/store/settings/checkout (Home » Administration » Store » Configuration » Checkout) there is a list of the panes available on the Checkout. If you uncheck 'Delivery information' and 'Delivery method' those panes will never appear.
If you are going to hide the Delivery information pane then the other option on the Checkout settings page 'Use the same address for billing and delivery by default.' would be useful too.
> 2 votes

---
Tags: 7, rules, ubercart
---


title: Make shipping optional ubercart

text:
# Question
Title: Make shipping optional ubercart
How to provide option for users to select whether to ship a product or not at time of chekout using ubercart in drupal ?

# Answer
Make a new flat rate shipping quote called 'No shipping' with zero cost. Then in the Delivery method pane at checkout the user can choose between your shipping option and your no shipping option.

You make shipping quotes at /admin/store/settings/quotes specifically the 'Add flat rate quote' link /admin/store/settings/quotes/methods/flatrate/add

Obviously you need both the ubercart shipping quotes module and ubercart fulfilment flat rate module enabled.
> 2 votes

---
Tags: 7, ubercart
---


# Question
Title: How to create a cronjob to update all nodes
I have a content type that has a computed field that needs to be updated constantly. So I need to create a cronjob to update all nodes of a certain type (example 'page'), so that the code is executed from the computed field and its value updated.

thx

# Answer
* You need to create a custom module to do this.
* Implement hook\_cron to create a cron job in custom module
* You can update a node programatically.. For more details see node\_save
> 2 votes

---
Tags: 7, cron, entities
---


# Question
Title: How to permit one sub admin to change passwords of other certain users?
I'ld like to make a sub admin be able to change other user's passwords depending on other user's role or uid.

The sub admin should be able to type the password by himself. Emailing a generated password is unfortunatley no optionn since the aimed user accounts will be used by a quite loose group of people (teachers and pupils, sub admin wants to change password every school year).

Until now there are only very few different accounts where that needs to happen. So can I maybe do that with uids?

Is it maybe possible to build a block that provides a form with password fields of the desired users? What hooks or forms would I need to use or alter then?

Any idea and/or explanation is very much appreciated!

# Answer
How about creating a custom block with content as a form.The form may have three fields password,confirm password and a select list of users for whom the sub admin wants to change the password.

How you will get users as options in the form?

* You have to narrow down "certain" word may with a user role,if so this link will be helpful in getting user by roles.Once you get them use uid as key and user name as value for select list option in the form.

How you will make this block accessible to sub admin only?

* I guess block access module can be helpful here.
* OR if you want to go for coding way you can define a permission using hook\_permission() and can then check permission using user\_access() inside hook\_block\_vew().

How to update the user password with this form?

* Your form submit handler will be picking uid of the selected user and password and then have to call user\_save() with required function parameters.You can cehck this link
> 1 votes

# Answer
Thanks to arpitr and my coworker J., I finally did it with a form on a page which is accessible only to selected roles via `hook_permission()`. The desired `array()` of `uid=>name` of that certain role to pass on as select list #option comes from `db_select()`, which definitely was the most difficult thing to get:

```
function _get_users_by_role($role_name) {
  $query = db_select('users', 'u')
    ->fields('u', array('uid', 'name'));

  $query->innerJoin('users_roles', 'ur', 'u.uid = ur.uid');
  $query->innerJoin('role', 'r', 'ur.rid = r.rid');
  $query->condition('r.name', $role_name);

  $result = $query->execute()->fetchAllKeyed();

  return ($result) ? $result : array();
}

```

For those interested in the custom block approach arpitr proposed, check the accepted answer on How can I display a change password form on its own? for a even more detailed description.
> 2 votes

# Answer
Take a look http://drupal-create-sub-administrators.blogspot.com/ .. this may meet your needs. Allows creation of sub-admins that can manage other lower level sub-admins or regular users including editing of user info (just like the user herself can).
> -1 votes

---
Tags: 7, users
---


# Question
Title: Workbench Access field cannot be used for access control
I have set up Workbench Access and Workbench Moderation and it is working in creating revisions for the Main Page Content section but when I go to add additional fields using the Workbench Access control field checkbox, I cannot enable the field and a message displays

> This field cannot be used for access control

How is it possible to allow a custom field to be added to access control? I've enabled the correct content type, set up vocabularies and set the Access control fields with the node reference field from the content type.

# Answer
The fields were enabled all along, the main issue was targeting the problem. Only my body field was displaying on the node draft. I had several other custom content fields in the node but they weren't displaying in the Draft. The site is built using Context and Views so was I had to do was clone Draft versions of those View Blocks and View Blocks. Setting that up can be a little confusing but I found good documentation here

Draft Revision Blocks
> 0 votes

---
Tags: nodes, workbench
---


# Question
Title: How to login by single role if user have multiple roles?
In my latest project client asked me to add extra interface after login where all roles assigned to that user will be shown and user can choose the single role and login by that role only. But i don't know how to do this in drupal. I tried with role switcher and other module but they didn't work for me ? Any suggestions will be appreciated.

Suppose User x have roles A B C D x can choose single role(eg A) after login and do the work only with that role.

# Answer
> 1 votes
* Create a custom module
* Create a custom form where Admin can whitelist users for certain roles .. Form should have username and roles as a list or checkboxes.
* Store these settings in database - uid - roles
* When a user logs in redirect user to a form where he can select user roles from above list
* On Form Submit, Update user programatically and assign role to the user he selected, remove other roles that user has if any

---
Tags: users
---


# Question
Title: Specify language of Comment using Entity Translation?
I'm building a site with multilingual support using Entity Translation. It is allowing authors to specify a language when creating a node, but there's no way to specify language when commenting on a node.

In Configuration \> Entity translation, the Comment item is checked in the Translatable Entity Types section.

In Structure \> Content Types \> Post, I see tabs for Comment Fields, and Comment Display, but language is not one of the options.

I have been looking into the form\_comment\_form\_alter hook, but so far have had no success with that.

In the Permissions panel, I confirmed that Administrator has "Translate entities of type Comment" checked. Even when editing a comment as admin, there is no option to translate.

The site uses Organic Groups 7.x-2.5, if that could influence this problem. The OG Post content type is the main one I'm trying to get fully functional.

# Answer
Drupal natural way would be to show comments for different languages separately.

For example If you have a node in English and Spanish. Drupal natural way would be to show comments for en/es translation separately (attached to en/es content).

If you are looking for language field you can use Language field module...

> This module creates a Language Field that combines Drupal 7's Field list options and Internal language list.
>
> This is used to simply collect language data.
> 1 votes

---
Tags: 7, organic-groups, comments, i18n-l10n
---


# Question
Title: How to properly name tpl file for webform-submission-navigation.tpl.php?
I am trying to theme the webform-submission-navigation.tpl.php template to add a link for a specific node but am having no success.

If I edit the main webform-submission-navigation.tpl.php file I can achieve what I require but for all of the webform nodes. What I want is to ONLY have this link for 1 specific webform (node 139).

What I have tried to do is name the file as follows, put them in the corresponding themes template folder and the reset cache but have no success:

webform--submission--navigation--139.tpl.php webform-submission-navigation--node--139.tpl.php

Am I naming my file incorrectly?

Thanks for any help!

# Answer
* Copy webform-submission-navigation.tpl.php to your active theme templates directory
* Clear Drupal Cache
* Add a php condition in above tpl to render your link only for node 139

Code you need to use in above tpl...

```
<?php
 if ($node->nid == 139) {
    print l('You Link Title', 'link/path');
 }
?>

```
> 0 votes

---
Tags: theming, webforms
---


title: retrive data from drupal not working

text:
# Question
Title: retrive data from drupal not working
**What I tried**

```
    $sql="select * from project_status where node_id=".$vid." and ".  strtolower($field_progress_flags)."!='' and ".  strtolower($field_progress_flags)." IS NOT NULL";
    $query=$sql;
    $array = array();
    $result = mysql_query($query);
    while ($object = mysql_fetch_array($result)) {
        $array[] = $object;
    }
    mysql_freeresult($result);
    echo "<pre>";
    print_r($array);

```

the actual sql query is `select * from project_status where node_id=385 and draft!='' and draft IS NOT NULL`

here am not getting any data what am doing wrong here?

# Answer
> 0 votes
After some R&D got the solution as follows:

```
$sql="select * from project_status where node_id=".$vid." and ".  strtolower($field_progress_flags)."!='' and ".  strtolower($field_progress_flags)." IS NOT NULL";
$result = db_query($sql);
while($record = $result->fetchAssoc()){
        $data[]=$record;
}

```

and its works for me

---
Tags: database
---


# Question
Title: Drupal views autocomplete filter inserts html tags
I have a site containing Free tagging field using text autocomplete widget option. A view is created with exposed filter for free tagging with autocomplete option. However the results provided via suggestions when entering a tag has html tags, in particular \< p \> tag.

Is there a way that the tags can be stripped off? Upon selecting the Unformatted dropdown and Unformatted suggestion in the filter option in views option, it displays the numeric id instead of text.

# Answer
> 0 votes
@MPD: Yes the problem was due to the formatter. The field format was set to Filtered HTML. Once I changed that to Plain Text in Views Exposed Filter settings for the autocomplete filter for the field, it worked. It was a simple change that I did not notice.

Thanks.

---
Tags: views, ajax
---


# Question
Title: Drupal Commerce File not issuing licenses
My store has been working perfect for the last year and a half. Yesterday I had to manualy add a license file for a user through Store\>File Licenses and clicking on the "Add a file license".

Since then every sale that has come through no file licenses has been allocated to them. When I look in the log file, it gives me this error: "Unable to evaluate action commerce\_file\_license\_issue\_order." .

When I go into the order under "LICENSE ORDER OPERATIONS" and I select " Sync to current product" and then press Create, it gives me the following error: "Licenses could not be updated or created for Little Lien. Check the logs for any errors that occurred." Then when I go and look in the logs, it gives me this error: "EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. in EntityMetadataWrapper-\>set() (line 122 of /home/embrojpq/public\_html/sites/all/modules/entity/includes/entity.wrapper.inc)."

I hope someone can help please!

Thank you

# Answer
I managed to fix the problem...after 20 sales have gone through without assigning any file licenses ;) Yesterday before everything went screwed up, I added the zip file extention under Store\>Configuration\>License Settings in the "Allowed file extentions" and then I also ticked the "LICENSED FILE FIELD SETTINGS" - "Number of values" to unlimited. That one settings stuffed everything up! When I changed the "Number of values" back to 1, I could go forth and asign the licenses to the purchases that weren't being assigned licenses without eny issues.
> 0 votes

---
Tags: commerce
---


# Question
Title: How allowing img tag in formats can be dangerous?
I get this recommendation form Security review module:

> It is recommended you remove the following tags from roles accessible by untrusted users: img

I am wondering what real world threats can img pose?

# Answer
Project page of security review module says

> Text formats don't allow dangerous tags (protecting against XSS)
>
> Cross-Site Scripting (XSS) attacks are a type of injection, in which malicious scripts are injected into otherwise benign and trusted web sites. XSS attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user. Flaws that allow these attacks to succeed are quite widespread and occur anywhere a web application uses input from a user within the output it generates without validating or encoding it.
>
> An attacker can use XSS to send a malicious script to an unsuspecting user. The end user’s browser has no way to know that the script should not be trusted, and will execute the script. Because it thinks the script came from a trusted source, the malicious script can access any cookies, session tokens, or other sensitive information retained by the browser and used with that site. These scripts can even rewrite the content of the HTML page.

For example you can use img tag as below for XSS attack..

```
<img src='#' onerror=alert(1) />

```
> 1 votes

---
Tags: 7, security
---


# Question
Title: entity Reference with select list doesn't show results
i'v created a content type with a entity reference field - select list. in the field settings i'v choose the desired content types for the select list. the preview select list was populated with all the wanted data. when i create a new content of the above content type the select list of the entity reference is not populated. the only option i have is -none-. any suggestions?

# Answer
Ok, the problem was due to the fact that the site has two languages. had to enable the second language in order to make the it work properly.
> 1 votes

---
Tags: 7, entities
---


# Question
Title: How safely allow untrusted users to use img tag?
Following this question, I'm wondering how can I allow users of a social site (which obviously are not all trusted) to upload images while avoiding XSS threats?

# Answer
> 4 votes
The default "Filtered HTML" text filter that ships with Drupal do not allow the `<img>` tag because image tags can contain attributes that allow for XSS attacks.

If you want to allow images, but also want to prevent untrusted users from using images as a vector for XSS attacks, you need to install and enable the WYSIWYG Filter and configure it to allow images, but disallow all unsafe image attributes. You use this filter *instead* of the "Filtered HTML" text filter, not in addition to it.

To create a new text format, navigate to *Configuration → Content authoring → Text format* and click on *Add text format*. Select a name for the format (e.g. call it «Wysiwyg»). Enable it for all user roles. Below, I am going to show you how to fine tune the attributes allowed for this text format. It may be a good idea to also enable the filters Convert URLs into links and Correct faulty and chopped off HTML.

If you use all three filters, make sure the filter processing order is the following:

1. WYSIWYG Filter
2. Convert URLs into links
3. Correct faulty and chopped off HTML

Now configure the WYSYWYG filter:

To make sure that no insecure markup emerges from your editor, you must create a white-list for the Wysiwyg text format. My recommended white-list for HTML elements and attributes is below:

```
a[!href|target<_blank|title],
div[align<center?justify?left?right],
p[align<center?justify?left?right],
img[src|alt|title|width|height], @[class|style],
h2,h3,h4,h5,h6,
br,span,em,i,strong,b,
u,s,strike,
blockquote,pre,address,sub,sup,
ul,ol,li,hr,br,
table,tbody,caption,tr,td

```

Creating a white-list of HTML elements and attributes and inserting it into the HTML elements and attributes in the Filter settings for the WYSIWYG Filter is not sufficient. You also need to whitelist the properties that is going to be allowed. By default, all properties are disallowed. To allow images and text to be styled and scaled, check the following properties:

The screen shot above shows (the part of) the WYSIWYG filter configuration screen with tick boxes that allows the `img` attributes it is safe to allow untrusted users to use.

Disallow *all other* attributes. Attributes that is disallowed will be stripped from the renderable version of the entity by the filter when the entity is saved after editing.

The screen dump below show the entire configuration screen I've used for *my* setup of the WYSIWYG filter.The text is too tiny to be readable, but I hope it gives you a rough idea about of it is configured.

After configuring the WYSIWYG filter, press *Save configuration*.

After creating the Wysiwyg text format, allow non-trusted users to access it, and make it the default by moving it to the top of the list of text formats, as shown in the screen shot below.

---
Tags: media, security
---


# Question
Title: Add t('String to be translated') to your database
I've altered a form where I set the save button text to `t("Buy Product")`;

But how can I make sure that I can translate this string in **admin/config/region/translate/translate** ?

I've tried to add this

```
$conf['locale_custom_strings_en'][''] = array(
 'Buy Product' => 'Koop Product',
);

```

to my settings.php but no result. How can I make sure the string in my code can be translated in drupal itself?

# Answer
Every single string passed to `t($string)` function will be added to the database, and you can find it in the path you montioned above `"admin/config/regional/translate/translate"`

clear the cache, and search it again with help of filters existing on the admin translate page.

**\[EDIT\]**

First of all a must have module in multilangual sites is the internationalization module, it's a powerfull and helpfull module...

**But the most important thing in your case** is that before you can see your string in the transltion page:

1. you must enable(switch to) the desired language
2. visit the page that contain that needle string
3. visit again the translation interface.

That's it you will find your string ;)
> 1 votes

---
Tags: i18n-l10n
---


# Question
Title: Change from address of user registration email
How can I update the from address of the email sent when a user successfully registers to the website. Currently the from address is same as the site administrator email id. Instead I would like to set it some custom email id like do-not-reply@example.com.

I looked at the Mail editor module and from the documentation I understand that it can be used only for updating the subject and body of the email and not the from address.

Any thoughts??

# Answer
There is one e-mail address that is used as From-address for *all* mails sent automatically by the system. By default, this is set to the *same* as the site administrator email. To change it, do the following:

1. Navigate to *Administration » Configuration » System » Site Information*.
2. Locate the field "E-mail address". Change it to whatever you want it to be.
3. Press *Save configuration*.

Note that will also be used as the From-adress for password resets and other generated mail.

If you require fine-tuning beyond this (to distinguish between different types of auto-generated email messages), you need to write a custom module. In that case, you may use `hook_mail_alter` to alter the From:-address, based upon some criteria (e.g. the subject field.

For avoidance of misunderstanding: The three steps listed above will *not* change the site administrator email id. To inspect and change the site administrator email id, click on the "My account" link while logged in as site admin, and then press the *Edit* tab to see it. The site administrator email id is by *default* the same email id as the From-address used for email sent by the site itself - but they do not need to be the same.
> 1 votes

---
Tags: 7, users, emails
---


# Question
Title: Running into deadlock when using XDebug with Drush
For most of the Drush commands it is not too difficult to get XDebug and Drush working togethr and catch staff in your IDE, e.g. PhpStorm.

However, I ran into a deadlock when Drush is calling itself for a sub-process. This happens e.g. if you execute `drush @site updatedb` because this will invoke a second PHP task for the cache-clear all command. This second PHP task wants to connect to the Xdebug port as well which is still in use by the parent PHP task. This results in a deadlock: the child is waiting for the XDebug port to become available and the parent task is waiting for the child task - for ever or until Ctrl-C.

Is there a way around this?

# Answer
> 5 votes
In PhpStorm at least, under File \>\> Settings \>\> PHP \>\> Debug you can find `Max. simultaneous connections` and crank it up. I typically keep it at 8 but probably 3 is enough.

---
Tags: drush
---


# Question
Title: Saving the content from a Textarea dont works
An **Textfield** within my **Custom Content Pane** works fine.

An **Textarea** incl. input-filter ('#type' =\> 'text\_format',) will not be saved.

```
<?php
  function text_edit_form($form, &$form_state) {
      $conf = $form_state['conf'];

      $form['form_text'] = array(
        '#type' => 'text_format',
        '#title' => t('Text'),
        '#format' => 'filtered_html',
        '#size' => 50,
        '#resizeable' => TRUE,
        '#default_value' => !empty($conf['form_text']) ? $conf['form_text'] : '',
      );

      return $form;
    }
  function text_edit_form_submit($form, &$form_state) {
    foreach (array('form_text') as $key) {
      $form_state['conf'][$key] = $form_state['values'][$key];
    }
  }
?>

```

At drupal.com somebody wrotes, that #default\_value expect and string, but text\_format is an array. So he postet the following solution.

But how can I build that within my hook\_edit\_form?

```
<?php
      // Retrieve the default values for 'value' and 'format', if not readily
      // available through other means:
      $defaults = array(
        'value' => '',
        'format' => filter_default_format(),
      );
      $my_richtext_field = variable_get('my_richtext_field', $defaults);
      // Just construct a regular #type 'text_format' form element:
      $form['my_richtext_field'] = array(
        '#type' => 'text_format',
        '#title' => t('My richtext field'),
        '#default_value' => $my_richtext_field['value'],
        '#format' => $my_richtext_field['format'],
      );
 ?>

```

Who can help me with that?

# Answer
Solved!

I just rebuild the save-stuff:

```
<?php
function text_edit_form_submit($form, &$form_state) {
  $form_state['conf']['form_text'] = $form_state['values']['form_text']['value'];
}
?>

```
> 2 votes

---
Tags: panels, input-formats
---


# Question
Title: How to use the "Render Views filters as select list" option in an Entity Reference field?
I have a content type Trait, that includes an Entity Reference field Trait Type. A trait type is categorized under a Trait Category. For my Trait content type form I created an Entity Reference View for as follows:

As (if) you can see, I have included a contextual filter that takes Trait Category id values. I've also added a relationship for Trait Type and Trait Category.

The view works as expected, when I enter trait category id values I'm able to filter related trait types.

My difficulty comes when my I want to use this view as my datasource for a Entity Reference field (Trait Types List) I want to add to my Trait content type form.In the field settings field for the Triat Types Entity Reference Field I've done the follow:

Now what I can't understand is:

1. What **View Arguments** is supposed to take and do I need to give it any value?
2. Shouldn't the option "Render Views Filter as a select List" a new select widget to my Trait content type form that would allow me to filter my Trait Type Entity Reference select widget?

Something like this perhaps:

Is my expectation wrong? How can I use this option?

# Answer
**1.** "Entity selection Views" helps you to deal with options list in the entity reference widget (on node add/edit form). E.g. if you want to reference some nodes that have specific term reference. Entity reference view can help you you.

As I see you want to reference "child" Trait nodes of special category to one "parent" Trait node. (At list your View shows it). In this case you don't have to use contextual filter. You can use ordinary "filter criteria" and set target category value.

**2.** "Render Views Filter as a select List" - it's not a widget for your content type add/edit form. But it's a widget for exposed filter in views. If you want to use this field as an exposed filter in views by default it's an autocomplete. But this option makes filter as select widget. If you read the "Render Views Filter as a select List" description, you might see that developers advice you not to use this option if you have more that 100 referenced entities. Just imagine a select widget with 100 options and query with WHERE condition. Just mind it.
> 5 votes

---
Tags: views, entities
---


# Question
Title: Show custom query page based on user logged in
I want to make a customized query page based on the user who is logged in. The query page is a node made in custom made content type "query"(this content type has no additional fields than which are created in a new default content type)

I have a `<p id = my_para>` tag in my node. I call an external query.js script in my node which uses xmlHTTPRequest to call an external query.php. This php connects with mysql and does a query like

```
select * from my_table where user = "logged-in-user";

```

and returns the query result using `json_encode` back to `query.js`. The `query.js` parses json and displays it on my node using `document.getElementById("my_para").innerHTML = my_parsed_json_variable`

So I some how want to get the logged in user details(there can be many logged in users to mysite at the same time) so that each user can see a custom page through these scripts.

How can I get the user details in my external query.php ? I tried using these in my query.php

```
global $user;
$name = $user->name;
$id = $user->uid;

```

But it gives

> Trying to get property of non-object in C:\xampp\htdocs\mywebsite\sites\all\themes\danland\query.php

# Answer
If your page is being created via code, then you can check the role of the user via code and not display the filters you want.

Otherwise, you may want to create different query pages for different roles and enable the right page for the right role using a module that restricts access such as the 'node access' module.
> 1 votes

---
Tags: users, database, cookies
---


title: Listing and Loading Nodes with AJAX

text:
# Question
Title: Listing and Loading Nodes with AJAX
In Drupal 7
I want to make a view of

```
/------------------------
--------- Header --------
List of links to nodes

/-------------
Node content

```

When the links of nodes in Header clicked, the node content should be loaded by ajax.
Is there anyway to do this by Views? or do I need some custom PHP?

# Answer
> 0 votes
First off if the content is only text and its size is not very big I recommend you strongly not to use Ajax , unless you can do it using views in the following way:

Be sure to enable the Ajax in views:

now this code will load the view.

```
$("links_click").click(function(){
            $.ajax({
                url: Drupal.settings.basePath + 'views/ajax',
                type: 'POST',
                dataType: 'json',
                data: 'view_name='+your_view&'view_display_id='+view_display_id,
                success: function(response) {
                  var output = response[1].data;
                  $(".your_container").html(output);
                },
                error: function(data) {
                    alert('An error occured!');
                }
              });
        });

```

for more detail visit this link.

---
Tags: nodes, ajax
---


title: Extending form validation functions

text:
# Question
Title: Extending form validation functions
How do I pass additional values to #element\_validate so they can be used for validation?

I'm using hook\_form\_alter() and Drupal 7.

```
//Example 1
function my_validation_function($form, &$form_state) {
    //Validation Code
}

```

I would like to use:

```
//Example 2
function my_validation_function($form, &$form_state, $additional_values) {
    //Validation Code with access to $additional_values
}

```

This works for example 1:

```
$form['field']['#element_validate'] = array('my_validation_function');

```

How do I pass `$additional_values` to example 2 using `$form['field']['#element_validate']`

# Answer
```
function where_ever_extra_data_originates_from() {
  $extra_data_to_pass_on_stored_here = &drupal_static(__FUNCTION__);
  $extra_data_to_pass_on_stored_here = $actual_extra_data
}

function my_validation_function($form, &$form_state) {
  //Here's our extra stuff now
  $extra_data = &drupal_static(where_ever_extra_data_originates_from);
}

```
> 4 votes

# Answer
You can add whatever extra elements to the $form\_state array in your alter function and read them out in the validate function, like so:

```
function my_form_alter(&$form, &$form_state, $form_id) {
  $form_state['additional_value'] = 'the extra value';
  $form['#validate'][] = 'my_validation_function';
}

function my_validation_function($form, &$form_state) {
  //Validation Code
  $extra = $form_state['additional_value']
}

```
> 0 votes

# Answer
You can't alter(add to) the number of parameters that are passed to a hook function. You could declare the variable that you want passed into the function as "global" -\> Variable scope when you define it and again in the function which would give you access to the value.
> -1 votes

---
Tags: 7, forms
---


# Question
Title: How to use union with a query of view itself?
I have a table that have 2 types of data:

* first type is '1'
* second type is '2'

And I want to get 3 records of both by union so, I want to know that how to get 3 records of both types from one table at a time so it is possible by union with itself so i want to add union with my views content.

How to get query of view and alter it and where I put this query in Drupal 7 but I have no one module for this data.

# Answer
> 1 votes
You can look here (https://drupal.org/node/409808) for information on creating custom sql statements in a View.

---
Tags: views
---


# Question
Title: How to programmatically remove a field from a node?
How does one remove a field from a node programmatically? I have a migration in `hook_update_N` that moves the contents from a a field into a custom table. After that migration, I want to remove the field in that same function.

Are there any field API's that cater removing fields?

**Edit, Solution**: Because the answers lack actual code, here is what I did to move fields from the $users into my own records and subsequently remove the field from the database;

```
function my_module_update_7005(&$sandbox) {
  $slice = 100;
  //Fetch users from database;
  if (!isset($sandbox['progress'])) {
    $sandbox['progress'] = 0;
    $sandbox['current_uid'] = 0;
    // We'll -1 to disregard the uid 0...
    $sandbox['max'] = db_query('SELECT COUNT(DISTINCT uid) FROM {users}')->fetchField() - 1;
  }
  if (empty($users)) {
    $sandbox["current_uid"] += $slice;
  }
  $users = db_select('users', 'u')
    ->fields('u', array('uid', 'name'))
    ->condition('uid', $sandbox['current_uid'], '>')
    ->range(0, $slice)
    ->orderBy('uid', 'ASC')
    ->execute();
  //Loop trough users;
  foreach ($users as $user) {
    $foo = new Foo();
    // Warning: drupal's fields return mixed values; e.g. NULL versus an int.
    $foo->debits = (int) $user->user()->field_credits["und"][0]["value"];
    $foo->save();

    $sandbox['progress']++;
    $sandbox['current_uid'] = $user->uid;
  }

  $sandbox['#finished'] = empty($sandbox['max']) ? 1 : ($sandbox['progress'] / $sandbox['max']);

  // Remove the field.
  field_delete_field("field_credits"); //note that the name for Foo is field_foo
  field_purge_batch($sandbox['max']+1);//Drupal seems to have an offbyone problem.
}

```

# Answer
> 29 votes
`field_delete_field($field_name)` will mark the `$field_name` for deletion on next cron run.

You could use `field_purge_batch` to do the deletion, if you don't want to do it on cron run.

**EDIT:** `field_delete_field()` should be used when you need to delete the field from other bundles as well. If you only wish to delete the field from a particular bundle you should use `field_delete_instance()` as mentioned by @Clive.

# Answer
> 24 votes
To remove a field from a particular bundle you can use `field_delete_instance()`

> Marks a field instance and its data for deletion.

Example:

```
function my_module_update_7001() {
  if ($instance = field_info_instance('node', 'field_name', 'page'))  {
    field_delete_instance($instance, TRUE);
    field_purge_batch(1);
  }
}

```

To remove a field from the system completely, you can use `field_delete_field()`

> Marks a field and its instances and data for deletion.

Example:

```
function my_module_update_7001() {
  field_delete_field('field_name');
  field_purge_batch(1);
}

```

The fields/instances are only marked for deletion, the data will actually be purged during subsequent cron runs. To purged it manually execute:

```
field_purge_batch(1);

```

# Answer
> 5 votes
To answer @berkes question:

`field_delete_field()` does mark the field for deletion, causing it to get purged on the next cron run. However *it does* leave data on `field_config_instance` regarding the dropped field. Running cron or `field_purge_batch()` will not remove this data from `field_config_instance` table, even if the deleted column is set to `1` for the field.

For me using `field_delete_instance()` followed by a `field_purge_batch()` for each purged field worked - instantly removing both the field from the database (without requiring cron), as well as purging the `field_config_instance` table of any field data (for the deleted field).

Here is the solution:

```
/**
 * Implements hook_uninstall().
 */
function hook_uninstall() {
  // Delete all fields for all xyz entity bundles.

  // Retrieve all bundles for an entity.
  $bundles = field_info_bundles('XYZ'); // The name of your entity type, for example, 'node'.
  foreach ($bundles as $bundle => $properties) {

    // Retrieve all the fields for a given bundle.
    $instances = field_info_instances('XYZ', $bundle);
    foreach ($instances as $instance) {
      field_delete_instance($instance, TRUE);
      field_purge_batch(1);
    }
  }
}

```

Do note the `TRUE` on `field_delete_instance()`, as it indicates that the Field API should perform cleanup operations.

---
Tags: 7, entities, updating
---


# Question
Title: How and when to use filter_xss() and check_plain()?
There are lots of template files like this one `views-view-fields--magazine--magazine.tpl.php` in my website. how and when I should use the filter\_xss() and check\_plain() to improve security? for example this is the code:

```
<div>
    <div class="bf-header bf-article-header"><?php print $fields['title']->content; ?></div>
    <div class="bf-article-body"><?php print $fields['field_magazine_body']->content;?></div>
    <div class="bf-article-image"><?php print $fields['field_magazine_image']->content;?></div>
</div>
<div class="separator article-view-separator"></div>

```

How do I can apply those functions in it?

# Answer
First, read up about these in the Drupal API:

So `check_plain()` encodes special characters that has special meaning in HTML (such as `<` and `&`) into plain text entities (i.e. `<` and `&` respectively) that will make these be rendered literally (not interpreted as HTML) when that string that is then displayed as part of a page with HTML-markup. The function `filter_xss()` filters an HTML string to prevent cross-site-scripting (XSS) vulnerabilities. It does four things:

* Removing characters and constructs that can trick browsers
* Making sure all HTML entities are well-formed
* Making sure all HTML tags and attributes are well-formed
* Making sure no HTML tags contain URLs with a disallowed protocol (e.g. javascript:)

Both functions are used to sanitize data from users to make sure that any user injection is neutralized before the data is *rendered* on your site.

You never pass the *same string* through *both*.

If you use `check_plain()` then the string passed to the function is supposed to be used as *plain text* (not HTML). Then `filter_xss()` is not needed, since `check_plain()` will always make the string plain text.

If you use `filter_xss()`, then the string passed to the function is supposed to be HTML, and `check_plain()` will mess it up.

When I look at the template you use as example, it looks to me as if all three fields passed to `print()` comes from content that is already sanitized, and need no more sanitation.

However, if you create your *own module* that collects user input without passing it through a "safe" text filter such as "Filtered HTML" or "Plain", you must use these functions for sanitation purposes.
> 13 votes

---
Tags: security
---


# Question
Title: db_query() and db_select() don't return any value
I'm trying to run the following query.

```
SELECT floormap_counter_expected.counter_name, tls_connect_agent_counters.counter_stage,tls_connect_agent_counters.applicant_gwf, tls_connect_agent_counters.counter_ip, floormap_counter_expected.expected FROM tls_connect_agent_counters INNER JOIN floormap_counter_expected ON floormap_counter_expected.counter_name = tls_connect_agent_counters.counter_name;

```

When executed via the command line, MYSQL returns the information I need.

When I try the following code, I get an error saying that `$center_counters` is not set.

```
$get_counter_info = db_select('tls_connect_agent_counters', 't');
$get_counter_info->fields('t', array('counter_stage', 'applicant_gwf', 'counter_ip'));
$get_counter_info->fields('n', array('expected'));
$get_counter_info->join('floormap_counter_expected', 'n', 't.counter_name = n.counter_name');
$get_counter_info->execute()->fetchAll();
if (isset($get_counter_info)) {
  foreach ($get_counter_info as $results) {
    echo "Rest";
    $center_counters[$results->counter_name]['stage'] = $results->counter_stage;
    $center_counters[$results->counter_name]['counter_ip'] = $results->counter_ip;
    $i++;
  }
}
return $center_counters;

```

The same happens with the following code.

```
$counters_query = "SELECT floormap_counter_expected.counter_name, tls_connect_agent_counters.counter_stage,";
$counters_query .= "tls_connect_agent_counters.applicant_gwf, tls_connect_agent_counters.counter_ip, ";
$counters_query .= "floormap_counter_expected.expected FROM tls_connect_agent_counters INNER JOIN ";
$counters_query .= "floormap_counter_expected ON floormap_counter_expected.counter_name = tls_connect_agent_counters.counter_name";
$get_counter_info = db_query($counters_query);
$get_counter_info->fetchAll();
if (isset($get_counter_info)) {
  foreach ($get_counter_info as $results) {
    echo "Rest";
    $center_counters[$results->counter_name]['stage'] = $results->counter_stage;
    $center_counters[$results->counter_name]['counter_ip'] = $results->counter_ip;
    $i++;
  }
}
return $center_counters;

```

I tried wrapping the code with `try{} catch(Exception $e) {echo $e-getMessage()}`, but nothing is printed.

I assume the query is running without error because nothing is "caught".

I was thinking that maybe I'm just calling the information wrong in my foreach loop. Maybe I should identify the table name as well when I call the field name. I don't think that is the case as nothing is printed when I try to echo strings out of `foreach`.

# Answer
```
$get_counter_info->execute()->fetchAll();

```

will execute the query...but what are you doing with the results, exactly? At the moment you're discarding them, instead you need to assign them to a variable.

```
$results = $get_counter_info->execute()->fetchAll();
foreach ($results as $result) {
  ...
}

```

Or at the very least actually *use* the return value from the execution:

```
foreach ($get_counter_info->execute()->fetchAll() as $result) {
  ...
}

```
> 0 votes

---
Tags: database
---


# Question
Title: Can I use lightbox for displaying pop up biographies?
I want to achieve this effect. When user clicks on (thumb) image, biography and image should pop up. Can I do this with lightbox, and if answer is yes, how to customize it? Also, is there some other module that is good for this purpose? I am using Drupal 7. Thanks in advance.

# Answer
> 0 votes
You might be able to do this by adding your content as the alt text caption and manipulating the lightbox display with css.

Alternatively this question may help: load a node content into a lightbox2 (without headers and footer and other blocks)

---
Tags: 7, javascript
---


# Question
Title: Permission to edit a node by multiple users
Suppose there is one node (Like `node/4`) which the Admin can edit. My requirement is to give permission to multiple users to edit the same node i.e. `node/4`. Please help how to accomplish this task.

# Answer
> 1 votes
The Nodeaccess module might also help:

> Nodeaccess is a Drupal access control module which provides view, edit and delete access to nodes. Users with the 'grant node permissions' permission will have a grant tab on node pages which allows them to grant access to that node by user or role. Administrators can set default access controls per content type, and also define which roles are available to grant permissions to on the node grants tab.

# Answer
> 0 votes
The best option is to install a node access module that allow the admin to:

1. Create access control lists (ACLs) to individual nodes; and
2. Add and remove individual users from an ACL.

The module named Flexi Access lets you do exactly that.

> The Flexi Access module will provide a simple and flexible interface to the ACL (Access Control List) module. It will let you set up and mange ACLs naming individual users that are allowed access to a particular node.
>
> The module let you manage access to individual nodes. The administrator may grant individual users the right to: View (read), update (edit/write), and delete the node.

It depends on the ACL module. (It actually provides an administrative interface to ACL.)

Disclosure: I am one of the maintainers of Flexi Access.

---
Tags: 7, nodes
---


# Question
Title: How do I import a csv-file into a table via Drupal?
I would like to import a csv into a table via Drupal. I use Drupal 7.

I create a content type 'Import', which contains a File field to upload a file to the server (destination: sites / default / files / import / \*)

When I validate my form content 'Import', I will wish to make a db\_query ()

```
db_query ("
LOAD DATA INFILE '$ csv_filename' INTO TABLE $ temp_table
FIELDS TERMINATED BY ';' OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\\n'
IGNORE 1 LINES ");

```

$ csv\_filename, I test the relative and absolute way, but drupal tells me it can not find the file. I even give the rights to the file to test 777 but it is not ca.

$ temp\_table is my table, it already exists in the database.

You would know the procedure and a use case that works for this query?

# Answer
> 2 votes
I don't know if this quite what you're looking for, but the Feeds module can import CSV content into nodes. Perhaps it could help...

> Import or aggregate data as nodes, users, taxonomy terms or simple database records.
>
> * One-off imports and periodic aggregation of content
> * Import or aggregate RSS/Atom feeds
> * Import or aggregate CSV files
> * Import or aggregate OPML files
> * PubSubHubbub support
> * Create nodes, users, taxonomy terms or simple database records from import
> * Extensible to import any other kind of content
> * Granular mapping of input elements to Drupal content elements
> * Exportable configurations
> * Batched import for large files

---
Tags: importing-exporting, database
---


title: The fieldset isn't shown as collapsed

text:
# Question
Title: The fieldset isn't shown as collapsed
I am writing a module that executes some queries, and returns the result in to a collapsed fieldset which is not shown as collapsed; I view its content. The collapse.js files are loaded.

This is the code I am using.

```
$body = $body . '<fieldset class="collapsible collapsed">' .
  '<legend class="gestioneinterna">Viste aggiuntive</legend>' .
  '<description class="description">fieldset extra.</description>' .
  '<div><p class="home_body "><a href="?q=vista_progetti_categoria/1"><strong>Vista progetti</strong></a></p></div>';
print $body;

```

# Answer
> 5 votes
You're missing a closing `</fieldset>` tag which probably won't be helping things, but I wouldn't advise doing it the way you currently are anyway.

A better way would be to make use of the `theme_fieldset()` function like so:

```
// Make sure the collapsible library is loaded
drupal_add_library('system', 'drupal.collapse');

// Build up the fieldset
$fieldset = array(
  '#theme' => 'fieldset',
  '#title' => 'Viste aggiuntive',
  '#attributes' => array('class' => array('collapsible', 'collapsed')),
  '#description' => 'fieldset extra.',
  '#children' => '<div><p class="home_body "><a href="?q=vista_progetti_categoria/1"><strong>Vista progetti</strong></a></p></div></fieldset>'
);

// Add it to the body
$body .= render($fieldset);

```

That works great for me.

You might want to replace the call to `render()` above with `drupal_render()` as it offers a minute performance increase; I tend to use `render()` for all my calls for this sort of thing for continuity, and so that I don't have to check the type of the data being passed.

In this case, as you know the argument is not a string, you could save yourself the few microseconds and use `drupal_render()` instead.

# Answer
> 2 votes
I used the following code for a quick test in a page callback, and it worked.

```
  drupal_add_js('misc/form.js');
  drupal_add_js('misc/collapse.js');

  $fieldset = array(
    '#attributes' => array(
      'class' => array('collapsible', 'collapsed'),
    ),
    '#title' => 'Viste aggiuntive',
    '#description' => 'fieldset extra.',
    '#children' => '<div><p class="home_body">' . l('<strong>Vista progetti</strong>', 'vista_progetti_categoria/1', array('html' => TRUE)) . '</p></div>',
  );

  return theme('fieldset', array('element' => $fieldset));

```

To notice that collapse.js needs form.js to work.
To be sure both the files are loaded, you can use `drupal_add_js()`; if the files are already added from a previous call to `drupal_add_js()`, they will not be added twice. Alternatively, you can replace those calls to `drupal_add_js()` with a call to drupal\_add\_library('system', 'drupal.collapse'). The code I wrote was written for a quick test just to verify I would have the same issue, but in general is preferable to call `drupal_add_library()` when there is a module that defines a specific library with hook\_library(), for the fact `drupal_add_library()` loads all the dependencies (in this case, it would actually load both misc/collapse.js, and misc/form.js) without you know them beforehand. For a list of all the libraries defined from Drupal, see system\_library() (mainly), and overlay\_library() (secondarily); if one of the JavaScript files you need is listed there, it would be better to use `drupal_add_library()`.

Apart from the `<fieldset>` tag not being closed in your code, the other problem could be:

* The code doesn't use all the CSS classes the code in the collapse.js file depends upon. When I look at the HTML output from my code, I see the following. (I reformatted the code to make the single parts more evident.)

```
<fieldset class="collapsible form-wrapper collapse-processed">
  <legend>
    <span class="fieldset-legend">
      <a class="fieldset-title" href="#"><span class="fieldset-legend-prefix element-invisible">Hide</span> Viste aggiuntive</a>
      <span class="summary"></span>
    </span>
  </legend>
  <div class="fieldset-wrapper" style="">
    <div class="fieldset-description">fieldset extra.</div>
    <div>
      <p class="home_body"><a href="/dr72/vista_progetti_categoria/1"><strong>Vista progetti</strong></a></p>
    </div>
  </div>
</fieldset>

```
* The form.js code is not loaded from the page you are outputting. This is could be the case, if you just added `drupal_add_js('misc/collapse.js')` to include the collapse.js file, or there is another module that used `drupal_add_js('misc/collapse.js')` without to use `drupal_add_js('misc/form.js')`.

As side note, when creating HTML output, it is better to use the functions Drupal provides; in this case, I used theme\_fieldset(), and l().
`l()`, in particular, outputs the correct URL. If you run the same code on a different server, such as one running on Windows, the URL would be always correct. That is also true when you move Drupal on a subdirectory of the root directory (which, in my case, is dr72); if you were to write the URL as you did, you would need to change the code you wrote (in the cases I reported), while using `l()` the code would not need to be changed. The same is true for url(), which is the function used by `l()`.

# Answer
> 0 votes
Just as a reference for people looking for simple Drupal fieldsets for their content - use render arrays! So much simpler & much cleaner to read.

The following snippet is a page callback function, that builds a fieldset that has a table inside it, with some sample data.

```
function mypage() {
  $build['myfieldset'] = array(
    'fieldset' => array(
      '#type' => 'fieldset',
      '#title' => t('Fieldset legend'),
      '#attributes' => array('class' => array('collapsible', 'collapsed')),
      'content' => array(
        '#theme' => 'table',
        '#header' => array('Col1','Col2','Col3'),
        '#rows' => array(
          array('Data 1-1','Data 1-2','Data 1-3'),
          array('Data 2-1','Data 2-2','Data 2-3'),
          array('Data 3-1','Data 3-2','Data 3-3'),
        ),
        '#empty' => t('No RFMs in this state'),
       ),
     ),
     '#attached' => array('js' => array('misc/collapse.js', 'misc/form.js')),
   );
   return $build;
 }

```

---
Tags: javascript, forms
---


# Question
Title: How to block the user after a few failed logins
modules like login security deny the user IP after afew failed logins. there are softwares that randomly generate new IP for user so it makes such modules useless. sending cookie to the user browser is also unreliable because the user can disable accepting cookie. What is the most reliable solution to block some users?

# Answer
> 0 votes
Rules is what comes to mind. You can react to the user logging in I guess.

---
Tags: users, security
---


# Question
Title: How to allow user picture during registration?
I have the Avatar Selection module and the Register with Picture module installed.

But I can't get the file chooser to show up on the registration page.

What would be the problem?

# Answer
You should be able to use the Register with Picture module.

I've never experience any problem with this module.

You install it and configure it, and it does what it is supposed to do.

> This module exposes the 'upload picture' element to the registration form. It also gives you the ability to set a picture as required in the module settings.

You will be given a check box at *admin/config/people/accounts* named "Enable user pictures on registration" and weight selection. Make sure you also check "Enable user pictures".

This is how it should look like when a new user tries to register:
> 2 votes

---
Tags: 7, media
---


# Question
Title: Adding custom classes to Views Filters (view-filters) and Content (div.view-contents)
I'm using a theme that includes bootstrap. I'd like to inject class `one_third` into `<div class="view-filters">` and `two_third last` to `<div class="view-content">`. Is there a way to do so from any theme `theme_preprocess_area`?

I know I could accomplish using javascript (selecting `div.view-filters` and `addClass()`), but I think it would be most prudent to handle in perhaps the preprocessing?

# Answer
> 2 votes
Views provides a lot of .tpl files for doing just this. They are found in the `/theme` folder of the `views` module folder. The one you want is `views-view.tpl.php`

Simply copy `views-view.tpl.php` into your theme's templates folder and edit ~ line 43 to include your bootstrap classes and whatever other markup you require ;)

---
Tags: views, bootstrapping
---


title: Broken Admin Menu, How Can I Repair It?

text:
# Question
Title: Broken Admin Menu, How Can I Repair It?
A while back I upgraded from D6 to D7 using the Drupal upgrade script. A bug that's lingered in my system is broken menus.

For example, on /admin I have a link for both "People" (/admin/people) and "User management" (/admin/user). The link for "User management" is dead, it goes to /admin, and I believe it is a carryover from the D6 install. I can give many more examples if necessary.

Is there a way to remove the broken menu items without affecting my working D7 menu items?

Thanks in advance to anyone that helps!

# Answer
Unfortunately—and this is not an ideal solution, but seems to be what everyone is using successfully—I have had to use the following brute-force SQL statement in the past.

First, backup your entire Drupal database!

Then, execute this in your favorite SQL manager:

```
DELETE FROM menu_links WHERE module = 'system';

```

Then visit /admin/config/development/performance and clear the cache.
> 2 votes

---
Tags: routes
---


# Question
Title: Is there a simple boolean formatter that allows custom content?
I have a boolean field that stores 0 or 1. I'd like a formatter that lets me enter custom markup to display on 0, and different content to display on 1. I'm happy enough doing this in code, just thought I might be reinventing the wheel if I did.

# Answer
You can give a try to custom\_formatters in Drupal, this module allows you to do things without writing a code
> 1 votes

# Answer
Using Boolean Field it allows you to define label for On value using "Use label as On value label" check box as shown in below screen. But, only issue is you cannot define the off value label.

You can use list (integer) type field to achieve the same functionality by selecting widget types as check-box/radio-buttons. In the allowed options you can set Key|Label pairs easily. That should work!
> 1 votes

# Answer
~~Not directly related, as it **wont allow users** to display **custom html**, but it's good enough for some cases (and saves you writing a module!).~~ My bad! it supports custom output.

boolean\_formatter has several nice *formatters* for *boolean fields*, check it on modules page.

It behaves like views's boolean formatter which can be used for psudo fields such as is *node sticky* or is *published* but not with Field API boolean fields :|
> 0 votes

---
Tags: entities
---


title: How to add Product image field to view

text:
# Question
Title: How to add Product image field to view
I'm not sure how much sense this makes as I've confused myself so much trying to do this.

I'm using Drupal 7.28 and the Drupal Commerce 7.x-1.9.

Basically the image and the description fields are both on the Product Type not the content type as each product has its own description and image.

In my view I now need to add the image field, but I can't add it, which I believe is because the field isn't in the content type.

When I add the 'Content: Referenced Products' relationship to the view, I am then able to add the image field to my view.

However when I then select to link this image field to the original content, the field links to the admin page where I edit the product - not the content type node that is displaying the product.

Also, after adding the image field, the view lists the image for every single product variation whereas I just need one image that links to the node.

# Answer
> 2 votes
This drives me nuts in Drupal Commerce. Now that you have the relationship, add a field to your view `Content:Path` using the relationship and tick boxes for `Exclude from display` then go to `Rewrite results` and tick the box next to `Use absolute link (begins with "http://")`. Move this field so that it appears above your image field. Then, in your image field, `Link image to [Nothing]` and under `Rewrite results` tick `Output this field as a link` and under `Link path` enter the token for your `path`.

Good luck.

---
Tags: views, commerce, entities
---