title: batch api for large batches

text:
# Question
Title: batch api for large batches
After a form submit, can I create multiple batches based on the maximum table size for the serialized batch string and how can this be done?

I am using a batch process to pass users to an external site using their API.

For each user I set `$batch['operations'][] = array('process_funcion', array(LIST OF VARIABLES));`

The batch processing works for upto 5000 users; anything over that I get the following error:

> Access denied
> You are not authorized to access this page.

I thought this had to do with max\_packet size, but I am not to sure of that anymore.

The batch is being initiated after a form is being processed.

Do you have any ideas on how I can process 5000 users at a time, or why I am getting this error?

I think that the insert to the batch table is to big, so I am trying to split this into separate batches like this.

```
$contactCount = 1;
foreach ($contacts as $contact) {
  $batch['operations'][] = array('_contact_add_batch', array($module, $acc_id, $Group_ID, $verb,$contact));
  //Due to max_packet_size restrictions, need to set multiple batches
  if (($contactCount % 2000) == 0){
    batch_set($batch);
  }
  $contactCount++;
}
// For the last set of batches, in the event that there is not 2000, lets add them also.
if (!empty($batch['operations'])) {
  batch_set($batch);
}

```

I am still getting the Access Denied error.

# Answer
> 5 votes
Batch API in Drupal 6 serializes everything into one row, causing the problem you've seen. You need to do manually what Batch API does for you automatically in Drupal 7: use a queue. The Drupal Queue module is a Drupal 6 backport of the Queue API that is in core for Drupal 7.

Basically, queue the items you want to process, and then only pass the queue ID to Batch API. Batch API then fetches the queue and processes the queue part by part until it's done. See batch\_example\_batch\_2 from the Examples project for reference.

The Examples project also has an example module for queue usage, see: http://drupalcode.org/project/examples.git/tree/refs/heads/7.x-1.x:/queue\_example

---
Tags: 6, batch-operations
---


# Question
Title: Change theme_image_widget in other theme
I have a site, where I want to alter the form of the image widget.

I have a admin theme and overlay activated. The Admin theme is set to the default 'seven' theme from the core (V7.14)

Now I want to write

```
function seven_image_widget($vars){
    $vars['element']['alt']['#title'] = 'Foo';
    return theme_image_widget($vars);
}

```

If I add this in the template.php of seven theme, it works, if I put it in my custom theme, it does not work. Can I access this theme hook of seven theme from my theme in any way? I don't want to change the core themes code.

# Answer
I found it myself. If made a subtheme of seven (named sevensub) with just this special function in template.php

```
function sevensub_image_widget($vars){
    $vars['element']['alt']['#title'] = 'Foo';
    return theme_image_widget($vars);
}

```
> 0 votes

---
Tags: 7, theming
---


title: Alternative to Node Class module?

text:
# Question
Title: Alternative to Node Class module?
I'm looking for a simple way to add classes to nodes. I found this module http://drupal.org/project/node\_class but it is Minimally maintained.

Just wondering if is there any alternative to this module.

# Answer
Check Skinr module.

If you are only looking for a straightforward way to add classes to nodes, you could do that even without any additional module.

1. Create a field called "css\_class"
2. Hide that field from output
3. Edit the node.tpl.php file and print the value in the wrapper element

That should do the trick.
> 5 votes

---
Tags: 7
---


# Question
Title: Creating a view that groups results by month/year
Does anyone know how to build a view that groups the results by Month/Year but can print the results expanded. Take the following dataset:

**Events**

```
    Event Name  Event Date
    ----------  ----------
    Event 1     2011-05-01
    Event 2     2011-05-15
    Event 3     2011-05-30
    Event 4     2011-06-04
    Event 5     2011-06-22
    Event 6     2011-07-01
    Event 7     2011-08-16
    Event 8     2012-01-01
    Event 9     2012-01-02
    Event 10    2013-05-15

```

I would like Views to output that data in the following format:

```
    May 2011
    --------
      Event 1
      Event 2
      Event 3

    June 2011
    ---------
      Event 4
      Event 5

    July 2011
    ---------
      Event 6

    August 2011
    -----------
      Event 7

    January 2012
    ------------
      Event 8
      Event 9

    May 2013
    --------
      Event 10

```

So the view would not actually be grouped in SQL it just needs to print out the events with headings visually grouped by month and year.

# Answer
I'm not sure if it would be possible to group by month like that, but it would be pretty simple to do this in a template (or a preprocess function).

All you really need to do is to loop through all the rows and check if the event has a new month/year. Each time that happens you add the event date formatted as `Month year`. This would also give you the flexibility to print the months like fx `h3` or whatever fits your site best, instead of relying on the markup views would generate.
> 1 votes

# Answer
You can group by any field, including Month-year. You have to select your date field and customize the output. Then, Views can group on the field, using the "Grouping" options under Format: Settings.
> 15 votes

# Answer
You can do that using Views and have it displayed as a table. Table has an option to group fields.
> 3 votes

# Answer
In Drupal 7, with Views 3, KarenS recommends disabling the RDF module in Core. That's all that has worked for me. http://drupal.org/node/1253562#comment-4886998
> 1 votes

---
Tags: 7, views
---


# Question
Title: Drupal commerce: how to force user to pay with specific payment method?
I Have written a shipping method (name:X) and a payment method(name:Y) for drupal commerce. the problem is that I want to force user to pay with Y if he selects X and I want to disable other payment methods on this condition.

it can manually be done with rules! but I want to programmatically add this limit. how can I do it? is there a hook or something else?

# Answer
You've already realized that you need a rules condition, since the available payment methods are determined through rules.

The selected shipping method is stored on the order entity ($order-\>shipping\_rates), so you can just check that. You might need to write a custom Rules condition (which is just a PHP function declared by an implementation of hook\_rules\_condition\_info()).
> 2 votes

# Answer
Depending on what you're trying to do you might want to reflect these restrictions in your form with javascript too, but essentially you probably just want to add some extra logic in your form validation or form submit handlers.

They aren't hooks, but are callbacks added in hook\_form\_alter().
> 0 votes

---
Tags: commerce
---


# Question
Title: Conditional code in preprocess_page function?
I need to add a conditional code in a **my\_theme\_preprocess\_page** function.

The conditional should be like:

if the loaded node has a field called **background\_image** and the value for this field is not empty, then is true

# Answer
> 2 votes
I think this will work for you. Note:

* It doesn't check the node type.
* It adds the variable `has_background_image` on *any* page that has `$vars['node']` available in `hook_preprocess_page`, and *only* on those pages.
* `$has_background_image` will be true if the field isn't empty (that's the only check).

.

```
function MYMODULE_preprocess_page(&$vars) {

  $field_name = 'field_background_image';

  if (!empty($vars['node'])) {

    $node = $vars['node'];
    $items = field_get_items('node', $node, $field_name);

    $vars['has_background_image'] = $items ? TRUE : FALSE;
  }
}

```

# Answer
> 0 votes
It's not really clear what do you want to do exactly, but I suppose you want to pass it as another variable.

```
function my_theme_preprocess_page(&$vars) {
  // Make sure node object exists
  if (isset($vars['node'])) {
    if (isset($vars['node']->field_background_image[0]['uri'])) {
      $vars['has_background_image'] = true;
    } else {
      $vars['has_background_image'] = false;
    }
  }
}

```

And then in your page.tpl.php you could use $has\_background\_image to check if the value is true/false.

If this is not what you asked, edit your question to make your goal clear.

---
Tags: theming
---


title: last insert ID of drupal_write_record

text:
# Question
Title: last insert ID of drupal_write_record
I need to get the latest inserted id, this is the line im using for writing files to my db

```
drupal_write_record('file_managed', $file, 'fid');

```

any ideas?

# Answer
> 1 votes
I found the answer myself. Use `$file->fid`.

---
Tags: 7
---


# Question
Title: How to create a new role with authenticated user permissions
I want to create a new role. New role should have all the permissions of authenticated user as well as the some new permissions.

I used the following code,

```
$role = new stdClass();
$role->name = 'New role';

// load the authenticated user role
$auth_role = user_role_load(DRUPAL_AUTHENTICATED_RID);
$role->weight = $auth_role->weight + 1;

user_role_save($role);

```

and I will assign the permissions using user\_role\_change\_permissions() or user\_role\_grant\_permissions()

Now I want to assign the authenticated user permissions to this new role. How to achieve this?

# Answer
Got it. following code will achieve the this functionality,

```
$role = new stdClass();
$role->name = 'New role';
// load the authenticated user role
$auth_role = user_role_load(DRUPAL_AUTHENTICATED_RID);
// Give the weight more than authenticate user, so that
// New role will have all the authenticated user permissions
// by default.
$role->weight = $auth_role->weight + 1;
user_role_save($role);
$auth_permissions = user_role_permissions(array(DRUPAL_AUTHENTICATED_RID => 'authenticated users'));
$auth_permissions += array('other permissions');
// Grant permissions to our 'New role' role
user_role_grant_permissions($role->rid, array_keys($auth_permissions[DRUPAL_AUTHENTICATED_RID]));

```
> 1 votes

# Answer
Here is code that will assign new role to user:

```
global $user;
$key = array_search('your role', $user->roles);
if ($key == FALSE) {
  $roles = user_roles(TRUE);
  $rid = array_search('your role', $roles);
  if ($rid != FALSE) {
    /* change role in current session*/
    $user->roles[$rid] = 'your role';
    /*save role in db*/
    $new_role[$rid] = 'your role';
    user_save($user, array('roles' => $new_role));
  }
}

```
> 0 votes

---
Tags: 7, users
---


# Question
Title: EntityFieldQuery causing column not found PDO exception
I have a very simple node type set up in drupal, see it here

And I'm trying to get the node id based on the email field (the email is unique to each node, just like the nid). My query looks like this:

```
$query  -> entityCondition('entity_type', 'node')
-> entityCondition('bundle', 'mail_entry')
-> fieldCondition('field_email', 'value', $email);

```

But drupal is complaining with:

> "PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'field\_data\_field\_email0.field\_email\_value'"

I don't really understand what's wrong.

# Answer
> 2 votes
At a guess you're using the Email Field module to provide that particular field?

If so, the column name is `email`, not `value`, so your code should be:

```
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'mail_entry')
  ->fieldCondition('field_email', 'email', $email);

```

---
Tags: nodes, database, entities
---


title: how to use images uploaded to public://

text:
# Question
Title: how to use images uploaded to public://
with a form I've got the possibility to upload images, this is the piece of code that says where the files go: `'#upload_location' => 'public://',`

this is the piece of code which generates the rows in my table view:

```
$rows[] = array(
        'data' => array(
            l($node->id, 'node/'. $node->id),
            $node->url,
            $node->title,
            $icon = "<img src='$node->icon'>",
            $node->created,
            $delete = "<a id='delete' href='$node->id/delete'> " . t('Delete') . "</a> | <a id='edit' href='$node->id/edit'> " . t('Edit') . "</a>"
        )
  );

```

notice '$icon'. $node-\>icon returns for example usa.gif. But of course the path is invalid.

The question is: how can I use my images? I cant figure it out

There's probably some drupal way to do this, advice is highly appreciated!

# Answer
If `$node->icon` is the path relative to public://, then you can use the following code.

```
if ($wrapper = file_stream_wrapper_get_instance_by_uri("public://{$node->icon}")) {
  $url = $wrapper->getExternalUrl();
}

```

The code works also for stream wrappers that are not local, for which the file is not local to the server running the code.
> 4 votes

---
Tags: 7, media, uri
---


title: how do chmod a directory in drupal

text:
# Question
Title: how do chmod a directory in drupal
I want to enable pictures for users in drupal http://drupal.org/node/22271 and I am not sure how to chmod the directory so that users can save their pictures in it.

Thank you for your help in advance.

# Answer
You want to go through this guide. It discusses in depth the appropriate filesystem permission settings you should have on every part of the Drupal installation (public files, private files, etc.) If you follow that guide to the letter your filesystem problems will sort itself out, and you'll have a more secure Drupal installation. Let me know if you have any questions.
> 3 votes

# Answer
Go to the parent of the directory where you want to save the pictures or create your own directory with `mkdir` and `cd` command.

`cd` to change the directory .

`mkdir` to make a directory.

Then do `sudo chmod 755 directory-name`
> 1 votes

---
Tags: users, media
---


title: Override taxonomy_term_uri

text:
# Question
Title: Override taxonomy_term_uri
Is there a way to modify the behavior of `taxonomy_term_uri()` in a custom module for D7? I am not able to do so by definining `THEME_term_uri()`, and I wouldn't like to alter the original Taxonomy module.

# Answer
> 1 votes
I managed to override it. I found out that `'taxonomy_term_uri'` is defined in **taxonomy.module**'s `taxonomy_entity_info()` function, so I added a hook that alters it:

```
function MODULE_entity_info_alter(&$entity_info) {
    $entity_info['taxonomy_term']['uri callback'] = 'MODULE_taxonomy_term_uri';
}

function MODULE_taxonomy_term_uri($term) {
    // change the path...
    return array(
        'path' => 'taxonomy/term/' . $term->tid,
    );
}

```

# Answer
> 1 votes
`taxonomy_term_uri()` is called from entity\_uri(), which contains the following code.

```
 // Invoke the callback to get the URI. If there is no callback, return NULL.
  if (isset($uri_callback) && function_exists($uri_callback)) {
    $uri = $uri_callback($entity);
    // Pass the entity data to url() so that alter functions do not need to
    // lookup this entity again.
    $uri['options']['entity_type'] = $entity_type;
    $uri['options']['entity'] = $entity;
    return $uri;
  }

```

The value returned from `entity_uri()` is normally passed to url(). This means that implementing hook\_url\_outbound\_alter(), and hook\_url\_inbound\_alter() could achieve the same result as implementing hook\_entity\_info\_alter() to change `$entity_info['taxonomy_term']['uri callback']`, even though `hook_entity_info_alter()` is more easily implemented. I would probably implement the first two hooks if I need to alter the URI for more than one entity.

`hook_url_outbound_alter()` would get the entity type, and the entity object as `$options['entity_type']`, and `$options['entity']`.
`hook_url_outbound_alter()` and `hook_url_inbound_alter()` would also work with modules that don't use `entity_uri()` to get the entity URI; in that case, `hook_url_outbound_alter()` cannot probably count on `$options['entity_type']`, and `$options['entity']` being set.

---
Tags: taxonomy-terms
---


# Question
Title: Getting the base drupal dir in JavaScript
I am writing a module that does ajax calls through the uses of javascript (not the Drupal ajax engine) to its Drupal installation, which in my case is {host}/drupal7.

My Ajax call should call "{host}/drupal7/notifications/get" from any page. Yet when I do my ajax call from javascript it calls "{host}/notifications/get" now this seems like an easy fix. Yet I can't think of a way to compose the right URL in a way that it will work in any installation.

Can anyone point me in the right direction?

# Answer
> 4 votes
You should use Drupal.settings.basePath in your Javascript.

---
Tags: ajax, javascript, uri
---


title: Delete Long Text Box

text:
# Question
Title: Delete Long Text Box
I have a Node Content Type that has an "unlimited" number of Long text boxes allowed. I have created one-too-many text !\[enter image description here\]\[1\]boxes and cant seem to find a way to delete them.

Here is a link to what I am talking about

http://my.jetscreenshot.com/demo/20120730-gpz3-42kb.jpg

# Answer
You don't actually "Delete" the extra values, you can simply leave the extra boxes empty and they will be ignored when you save the content.
> 0 votes

---
Tags: nodes
---


title: Block inside another block

text:
# Question
Title: Block inside another block
I'm using *jquery countdown timer*, I want to but it in the *main page content block*. How do I put a block inside another block?

# Answer
From the url `/admin/structure/block` you can set Blocks to Regions on your site. You simply drag and drop the block(s) to the given Region of your page and `Save` the block ordering on that page. In this screenshot I have 3 blocks in the main content area for my theme:

You can then go into each block with the `configure` link and set that block to show only on certain page(s) for instance, or only for certain Roles of the site.

This is the simplest means using Core drupal and no 3rd party modules.

If you want to eventually look into other means of doing this look into the Context module, or Panels.
> 2 votes

---
Tags: 7, blocks, javascript
---


# Question
Title: Checkbox left hand navigation drill down
Does anyone have an idea on how I can go about creating this navigation? I have a section of a website that has subwords of a top vocabulary word that I would like to show in a left hand menu in order to drill down to the content with checkboxes.

\[\]Topic 1 ---\> if checked show excerpts of all articles with this topic in the content area.
\[\]Topic 2 ---\> if checked show these articles...
\[\]etc...

The user could check 1 or all of the topics and get the articles.

Sort of like: https://wordpress.stackexchange.com/questions/18484/checkboxes-in-the-category-list

Thanks for any direction, help or the like!

# Answer
> 0 votes
Just to help others out here! This is called Faceted Search. After looking around and around online, I found it. There are a lot of posts about it. Drupal 7 uses Facet API to do this. However, it is still not extremely straight fwd...

---
Tags: navigation, forms
---


# Question
Title: How to compare two fields in a preprocess_field()
I need to compare two fields using template\_preprocess\_field().

I've got a field date and a boolean field. Field date collect start and end date but if it's one day event, I need to show "start date - one day"

If you don't collect the end date, it will be the same date of the start date. Of course I can compare start date and end date and if they are the same I will show "one day" but if the event is still running (so I won't collect the end date), I should show "on air"

So I'm trying this

```
function bartik_preprocess_field(&$variables) {

  //here I call the date field
  if($variables['element']['#field_name'] == 'field_duration') {
    $starttotime = time($variables['element']['#items'][0]['value']); // convert it in time
    $starttodate = date('d-m-y', $starttotime); // formatting date

    // check if start date and end date are similar
    if ($variables['element']['#items'][0]['value'] == $variables['element']['#items'][0]['value2']) {
      // HERE I NEED TO CHECK THE OTHER FIELD
      if (HERE THE FIELD ONE DAY == 0) {
        $variables['items'][0]['#markup'] = $starttodate." - One day";
      } else {
        $variables['items'][0]['#markup'] = $starttodate." - On air";}
      }
    }
  }

```

# Answer
> 0 votes
`hook_preprocess_field()` is invoked while rendering a single field, but (basing on the documentation for field.tpl.php) `$variables['element']['#object']` is the entity object to which the field is attached. Through that, you can get the value of the other field you are looking for.

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


# Question
Title: Is this a reasonable use of hook_user_presave?
The documentation for `hook_user_presave` says that

> This hook is primarily intended for modules that want to store properties in the serialized {users}.data column \[...\]

Instead, I'm using it to check that a change of email address does not clash with any email address in a database separate from the database for my drupal site. If it does, I do

```
$edit['mail'] = $account->mail;

```

so that the update to `mail` does not go through, but the rest of the edit is unaffected. (I also put up a warning message, under the assumption that the only time the email changes is when someone changes it manually.)

With anything web-related being outside my usual field, I'm not sure if using this method in a different way than intended is too clumsy or unsafe. Is it ok to use this method in this way?

# Answer
> 1 votes
If you look at the documentation page for Drupal 8, you will notice that sentence is not used anymore.

> Act on a user account being inserted or updated.
>
> This hook is invoked before the user account is saved to the database.
>
> Modules that want to store properties in the serialized {users}.data column, which is automatically loaded whenever a user account object is loaded, may add their properties to $account-\>data in order to have their data serialized on save.

The fact the hook has different parameters in Drupal 8 doesn't change its purpose. In fact, with Drupal 8 you could use the following code.

```
$account->mail = $account->original->mail;

```

`$account->original` contains the value returned from entity\_load\_unchanged().

Although on Drupal `hook_user_presave()` is normally used for the purpose you noticed, you could use it for the purpose you described.

The alternative would be to add a form submission handler to the user edit form which is executed before the default form submission handler. The pro of using `hook_user_presave()` is that it works also when a module programmatically save a user object using `user_save()`.

---
Tags: hooks, users
---


title: CSS in IE doesnt load

text:
# Question
Title: CSS in IE doesnt load
CSS styles don't load in Internet Explorer (checked on version 9 and 7). They work locally, but not on the remote server. Do you have any idea?

**Edit**: It seems that compressing CSS inside "configuration \>\> performance" causes this problem. Is there a way to turn this feature for all browsers except IE?

# Answer
Does turning on CSS aggregation make your CSS work in IE?

If so, you may be coming up against the 31 CSS file limit in Internet Explorer.

Someone has made a module that deals with this - IE Unlimited CSS Loader.
> 1 votes

# Answer
What you need to do is copy the html.tpl.php template from modules/system/html.tpl.php to your themes templates directory, so sites/all/themes/your theme/templates and open it up. In the head section add this tag:

```
<meta http-equiv="X-UA-Compatible" content="IE=8" >

```

This tells Internet Explorer to specifically use the web standards incorporated into IE 8. This means that basically for any version of Internet Explorer equal to 8 and above you'll have, at minimum, IE 8 viewing standards. I had to do this same thing when using CSS aggregation.

BTW, you don't necessarily have to use version 8 as the base, if your site runs fine with 7 then I'd recommend going with 7.
> 0 votes

# Answer
As well as the 32 stylesheet limit there's a 4095 selector per stylesheet limit. If you're encountering that issue with aggregation *on* then it's probably the selector limit.

I've gotten around this in the past by writing a page preprocess function to split up aggregated stylesheets into smaller chunks than IE can handle.
> 0 votes

---
Tags: theming
---


# Question
Title: If I delete enabled module files will items be stuck in the database forever?
The list that populates the modules page is loaded from the files. But whether a module is enabled or is stored in the database (I assume).

If I enable a module and then delete the files will there be an database entry (to say it's enabled) in the database forever? Or will it be cleared at some time?

Will it slow down the site or clog up my database if I've cleared a lot of modules without disabling them first?

# Answer
In order to get rid of module's database tables and other contents, you must first **disable** the module, and then **uninstall** it. Deleting a module without disabling it is "against the rules", as module\_exists('foo') will still return 'true' for these enabled-but-removed modules. Since Drupal tends to call modules only via code that uses the php function `function_exists` to determine if hooks are available, you usually won't experience any obvious problems if you do this. However, things could get weird if you had a situation where module B uses module\_exists() on one of these modules that you removed. The code in question could make assumptions that are only true when the hooks you deleted are executed, which could cause unpredictable behavior. So, in short, don't do that -- always disable and uninstall your modules if you no longer need them.
> 2 votes

---
Tags: 7, database, files
---


# Question
Title: Where do I find the Facebook application id for the the fb_social module?
I just installed the fb\_social module. Now I need to set up the module which requires the Facebook application id.

Under the field reads: **Get the ID of your facebook app or create a new facebook app : here.**

But the link drive me to the main page of my facebook account.

Where is the right place to find it?

# Answer
1. Login as FB app admin
2. Go here: https://developers.facebook.com/apps
3. Copy the destination for "Edit settings" link for your app
4. Take app ID from the URL. This is the pattern: https://developers.facebook.com/apps/\[your app ID\]/summary
> 1 votes

---
Tags: 7, social-network
---


title: superfish not affected by css edits

text:
# Question
Title: superfish not affected by css edits
I am making a nav bar using the suckerfish module. I have installed the suckerfish module and have extracted the library into the necessary folders. I'd like to change the width of the individual columns in the nav, as some of my menu items are getting cut off. I'd also like to change the width of the nav bar as a whole, as it is not the same width as my header. However, when I try to make basic edits in the space-orange.css file, the edits do not seem to make any difference what-so-ever. I can change the style of the nav bar from the blocks menu, so I know the css files are in the right place. I have also looked at the suckerfish.css file, but it's not clear what, if anything, I could try to edit there. I am all out of ideas at this point. Are there any great tutorials out there pertaining to this? I can't seem to find any. Any help in getting me going in the right direction would be most useful and appreciated.

Thanks,

Kev

# Answer
If some of your menu items are cut off, you should enable the supersubs plugin. You can do that on the block settings page for that particular menu.

If that's not what you want, copy over the stylesheets of superfish to your theme, include them in .info file and play around there.
> 0 votes

---
Tags: theming
---


# Question
Title: Any particular vacuum policy to increase performance using Drupal with PostgreSQL?
I'm running Drupal 7 with PostgreSQL as a Q&A (with a lot of nodes inserts/updates and several contrib modules). Do you recommand any particular pgsql vacuum policy on particular tables ?

# Answer
> 2 votes
In theory you can run your database optimization commands any time you want, but I think at least bi-weekly helps. However, if by running database optimization commands you intend to improve the performance of your site by more than 5%-10%, I'm afraid no vacuum optimization policy will do. You will need to utilize traditional performance troubleshooting procedures such as checking all your server's error logs, access logs, database slow query logs, as well as taking in consideration your peak and average load versus your current architecture.

---
Tags: 7, performance, database
---


# Question
Title: How/where to change the default size of inline images?
For the life of me, I can't seem to figure out **how/where to change the default size of inline images** (that is, images that have been inserted into the body by way of the wysiwyg editor's `Insert/Edit Image` button). It's likely that I'm missing something obvious here as I've only had one cup of coffee today... tragic, I know.

# Answer
> 4 votes
I would use the Image Resize Filter or Image Autosize Filter modules. These module add a filter to your input format that automatically resizes images added through the WYSIWYG editor. Image Autosize Filter allows you to set a maximum width, which seems like it would work for your case.

As a precautionary measure, you could add some CSS like this as well:

```
.node img {
    max-width: 450px !important;
    height: auto !important;
    border:0px;
    margin:0em;
}

```

# Answer
> 1 votes
With CSS, you could do something like:

```
.class-of-whatever-div-your-content-is-in img {
   width: 228px;
   height: 228px;
}

```

and then all images in there would be 228 x 228 squares. You could use max-width and/or max-height if you wanted to get fancy and not potentially upscale any small images, too. (Add some !importants if necessary depending on what your WYSIWYG editor may put in, too :)

# Answer
> 1 votes
You can also write custom JavaScript to adjust the width of images that have been inserted using WYSIWYG. Then you can use JS Injector module to inject your little JavaScript on required paths.

One time, I had to make sure that width of images uploaded using CKEditor does not exceed the max width of my theme.

I used following code. You can do same for basically any node page by passing the correct ID to jQuery function.

```
//adjust the width of images shown using views
var views=$(".view-content");
$(views).each(function(){
var max_width=$(this).width();
$(this).find('img').attr('style','max-width:'+max_width+'px;');

});

//adjust the width of images on node pages
max_content_width=$("#main .content").width();
$("#main .content").find('img').attr('style','max-width:'+max_content_width+'px;');

```

# Answer
> 1 votes
As mentioned by others here, the default inline images button just inserts an image as-is, so the answer to your question is technically that there is no "default" size.

That's not very helpful though :P What you want is some way to get the image to be processed by imagecache/image (depending on whether you use D6 or D7) so you can apply a preset/style. Anything that allows the image to be rendered with core's theme() function will do the trick.

Taking pre-existing rendered markup and retroactively applying image styles would be another approach, you could use querypath or something similar but something tells me that you'd end up killing kittens..

There's a WYSIWYG Fields module that is designed to give you the best of both worlds (the control from rendering fields + the ease of WYSIWYG editing) - http://drupal.org/project/wysiwyg\_fields. That sounds like a good option for you to get what you want.

# Answer
> 1 votes
If you are using the CKEditor module, for example, you can always write your own CKEditor plugin. Although it sounds scary, it is actually more easy to do than what it sounds, and it is well documented here, here, and here. Examples are included in the links. The cool thing about writing your own plugins is that you have ultimate control of the WYIWYG editor's functionality because your plugin interacts both with Drupal/PHP (using custom CKEditor hooks) and the editors' JavaScript interface.

In your case you could write a custom settings page in Drupal through which you specify the default image size, or as suggested elsewhere, interface with the image cache API (which is pretty elegant, btw). Then you could copy/take ideas from whatever JavaScript code currently inserts the images, and modify it to your will.

Once you implement your own plugin, the sky is the limit. Good luck!

---
Tags: media
---


title: order by weight ASC - D7

text:
# Question
Title: order by weight ASC - D7
This piece of code:

```
->orderBy('weight', 'ASC');

```

orders the column by the weight ascending. However, the rows are sorted like: 15 - 2 - 20 of course this should be: 2 - 15 - 20

How can I achieve this, specifically for drupal(7)?

# Answer
> 3 votes
It seems that the database is using lexicographic ordering, while your intention is to use numeric ordering. Numeric ordering is only used when the type of the field is a numeric type. Check whether the field is of a numeric type.

---
Tags: 7, database
---


title: Multilanguage mails

text:
# Question
Title: Multilanguage mails
We have built a site with multi language support in English and German languages. Now we need to set drupal default mails like login reg. mails, forget password mails in both the languages. The users using German site will need to get German mails and vice versa for English users.

So we have changed German mail content under Account setting -\> Email of german(DE) Website. and i had checked the English website(EN) Version, its shows me the german mail Content. The Mail content are synchronizing while updating in one language version of the website... what i need to do to fix this one?

# Answer
Ok, here's how to do this using i18n and variable:

1. Visit "Variables" under "Multilingual settings". (/admin/config/regional/i18n/variable)
2. Under "User e-mails", check all e-mails that you wish to translate and click "Save configuration".
3. Go to the e-mail configuration page. (/admin/config/people/accounts)
4. By default, the e-mails will be displayed in the default language. To translate the e-mails you selected in Step 2 above, choose a language from the **There are multilingual variables in this form)** box at the top of the page.
> 16 votes

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


# Question
Title: How to force openid login from a single provider in Drupal 7?
So with the current Drupal 7's OpenID module, one must click on the "OpenID" on the main page, which the user then enter the url of the OpenID provider to link up to. Assuming I know exactly what provider I want to use (my university's), there some way I can make it such that as soon as a user visits the homepage, or any part of my drupal site, the first thing it does is authenticates with that specific provider url before it even shows the page?

The reason being is I want people within the university network to be able to go to the site and automatically see who they are without having them perform that extra step of clicking on an "openid" button. Much like a single-sign-on solution.

# Answer
You must create a custom module to generate a page "/login" that start OpenID authenticate.

Create a module with this code :

```
/**
 * Implements hook_menu().
 */
function mymodule_menu() {

  $items['login'] = array(
    'title' => 'OpenID Login',
    'page callback' => 'openid_login',
    'access callback' => 'user_is_anonymous',
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/*
 * Menu callback; start openid authenticate
 */
function mymodule_login() {

  $return_to = url('openid/authenticate', array('absolute' => TRUE, 'query' => array('destination' => 'user')));

  openid_begin("https://www.myopenid.com/", $return_to, array());
}

```

The example works with the myopenid.com provider. Go to "/login" on your website to log in.
> 2 votes

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


title: Remove jquery CSS

text:
# Question
Title: Remove jquery CSS
When i add `drupal_add_library('system', 'ui.accordion');` to my template.php, 3 jquery css files are loaded, but i can't remove them with `$css_to_remove[] = drupal_get_path('misc','ui').'/jquery.ui.core.css';` (i tried some paths, but none worked).

Can anyone tell me how to remove CSS files loaded by jquery libraries? Thanks

# Answer
> 4 votes
This code will help you. Add it to your template.php:

```
function THEME_NAME_css_alter(&$css) {
  // List of disabled drupal default css files.
  $disabled_drupal_css = array(
    // Remove jquery.ui css files.
    'misc/ui/jquery.ui.core.css',
    'misc/ui/jquery.ui.theme.css',
  );

  // Remove drupal default css files.
  foreach ($css as $key => $item) {
    if (in_array($key, $disabled_drupal_css)) {
      // Remove css and its altered version that can be added by jquety_update.
      unset($css[$css[$key]['data']]);
      unset($css[$key]);
    }
  }
}

```

If you want to remove some other css - just print\_r $css variable to get its name and add it to $disabled\_drupal\_css.

# Answer
> 0 votes
You have to use exactly the same name as the stylesheet you want to remove.

You could do that even in your theme .info file. The file does not need to exist, it is enough if you just add this line there:

stylesheets\[all\]\[\] = jquery.ui.core.css

---
Tags: 7, javascript, theming
---


# Question
Title: Is there any way to display a taxonomy sorted by another taxonomy?
I'm working on a homepage for a student paper and I'm needing some way to display 3-4 arbitrary pieces of content from each section every week (I.e., top stories) in a panel for each section.

In order to do this, I'm thinking I'll use the Weight module to create a list of top stories for the week via that Taxonomy, **which I would then like to group by another taxonomy term, "section".**

How would I go about doing this?

Many thanks!

# Answer
> 0 votes
I ended up creating a view that grouped row by the section taxonomy field, then sorted by sticky. Didn't even have to use Weight or Flag!

Oh, Views -- you make life so easy...

# Answer
> 0 votes
I would look into the Flag module. With it, you could flag certain content and then use Views to show just that content. You could also create different flags for different sections, etc.

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


# Question
Title: Add / Remove column in admin/content/node
How can I add / remove columns in admin/content/node ?

# Answer
Of course you can modify this page by implementing hook\_form\_alter in your custom module.

But the best approach is using Views and VBO module create your own contant admin page with columns and filters that you need. Module Administration Views will help replace Drupal core admin page with your own.
> 3 votes

---
Tags: nodes, forms
---


title: Delete duplicate user

text:
# Question
Title: Delete duplicate user
Somehow I've got 2 users in my `users` table with the same email address (mine!). I need to delete one of them. One is user ID #1, the other is user ID #144.

When I use the `advuser` module to search for my email address, only one user (#144) shows up. I select it and try to delete, but it's not successful - the confirmation screen says `"No selections have been applied."` I'm guessing it's trying carefully to not delete user #1.

Additionally, I can't seem to change any account details in my own (user #1) account, it complains that `"The e-mail address me@foo.com is already taken."`

Not sure what to do next - am I safe to just do `DELETE FROM users WHERE uid=144;`? Or will that create dangling references elsewhere?

I'm using D7, but I had this extra user before I upgraded from D6 too.

# Answer
> 2 votes
Why can't you delete it using admin account?

Drupal 7 people path : goto admin -\> people \[ here you can manage your users account\]

# Answer
> 4 votes
Instead of deleting the user and risking something going bad, why don't you try just to change his e-mail address in the SQL table? If you change #144's mail won't you then be able to edit, delete his account through the usual UI way?

# Answer
> 1 votes
If you delete your extra user via an SQL statement, you may still have content in your database (nodes) that were created by that user. You could also try to track down all of those references and fix them up, if you wanted, or you could use `drush user-cancel username` to remove the extra user. This presumes that the two users who have the same email address have different user names; many of the drush user commands will allow you to specify the target by uid, but user-cancel requires a username. If the usernames are unique, then drush user-cancel will re-assign all content created by said user such that it will appear to have been created by uid 1.

See http://drupal.org/project/drush for Drush.

# Answer
> 0 votes
With Drupal 7, you can delete a user account using `user_delete_multiple(array($uid))`. The function will take care of any reference to that user account; it also invokes the necessary hooks, to let other modules know the user account is being deleted.

This is the code executed from that function.

```
  if (!empty($uids)) {
    $accounts = user_load_multiple($uids, array());

    $transaction = db_transaction();
    try {
      foreach ($accounts as $uid => $account) {
        module_invoke_all('user_delete', $account);
        module_invoke_all('entity_delete', $account, 'user');
        field_attach_delete('user', $account);
        drupal_session_destroy_uid($account->uid);
      }

      db_delete('users')
        ->condition('uid', $uids, 'IN')
        ->execute();
      db_delete('users_roles')
        ->condition('uid', $uids, 'IN')
        ->execute();
      db_delete('authmap')
        ->condition('uid', $uids, 'IN')
        ->execute();
    }
    catch (Exception $e) {
      $transaction->rollback();
      watchdog_exception('user', $e);
      throw $e;
    }
    entity_get_controller('user')->resetCache();
  }

```

Between the implementations of `hook_user_delete()`, there is also node\_user\_delete(), which deletes the revisions of a node made using the user account being deleted.

---
Tags: users
---


# Question
Title: Drupal commerce show taxonomy image in product variation
I'm trying to change the view of the product variation. Let's say I'm selling t-shirt in different color so I create the taxonomy with the color and a small image of the color. I create the term reference in product and enable the "Attribute field settings". Now when i display a product i should be able so see the image of the taxonomy to choose the color but it shows me just the title in a select list or radio button. How can I override it?

Thanks in advance.

# Answer
You need the Commerce Fancy Attributes module.
> 2 votes

---
Tags: 7, theming, commerce
---


title: Can not access admin links

text:
# Question
Title: Can not access admin links
I have encountered a weird problem in Drupal 6 in the recent days: I can log in as admin but none of the mysite.com/admin/\* links work from GUI.

I still can use drush to enable and disable modules and do other administrative tasks but can not do the same from the admin menu.

None of the other aspects of the site are affected. I cleared all cache, updated the database, performed cron (using drush), and restarted all servers. Alas, no effect. The log messages are not helpful either. I'm really perplexed and appreciate your help.

# Answer
> 0 votes
It turned out to be a problem with nginx/php5-fpm settings that timeout prematurely. When I use apache (using another port) the problem does not exist.

---
Tags: navigation, users
---


title: jQuery Star Rating Plugin in drupal 7

text:
# Question
Title: jQuery Star Rating Plugin in drupal 7
Our customer wants to have this plugin within drupal: http://www.fyneworks.com/jquery/star-rating/#tab-Testing and I cannot get it to work.

The basic code works, I can create stars and have them display a stored value. However, I want to use the callback functionality and this is not working, not even when I copy the test code from the site above to a blank page.

There are no stars (just radiobuttons), when I add star as a class I can see the stars again but then the callback will not work (as mentioned on several pages).

I figured it might have something to do with the version of jQuery so I installed the jQuery Multi module and the most recent jQuery (1.7.2) and enabled that for the star rating plugin, but this did not help. Any tips on how to proceed/debug?

I am no jQuery expert, I tried looking at the plugin code to see if something was missing, but could not understand it and nobody else complains about this not working (except if they did something wrong with the callback functionality).

edit: I failed to mention that the entire page is constructed from php ignoring drupal things like blocks or nodes, this makes it hard to use the 5-star module. This was not my choice and a very bad way to use drupal, but that is what I have to work with, unfortunately.

# Answer
With help from Lennert at gettingsocial.nl I was able to solve this. The trick was to not use the drupal method to load the jquery.rating.pack.js as the script needs to be loaded after the checkboxes have been added. (the drupal\_add\_js() function will put it in the header).
> 1 votes

# Answer
You can use Fivestar module.

It features:

* jQuery rollover effects and AJAX no-reload voting
* Configurable star sets
* Graceful degradation to an HTML rating form when JavaScript is turned off
* Support for anonymous voters
* Spam protection to keep users from filling your DB with bogus votes
* Easy-to-use integration with Views module for lists sorted by rating, or filtered by min/max ratings
* A Fivestar CCK field for use in custom node types
* An easy-to-use Form API element type for use in other modules
* Compatible with all versions of jQuery (1.0 - 1.4.4)

### Dependencies

This module is dependent on the Voting API. Voting API provides database storage of votes, as well as Views integration. You'll need to download Voting API, and Views is highly suggested if you want to create pages of results or use ratings to sort content.
> 0 votes

---
Tags: 7, javascript, rating
---


title: How to add a static image to theme?

text:
# Question
Title: How to add a static image to theme?
I'm very amateur in theming. Using Basic theme for Drupal 6, I try to add an image to the very top of the page. (Something like repeating flags here) However, when I add

```
<img src="images/flags.png"/>

```

to the upper side of page.tpl.php, the image has proper permissions but does not show up. No surprise though since the image is hyperlinked as

```
http:// 127.0.0.1/drupal6/content/images/flags.png

```

I have also tried defining a div class="flags" at the top of page.tpl.php and then introduce the image as the div's background-image url('images/flags.png'). No success either.

Direct insertion of static images used to work on my other theme. So got really perplexed and appreciate your help.

# Answer
> 2 votes
Put all your theme images in a directory in your theme; let's call it `img`.

Then you can load them like so:

```
<img src="<?php echo drupal_get_path('theme', 'THEME_NAME'); ?>/img/flags.png">

```

Hope this helps.

(More info at drupal\_get\_path();)

# Answer
> 1 votes
I think you should use the div header and css background image to put that kind of image. Anyway if you want to put a static image in the theme you can add

```
<img src="<?php print $GLOBALS['base_url'];?>/images/flag.png" />

```

$GLOBALS\['base\_url'\] is the url of the website (http://www.example.com or http://www.example.com/folder if it's in a subfolder)

---
Tags: theming, media
---


# Question
Title: views-view-field.tpl.php - How to print multiple values?
I've created a views template (based on views-view-field.tpl.php) because I want to exclude a certain value ('o') from being displayed. I came up with the following code:

```
$data = $row->field_my_field;
$raw_value = $data[0]['raw']['value'];
$rendered_value = $data[0]['rendered']['#markup'];

if ($raw_value == 'o') {
}
else {
  print $rendered_value;
}

```

This works fine for a single value, but this field allows for multiple values (up to about 20). How can I modify the code to print all of the values except, if present, 'o'?

# Answer
> 1 votes
You can do it in the template itself quite simply, something like:

```
<?php foreach ($row->field_my_field as $data): ?>

  <?php if ($data['raw']['value'] == 'o'): ?>
    // Output nothing, or placeholder, whatever
  <?php else: ?>
    <?php print $data['rendered']['#markup']; ?>
  <?php endif; ?>

<?php endforeach; ?>

```

This is a custom template for that particular field, and so should only be used with it (which can be done via preprocess). You might also need to be careful about the name of the field changing if the field's changed in the View.

The nicest approach I can think of is probably using `hook_field_attach_view_alter()`:

```
function MYMODULE_field_attach_view_alter(&$output, $context) {

  $field_name = 'field_test';
  $to_hide = array('o');

  if (isset($output[$field_name]['#field_name'])) {
    if ($field_name == $output[$field_name]['#field_name']) {
      foreach ($output[$field_name]['#items'] as $delta => $item) {
        if (in_array($item['value'], $to_hide)) {
          unset($output[$field_name][$delta]);
        }
      }
    }
  }
}

```

That will work for Views *and* a normal entity view. AFAIK you can use `$context` to detect whether you're in a View or not, but I can't remember what you'd check for exactly. (And if you later find you *do* want to display the field like this outside of Views, it's painless to change.)

HTH

---
Tags: views, theming
---


# Question
Title: How to add global variable in custom js file
I've added my custom script wrapped in :

```
(function ($) {

    Drupal.behaviors.exampleModule = {
        attach: function (context, settings) {

```

But can't create a global variable inside it

# Answer
> 16 votes
You can do something like

```
(function ($, Drupal, undefined) {
    var my_global;

    Drupal.behaviors.exampleModule = {
        attach: function (context, settings) {
            my_global = 1234;
        }
    }
})(jQuery, Drupal)

```

and the Javascript scope-chain rules will make `my_global` visible to your whole closure. If you need a true global, move the declaration of `my_global`:

```
var my_global;

(function ($, Drupal, undefined) {
    Drupal.behaviors.exampleModule = {
        attach: function (context, settings) {
            my_global = 1234;
        }
    }
})(jQuery, Drupal)

```

Personally, my JS files for Drupal start out as

```
var MYMODULE = (function(me, $, Drupal, undefined) {
    me.name = "MYMODULE";

    function attach (context, settings) {
        console.log(me.name + ".attach()");
    }

    Drupal.behaviors[me.name] = {
        attach: attach
    };

    return me;
}(MYMODULE || {}, jQuery, Drupal));

```

and I then add locals for module-wide variables, or directly to the module if other modules need them. The article JavaScript Module Pattern: In-Depth explains this very well.

---
Tags: 7, javascript
---


# Question
Title: views exposed filter on field collection item
I use `views-7.x-3.3` and `field_collection-7.x-1.x-dev` of 2012 Jun 28.

I have a very simple content type (person) with the following fields:

* name: text
* surname: text
* mother language: term reference \[en, fr, de\]
* portfolio: field collection of:
    + website language: term reference \[en, fr, de\]
    + url: link

I can create an exposed views filter on the `mother language` field just fine. The drop down appears and correctly filters the nodes as expected.

When I try to create a filter on the `website language` field of the `portfolio` field collection though, it fails to filter. No results are returned unless the dropdown value is set to "all".

Is it the case that field collection fields cannot participate in views filters? Is there a solution to that?

# Answer
> 12 votes
Field collection items can perfectly participate as Views filters. The key is to use Views relationships. You can create a relationship for the portfolio field, and then in the filter specify to use that relationship. That will cause the filter to analyze the field collection's contents, as opposed to the host entity's.

For example, here I established a relationship to an image gallery collection, created a file id filter, and associated the filter with the collection. The fid filter is also exposed:

---
Tags: 7, views
---


# Question
Title: How to bulk resize images imported with feeds importer module?
I have a Drupal 7 site on a test machine (Windows 7/Apache/PHP 5.3), with the Commerce and Feeds modules installed, and succeded in importing a CSV of more than 400 products (images included!), which made me really happy.

Now I've got a problem: in the Commerce product settings, the maximum width & height are set to 700px and 400px, respectively. The feed importer **didn't resize** the product photos, so now I'm stuck with product images that are the original hi-resolution photos (all above 2000x1000 pixels)!

Is there a way to make Drupal automatically re-process all the Commerce product images (call it a bulk resize, or a batch resize...)? Or have I got to reprocess them through Photoshop or something like that, and then re-import the CSV?

I know that probably not many people have faced a similar situation... any hint is appreciated!

**Edit**

I'm using Views Slideshow with jQuery Galleria, which loads the **original** images and resizes them via `img` tag attributes `width` and `height`.

That is a reasonable part of the problem, because even if I use Image styles (Configuration\>Media\>Image styles), Galleria keeps using the original image, which slows down the browser and consumes a lot of RAM.

# Answer
> 1 votes
If you have access to a command line and ImageMagick, you can run `convert` from `find`.

## **In Unix et al**

From Drupal root:

`find sites/default/files/products -name '*.jpg' -execdir convert {} -resize 700x400 {}\;`

(Note: this assumes all product images are in the "products" directory in sites/default/files. You *DO* want to make a copy of this directory with `cp -r sites/default/files/products sites/default/files/products_backup` before running the above in case it does something you don't want it to!)

## **In Windows:**

1. Download and install findutils.
2. Download and install ImageMagick
3. Make sure both are working on the commandline. Type "find" and hit enter. Same with "convert". If neither gives you a "command not found" error, they're installed and working.
4. Backup your product images directory.
5. Instead of the above command, try:

`find sites\default\files\products -name '*.jpg' -execdir convert '{}' -resize 700x400 '{}' ';'`

If find chokes on that path, try using backslashes. Also, make sure it's using the GNU version of find and not some other version (The lender Windows machine I'm working on right now has a find command, don't know if that's standard or something somebody else installed).

# Answer
> 0 votes
I think its ok to have the images in high res. So you're able to use them in whatever format and size you need. Have a look at the Imagecache Module. This module allows you to create image styles. For each image you show on your page, you can have different media styles or presets and use them for example in views or in different view modes.

Edit: Built in in Drupal 7. Have a look in Admin -\> Image Styles

---
Tags: 7, media, commerce, feeds
---


# Question
Title: getting response back from a Java Servlet to Drupal
My working scenario is like this, A webform (suppose an admission form for school) should be there on my drupal site and when a user clicks "submit" button a nicely formatted pdf file should be generated.

my approach is like this: 1. I have created a webform using webform module

1. I have written a servlet to generate pdf file (currently hosted at another server)
2. now I want to have communication between my servlet and drupal, so I created a small module that will execute custom function whenever user clicks submit button of the webform.

I am using curl to send the form data to servlet and it is working with http code 200.following is my code.

```
define("URL","http://localhost:8080/pdf?");
//my data actuly its coming from the webform
$fields = array(
  'name'=>'deepak',
);

$fields_string = http_build_query($fields);
drupal_set_message($fields_string);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, URL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec($ch);
curl_close($ch);

```

I am getting the PDF file encoding printed in the browser. How can I force User to download it.

please guide me.

# Answer
> 2 votes
To force download, you want to set the proper headers for filename, content-disposition and content-length. In your case, it may need to be set from the Servlet application, but without knowing the details of $response, that's difficult to determine.

In general, though, your headers should look something like this:

'Content-disposition:attachment;filename=foobar.pdf' (content-disposition:inline is the opposite of this) 'Content-length:1234567098'

---
Tags: hooks, webforms
---


# Question
Title: Webform on 'hostile development' environment
A client has a 'hostile development environment' and, related to this, a list of 'blessed modules'.

One of the hard/fast rules is 'no Webform' module.

(The only answer given to 'Why?' so far is, "If the answer is Webform, you're asking the wrong question," by the Devops people who guard this hostile environment.)

Is this a justified exclusion in any way and how would you respond to this statement/exclusion?

Our use case is for a single, simple contact form which allows users to submit their email address, a Subject and a body (in plain text only).

And the reason I'm asking this is so I can explain to 'stakeholders' (also on the client side) what's going on. Devs on my side are mystified.

# Answer
Coming from a huge production environment with Drupal multi-site running, the Webform can be a constant headache if there is no SPAM protection turned on, or if modules/core aren't kept up-to-date. Maybe they had problems in the past with Drupal admins not running protection on their forms and not keeping their modules up-to-date with the latest security fixes? Also, Drupal, the Webform module and open-source CMSs in general have a bad rap with the IT/Security crowd. I have experience it more than once in my career.

The best thing you can do is find out why they feel the way they feel about that particular module, and then explain to them how, if maintained correctly and used correctly, it should be of little to no concern.
> 3 votes

# Answer
The webform module has well over 200000 installs. Compared to any other Drupal-related way of gathering data, the module is very well vetted from a security perspective. Add that it's used on the professional webform.com site, and I don't see how anyone could complain about its security.

I've deployed webform to a customer that described it's environment as very hostile as well, their team didn't have any problems with it.

You need to get a serious answer, or a suggestion for an option. If you need to gather data, sure, you could implement it yourself, but then why not implement your own encryption-scheme while you are at it.
> 2 votes

# Answer
First of all I would want a clear explanation of why certain modules are restricted. May be they have found a security issue in it or sometimes some business units wants to store Personally Identifiable data in a secured manner. Once I get the explanation I will modify the module accordingly if its reasonable.
> 1 votes

---
Tags: webforms
---


# Question
Title: How can I create a collapsible block from page content using .tpl file?
I'm using the FlickrGallery module - http://drupal.org/project/flickrgallery and its basic functionality is pretty great - it automatically pulls in photosets from the Flickr account and displays everything using shadowbox, which means it'll work on iPhones, iPads, etc. Once the user uploads a photoset on Flickr, it simply appears on the site - no fuss, no muss. And it's also domain-sensitive, so different subsites can have different galleries. Like I said, pretty great - except for one major issue:

The module works outside of Drupal's content system - it simply pulls in a page and everything's hardcoded. The problem is that the page displays **all** photosets and there's no way to limit the photosets displayed, by paging or otherwise.

I want to create a multimedia page with collapsible blocks for photos and video - the video is no problem using Collapsiblock, but with a large number of photosets, the user will need to scroll down to the bottom of the page to see all available content.

Here's my question: How would I place the page content into a collapsible block using the module's .tpl file? Any ideas greatly appreciated - this is my first post on Drupal Answers!

Here's the existing template (with a few mods):

```
<?php
/*
 * Available vars:
 * - $description: Containing the description of the FlickrGallery module you provided at the settings page
 * - $albums: Array that contains the image and titles with links
 */
?>
<div id='flickrgallery'>
  <div id='flickrgallery-description'><?php print $description; ?></div>
  <div id='flickrgallery-albums'>
    <?php foreach ($albums as $key => $album) : ?>
      <div class='flickr-wrap'>
      <div class='flickr-image-link'>
        <?php print $album['image_link']; ?></div>
        <div class='flickr-title-link'>
        <?php print $album['title_link'];  ?></div>
        <div class='flickr-total'><?php print $album['total'] . t(' Pictures'); ?></div>
      </div>
    <?php endforeach; ?>
  </div>
</div>

```

It would be great to call the code for collapsiblock - thanks for any ideas here!

# Answer
i'm pretty sure all the core js and css files should handle both the collapsing and styling of the fieldset. you could simply add the fieldset into your code. however, if it is not added in by default for some reason you can use the following addition to your function code.

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

```

Below should be an opened fieldset example.

```
<div id='flickrgallery'>
  <div id='flickrgallery-description'>
    <?php print $description; ?>
  </div>
  <div id='flickrgallery-albums'>
    <?php foreach ($albums as $key => $album) : ?>
     <fieldset class=" collapsible collapsed">
     <legend><span class="fieldset-legend">More Info</span></legend>
      <div class="fieldset-wrapper">
       <div class='flickr-wrap'>
        <div class='flickr-image-link'>
         <?php print $album['image_link']; ?>
        </div>
        <div class='flickr-title-link'>
         <?php print $album['title_link'];  ?>
        </div>
        <div class='flickr-total'>
         <?php print $album['total'] . t(' Pictures'); ?>
        </div>
      </div>
    </div>
   </fieldset>
  <?php endforeach; ?>
 </div>
</div>

```

To have it closed simply add `collapsed` to your class like `<fieldset class="collapsible collapsed">`
> 4 votes

---
Tags: theming
---


title: Flexible drupal content-types

text:
# Question
Title: Flexible drupal content-types
Okay it might sound a little weird for me to ask a question about dynamic content-types seeing as that's what drupal is all about.. however I'm wondering if there is a preferred method to do a page template that will allow you to add hooks in to activate modules within the page.

for example

if I had a simple 2 column layout w/ main content and right rail next to eachother. would it be feasible to create a template that would take an argument (lets say something you can put in the description) like "$rightRail = twitter;" and then the page renders w/ a twitter module in the right rail?

I hope that makes sense. I'm running into an issue where we have a bunch of pages that look similar, except the rightrail has a very different information in terms of modules, etc... and I wanted to see what the best way to unify my template would be.

Right now the team is creating a new content type and page template for each type... and I don't like that.

thanks guys.

# Answer
I am thinking you are wanting to learn more about blocks. You could, for example, have a block that output an iframe/html/whatever widget. In the blocks hooks, you can use all sorts of information to decide when to display it it, eg what page/url, what type of node, etc. So, for example with twitter, you could grab information/fields from the node it is being displayed next to and customize it appropriately.
> 1 votes

---
Tags: theming
---


title: block visibility snippet restrict path

text:
# Question
Title: block visibility snippet restrict path
I use the following snippet to restrict who can see a block inside admin pages. Can you help me add the restriction of a path /cart\* for non admin users into this snippet?

```
if (user_access('access administration pages')) {
  return FALSE;
} else {
  return TRUE;
}

```

# Answer
I am assuming the logic is:

```
Display this block only on pages with a path beginning with cart/*,
And only when the user has `access administration pages` permission

```

If so....

```
if (arg(0)=='cart' && arg(1) && user_access('access administration pages')) {
  return TRUE;
} else {
  return FALSE;
}

```

If you want it displayed on path `cart` all by itself as well, just remove the `&& arg(1)` from the above and then it will work on `cart` in addtion to `cart/foo` and `cart/foo/bar` etc.

If, however, you want it only on `cart/oneargumentonly`, you can add in `&& !arg(2)`.

ADDITION/CORRECTION:

```
if (user_access('access administration pages') || (arg(0)=='cart' && arg(1))) {
  return FALSE;
} else {
  return TRUE;
}

```

while return FALSE if the user can `access administration pages` regardless of the path OR the path is `cart/*` regardless of any permissions.

So, if my logic is right now, if the user can `access administration pages` the `if` is "short circuited" and returns FALSE. Otherwise, if the user doesn't have this permission, it continues on and if the path is `cart/*` it returns FALSE. Otherwise, since we already know the user doesn't have the `access administration pages` permission it returns TRUE for any other path.

FINAL?

```
if (user_access('access administration pages') || arg(0)=='cart') {
  return FALSE;
} else {
  return TRUE;
}

```
> 1 votes

# Answer
This is to hide the block in cart/\* for non administrator roles.

```
if(stristr(current_path(),"cart/") && user_access('access administration pages')) {
  return TRUE;
}
else {
  return FALSE;
}

```
> 0 votes

---
Tags: blocks
---


# Question
Title: Sorting a view basing on the value of a boolean field
I have a content type X. A view is used to display this content type (X), as a table. The content type has a field called "Preferred" which contains boolean values. I need to sort the table so that the "Preferred:true" items display at the top of the table.

How can I achieve it?

# Answer
Add a new `Sort Criteria` sorter that sorts based on that field. Make sure it's at the top of your list of sort criteria.

If you don't want there to be a column for it in the table, click "exclude from display" in the field settings.
> 2 votes

---
Tags: views
---


# Question
Title: How to make a panel page the default local task
I've got a custom module providing local tasks like entity/%/edit and I'm trying to get entity/% to show up as the default local task. entity/% is defined as a Panel Page using the panels module. How do I do this? Whenever I change the menu type to "local task" or "menu tab" (or "default menu tab") the local tasks disappear from the display. This is in Drupal 7.14 with ctools 7/x-1/0

# Answer
> 3 votes
I was eventually able to get this to work. The page needed to be a "default menu tab" with the path `entity/%/view` or similar. With that, `entity/%` loads the path `entity/%/view` and all of the tabs show up as expected. This turned out to be more a problem with my understanding of default local tasks than anything else.

---
Tags: panels, routes
---


# Question
Title: Steps to Create a copy of a Drupal 7 website using cpanel?
I want to create an exact copy of an existing drupal 7 website in a subdomain. What steps should I take to do this using just cpanel?

# Answer
Here are the steps I would take in cloning the site. First, Create the subdomain. Then copy all the files from the live site to the subdomain. Then I would back up the database. Create a new database and import the backup into that. Assign the user from the first database to the second one. Then change the settings.php file to read from the second database. Also, if you have a base url set in settings.php you would need to change that as well. Hope that helps.
> 1 votes

# Answer
if the site is coming from another cpanel, there are export/import features for entire sites.

otherwise there's no cpanel specific way to move a drupal site that I am aware of.
> 0 votes

---
Tags: 7
---


# Question
Title: Is It Possible To Show One More Views In Homepage
I have created some Views to show in Home page. I have successfully installed one View in my homepage but i really can't understand is it possible to show one more Views in Homepage. If it possible then please take a time to describe it.. Thanks

# Answer
In Drupal 7, you should create a "block" display for the views you want to show, by selecting "Add" in the view config page.

When you save the view block, the corresponding blocks will show up in the `/admin/structure/block` administration page and you can add it to any page you want.
> 2 votes

# Answer
If you have it set up as a Page display, then no, not really -- those are designed to show one view at a time, though you can probably install Views Field View and then add one of those to the footer if you're set on that.

However, the simpler route is to just create a Block from that view and add it to pages that way. Click the Add button near the word "Displays" when editing a view. Then you can drag and drop them in admin/structure/block.

To set it only on the home page, in admin/structure/block, click Configure next to the Views block in question. Under Pages at the bottom, click "Only the listed pages" and put "" in the text area.
> 1 votes

# Answer
Another way is to use panels you setup your panel structure and then add the views this give you the layout you want with minimal effort.
> 0 votes

---
Tags: views, nodes
---


# Question
Title: How to turn off "<em class="placeholder"> </em>" surrounding vars in the output of t()?
In my module I display a menu inside a block using `drupal_render(menu_tree('my-menu'))`.

In the output the variables printed with `t()` are surrounded by `<em class="placeholder"> </em>`.

```
Drafts <em class="placeholder">(4)</em>
Inbox <em class="placeholder">(2)</em>

```

How do I turn this off?

# Answer
> 14 votes
There is actually an excellent comment in the documentation for this. Pasting here for completeness

---

There are three styles of placeholders:

`!variable`, which indicates that the text should be inserted as-is. This is useful for inserting variables into things like e-mail.

```
$message = t("If you don't want to receive such e-mails, you can change your settings at !url.", array('!url' => l(t('My account'), "user/$account->uid")));

```

`@variable`, which indicates that the text should be run through check\_plain, to escape HTML characters. Use this for any output that's displayed within a Drupal page.

```
$title = t("@name's blog", array('@name' => $account->name));

```

`%variable`, which indicates that the string should be HTML escaped and highlighted with theme\_placeholder() which shows up by default as emphasized.

```
$message = t('%name-from sent %name-to an e-mail.', array('%name-from' => $user->name, '%name-to' => $account->name));

```

---
Tags: 7, routes
---


# Question
Title: Other related content block using taxonomy
I have a content type call "procedure" and a taxonomy vocabulary call "services". I was able to build a block using Views that will show me all the related nodes sharing the same term from the vocabulary "services".

Now, I want to build a block showing "other procedures" that will list the nodes not sharing the same term, but having terms from the same vocabulary "services".

Note: in the first block I use the "Has term ID" argument and the "NID" argument.

I don't see how can I "negate" an argument. What am I missing?

# Answer
> 4 votes
I finally figured it out.

1. Add the fields to your view (title, body, etc)
2. add a relationship to "Taxonomy terms on the node" (do not check required)
3. add the arguments (now contextual filters) the "Taxonomy term: Term ID" (use relationship)
4. set "Provide default value" to "Taxonomy term ID from URL"
5. uncheck (to save on the load, optional) "Load default filter from term page"
6. check "Load default filter from node page, that's good for related taxonomy blocks"
7. set the "Limit terms by vocabulary" and pick the vocabularies
8. select "Filter to items that share any term"
9. Scroll down to the "More" section and check "exclude" that way all TIDs will be shown, but the one on the argument.

**Note:** I also added the exclusion on the NID of the node where I am showing the block with the other related nodes tags with terms from the same vocabulary.

Thank you.

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


# Question
Title: Views: Limit amount of a node type by percentage
I have a view showing nodes of two different types sorted by date. I want to limit the maximum number of nodes shown of the one type by, say, 25% percent of the total nodes per page.

How would I go about that?

# Answer
This might be a job for \_views\_pre\_render(). In it, you can go through your views results and modify them to your module's content. The issue here is creating a view result big enough to make your percentages work. For example, let's say you want to have that view of 4 nodes, but only 1 of which is of a certain type. Since you are sorting by date, if the first 4 are all of that type, you grab one but need to keep looking for 3 of the other type.

In a dull ax approach, you could, though, create a view that returned 100, or however many is reasonable on your site based upon what you actually see re mix of nodes, of both types sorted by date and then do something like:

```
function YOURMODULE_views_pre_render(&$view) {

  if ($view->name=='NAMEOFTHEVIEW') {

    //  drupal_set_message('<pre>' . print_r($view->result[0], true) . '</pre>'); // just the first row
    //  drupal_set_message('<pre>' . print_r($view->result, true) . '</pre>');    // all of them

    $max=1;    // hardcoded for example purposes
    $total=4;  // hardcoded for example purposes

    $new_result=array();

    foreach ($view->result as $result) {

      if ($max && $result->FIELDTHATHASTHENODETYPEINIT==NODETYPEWEARELOOKINGFOR) {
        $new_result[]=$result;
        $max--; $total--;
      } elseif (--$total) {
        $new_result[]=$result;
      }

    }

    $view->result=$new_result;

  }

  // any other views_pre_render()ing here

}

```

which if my logic gene is in gear today will cycle through your view results and pick out at most `$max` nodes of one type and then fill up `$new_results` up to `$total` with the rest of the view results and then replace the results of the view with that.

The issue, again, is that if all the results are of one node type, or there aren't enough of the other node type to fill up `$new_result`, you will have less than `$total` results returned.

(One or both of the drupal\_set\_message()s will/might be helpful for figuring out FIELDTHATHASTHENODETYPEINIT. If there isn't one in your view already, you can put one in and then not display/hide it if necessary.)
> 2 votes

# Answer
A simple way will be to:

1. create a view that will show X amount of 1 type of nodes that is equivalent to the 25% of the total nodes you want to display.
2. Then add an attachment (not EVA) view and attach it after the first one, but overwrite the filter indicating the content type selected for the attachment view only.
3. Repeat the step 2 as many times as needed to show the 100% of the total nodes from 25% of different content types.

**Note:** if you add footer and header HTML or text to the main view when adding the attachment view they will be copy over, but you can overwrite them so they will not show.

**End result width a limit of 4 node will be like:**

1. Node title (content type A) {main view}
2. Node title (content type B) {attachment view 1 =\> attached after main view}
3. Node title (content type C) {attachment view 2 =\> attached after attachment view 1}
4. Node title (content type D) {attachment view 3 =\> attached after attachment view 2}

Thank you.
> 2 votes

---
Tags: views
---


title: How to add additional url parameters?

text:
# Question
Title: How to add additional url parameters?
I would like to know how I can include additional URL parameters to a given link? ie: 'news?pid=3'

```
<?php
print $path='news?pid=3';
?>

```

This returns page not found error as the '?' is getting printed as %3F.

# Answer
> 13 votes
If you are using `l()`, you would do something like this to create news?pid=3.

```
l('Link Text', 'news', array('query' => array('pid' => '3')));

```

If you have other query parameters, you can add them in like this:

```
l('Link Text', 'news', array('query' => array('pid' => '3', 'foo' => 'bar')));

```

and that would create `news?pid=3&foo=bar`.

More information on `l()` here and `url()` here.

---
Tags: uri, navigation, 7
---


# Question
Title: Drupal 7.14 - grouping site links on search engines
I am trying to get my sites links, ie. about us, to appear as sublinks of the sites main page. For eg. When you google Drupal, the Downloand & Extend as well as Modules links appear grouped under the main Drupal.org link.

Is there a module that can do this? Thanks in advance.

# Answer
> 2 votes
These are generated by google, not by any module inside of drupal. googling 'sitelinks' will show you more information about how google creates them for popular sites.

http://support.google.com/webmasters/bin/answer.py?hl=en&answer=47334 from google is a good start.

---
Tags: 7
---


# Question
Title: All available variables returning node ID
I am trying to define a custom field in D7 view, and I used views\_php. Here few variables are available as field tokens, but while using it inside the code, it doesn't return its original value, but does the node id.

Available variables:

* $view: The view object.
* $handler: The handler object.
* $static: A variable that can be used to store reusable data per row.
* $row: Contains the retrieved record from the database (e.g. $data-\>nid).
* $row-\>nid: Content: Nid
* $row-\>field\_twitter\_page: Content: Twitter Page
* $row-\>field\_facebook\_page: Content: Facebook Page
* $row-\>php: Global: PHP
* $data: Contains the retrieved record from the database (e.g. $data-\>nid).
* $value: Value of this field.

I need to fetch the value of "$row-\>field\_facebook\_page"; so I wrote:

```
<a href="<?php print $row->field_facebook_page; ?>"Like</a>

```

When I click on the "Like" link, the given URL is empty. When I print the variable, I get the node ID.

What am I doing wrong?

# Answer
Start with print\_r to see what's available:

```
<pre>
<?php print_r($data); ?>
</pre>

```

You will likely end up using $data, something like:

```
$data->_field_data['nid']['entity']->field_facebook_page['und'][0]['value']

```

If that doesn't work, take a look at http://drupal.org/node/1140896#comment-5945164
> 3 votes

# Answer
Thanks Keva. It works!

```
<?php
$node = node_load($row->nid); //loads the entire node values

$fburl = $node->field_facebook_page;
$fburl1=$fburl['und'][0]['value'];

$twurl = $node->field_twitter_page;
$twurl1=$twurl['und'][0]['value'];
?>

```
> 0 votes

---
Tags: 7, views
---


title: "Undefined index: preview_image_style"

text:
# Question
Title: "Undefined index: preview_image_style"
I have this error message, which I know is related to the multiupload\_filefield\_widget module. If I disable this module, the message disappear.

> Notice: Undefined index: preview\_image\_style in `image_field_widget_process()` (line 381 of /Applications/MAMP/htdocs/my-site.com/modules/image/image.field.inc).

I found this issue\] which mention this message but isn't fixed yet.

How can I solve this?

# Answer
> 1 votes
The error message doesn't show up if you go to the image field settings and, under *Image preview style*, select a value that actually exist or *None*. For some reason, there are several values in that field that don't match with any file in the filesystem; when the code checks this, it finds no such version of the image and emits an error.

---
Tags: media
---


# Question
Title: Template file not recognized when moved to module theme folder
I have a template file in my custom module folder which I am using to theme a form. Everything works fine when the template file is in the root of my custom module folder. However, I would like to move this template file to another sub-folder in my custom module folder, so that I can basically put all the template files in one folder. My directory structure is such that in the root of the my custom module folder I have (/sites/all/modules/mycustommodule):

mycustommodule.module mycustommodule.info mycustommodule.install mycustommodule\_admin.inc

In /sites/all/modules/mycustommodule/mycustomthemes: mycustommodule-example-form.tpl.php mycustommodule-example2-form-tpl.php

This is my hook\_theme:

```
'mycustommodule_example_form' => array(
  'template' => 'mycustommodule-example-form',
  'file' => 'mycustommodule_admin.inc',
  'render element' => 'form',
),

```

I would like to know what I would need to do to make the path clear to Drupal that the template file is in that sub-folder. Thanks.

# Answer
> 4 votes
Try using `'template' => 'subfolder/mycustommodule-example-form'`.

# Answer
> 1 votes
or you can move free to your theme's templates directory. Drupal seeks tpl files recursively inside theme directories. you may store your mycustommodule-example-form.tpl.php to

```
mytheme/templates/mymoduletemplates/mycustommodule-example-form.tpl.php

```

or

```
mytheme/templates/mycustommodule-example-form.tpl.php

```

but this will not work for another theme

---
Tags: theming
---


# Question
Title: Can I use the Services module without coding skills?
I'd like to create an xmlrpc endpoint to import (add, update, delete) users from one Drupal site to another and believe that the Services module is the right tool for the job. However, by reading the documentation and looking at the screencasts out there, it seems to me that it requires some coding skills (like the Migrate module) in order to get the most out of this module.

I'd like to know if I could import my users with this module without any coding skill or if it requires more developers skills.

# Answer
Using migrate and services are for separate use cases IMO.

I'd use Migrate for a one-off or periodic import and use Services for RESTfully add/update/deleting one at a time.

The services module includes integration with the user module and you can pretty much administer/point and click to get an xmlrpc endpoint with the user resources added.

You'd have to write a bit of code on the first site though, you might use a user hook http://api.drupal.org/api/drupal/modules!user!user.api.php/function/hook\_user\_insert/7 (or update, delete etc) and then use the data to make a http request to your other site http://api.drupal.org/api/drupal/includes%21common.inc/function/drupal\_http\_request/7
> 1 votes

---
Tags: services
---


title: Common Javascript File for all Themes

text:
# Question
Title: Common Javascript File for all Themes
I have a multi-site installation using **domain access module** and each sub-domain has its own theme. I have a javascript file which is common to all the themes. Right now I've placed the js file inside all the themes folder. Is there a way to place the js file in a common location so that all themes can share it ? Can I use **Libraries API** module for this purpose ?

# Answer
Yes, you can use the Libraries API for this. The docs explain all of this fairly well. This is best for things that change infrequently.

For my custom Javascript libraries (which I work on continuously), I make module with an instance of hook\_library

```
function mymodule_util_library ()
{
    $path = drupal_get_path("module", "mymodule_util");

    $libraries = array();

    $libraries["mymodule_util"] = array(
        "title" => "MyModule Javascript Utilities",
        "version" => "0.0",
        "js" => array(
            $path . '/UTIL.js' => array(),
            $path . '/UTIL.HTML5.js' => array(),
            $path . '/UTIL.COLOR.js' => array(),
            $path . '/UTIL.MATH.js' => array(),
        ),

        'weight' => -10,
    );

    return $libraries;
}

```

Put the module in "site/all/modules" so all of your sites can see it, then enable it on the sites you need.

Then, wherever you need these JS libraries, you use drupal\_add\_library

```
drupal_add_library("mymodule_util", "mymodule_util", $every_page);

```

Typically, this is in a `hook_block_view` or a preprocess function.
> 2 votes

# Answer
**MPD's** solution is very elegant. But since I'm new to Drupal and I don't know anything about module development (yet), I used a different method. The method I used to solve this problem was :

1. I placed the js file in the main theme.
2. I made the remaining themes as **sub-themes to the main theme**.

I know this is not a very elegant solution but this is an easy solution for newbies in Drupal.
> 0 votes

---
Tags: theming, javascript
---