# Question
Title: Creating a Custom Formatter to replace a Link with an Icon / Image
I would like to replace links in a view I have created with icons. The links are dynamic(varying URLS) but will be be within 5 domains, eg: www.example.com/page7 www.example.com/page2 www.example2.com/page9 www.example3.com/page77

I would like to provide an Icon for each of the Domains which is applied to the link, so that clicking on the link takes the user to the URL(in a new window) and the text is hidden. I am aware of CSS image replacement technique but would like to use https://drupal.org/project/custom\_formatters to do this. I am also aware of https://drupal.org/project/image\_link\_formatter .

Using the Custom Links Formatter module would allow me to import/export, save, reuse and share this function.

# Answer
Just click on the **rewrite results option in the view** for the field you want the changes then just add the following :

```
 <a>href ="www.example.com/page7 "><img src="sites/all/...your image
    path"></a>

```

In a similar way you can add images
> 1 votes

# Answer
I think this module will help you on that http://customformatters.com/
> 0 votes

---
Tags: views, entities
---


# Question
Title: Count of users who are logged in per day
I searched to find a way to display the number of users who are logged in per day.

I want to display a chart using views for last month to show the login statistics of the website.

Any suggestion?

# Answer
Well in other to achieve this, you will be using a combination of modules.

Use the counter module for gathering that kind of statistics. Another option is to enable the statistics module in Drupal core

> Counter module counts how many visitors on your website. This module provides real time counting. All data saved to database.

And with google chart tools and the views module create a chart

> Display live data on your site using Google Chart Tools Google Chart Tools module provides a simple API to Build custom interactive SVG charts. The module contain an example module which demonstrate how this module can be use.
> 0 votes

# Answer
Could you not use Google Analytics and create a custom report in Google Analytics rather than your site?
> 0 votes

---
Tags: 7, views
---


# Question
Title: Disable breadcrumb on View in Drupal Commerce Kickstart
I am using Drupal Commerce Kickstart. I have been able to disable the hard coded menus by this advice \- specifically my own post at the bottom. Unfortunately this has not disabled the breadcrumbs on certain Views I have created. The Views in question show a single product. One of the views shows content: Full content and the other just draws in node fields from the products. I have a view that doesn't call in any products and this does not show the breadcrumb trail.

The breadcrumb must be hardcoded somewhere as it doesn't appear in the blocks area. It seems to be set to show the breadcrumb in the preface first area.

I would appreciate some advice on where to disable this breadcrumb. Failing that are there any tools in drupal that you can use to trace back to find where things (like the breadcrumb) are getting generated from?

# Answer
> 1 votes
Do you want to disable the breadcrumbs entirely? If so, with kickstart, you can do so at:

Appearance \> Settings \> Commerce Kickstart Theme \> Toggle advanced elements

It looks like commerce kickstart 2 uses the crumbs module (https://drupal.org/project/crumbs) to handle breadcrumbs (that's what I see in a local install from late July).

I haven't worked with Crumbs, but the documentation is here: https://drupal.org/node/1004394

---
Tags: 7, views, commerce, breadcrumbs
---


title: Assign tinymce to text formats

text:
# Question
Title: Assign tinymce to text formats
Just to start with I am trying to do this in code (installation profile), not in Drupal itself.

In my installation profile I create three text formats. Thanks to the drush make file tinymce is also automaticly installed. Now wysiwyg gives you the option to assign the editor to a text format. See image below how the option looks in Drupal.

Now I am wondering how I could change the 'No editor' to 'TinyMCE' in my installtion profile. After changing the option in drupal itself then the database changes to: (see image below)

What is the right way to do this and how can I change these module settings?

# Answer
> 0 votes
Looking through the WYSIWYG modules' code when saving the form, it implements:

```
db_merge('wysiwyg')
  ->key(array('format' => 'full_html'))
  ->fields(array(
    'editor' => 'tinymce',
  ))
  ->execute();

```

So that's what I suspect you'll need to put into your install profile

---
Tags: 7, wysiwyg, installation-profiles
---


title: Using Rules link to Un/Publish content

text:
# Question
Title: Using Rules link to Un/Publish content
Have anybody tried this?

Currently I am using Publish Content Module to Un/Publish contents, but the module doesn't support Confirmation action, if somebody hits Publish/Unpublish it just does the action straight away without asking confirmation.

I have been looking for the solution and Rules Link modules advertises it as its promo feature. Being a newbie I am not much aware of Rules power, so, any hint how could I Publish/Unpublish content with this would be very helpful.

So, far I tried by creating new **Link** which displays in my content type, When I click the link it asks for confirmation, but I couldn't figure out how to exactly Publish/Unpublish the content after that.

# Answer
> 3 votes
I solved a similar problem with the Flag and Rules modules. I created a flag called 'Published' for nodes and two rules that are activated when content is flagged/unflagged with this flag. These are my settings:

*'Published' flag*

* **Bundles:** Article
* **Display in entity links:** Display link as field
* **Link type:** JavaScript toggle

If you need the flag for (an)other content type(s) too, you simply have to check the box in the flag settings.

*'Published node' rule*

* **Event:** A node has been flagged, under 'Published'
* **Action:** Publish content: Parameter: Content: `[flagged-node]`

*'Unpublished node' rule*

* **Event:** A node has been unflagged, under 'Published'
* **Action:** Unpublish content: Parameter: Content: `[flagged-node]`

If you want to, you can add some extra actions to the rule (e.g. display a message).

---
Tags: 7, rules, nodes
---


# Question
Title: Populate article field based on user login
I am trying to accomplish a task with Drupal and I'm kind of stuck in how to implement this, so I'm wondering if anyone has any ideas or can at least point me in the right direction.

My company has over 60 locations. I am using Views to dynamically create a single "profile" page for each location. What I want is a way for the manager of each location to be able to log in and create articles for a kind of "What's Happening" section for their respective pages.

When the "manager" user accounts are created, I assign them a location based on a "Location" field that I added to the "User" content type.

What I want to do is add a field to the "Article" content type that is automatically populated with the "Location" of the manager that is posting the article. From there I can filter in Views to complete the page generation.

I could easily just add a "location" field to the Article content type that the user could manually select, but I know my users, and people will be creating articles for other sites and cause big mess for me to clean up. I'd like to have the "Location" field in the article automatically populate depending on the users' login.

Possible? If so, how?

# Answer
I dont think you need to assign the location for the user.

When a person adds a content that content is automatically assigned the author. So if manager A creates a content then its author field is populated with Manager A.

Now you can use this information in views.

If you are creating a view with all the information related to the location you could create a view with all the contents added by the particular person.
> 0 votes

# Answer
A quick solution to do this is implement a custom module that uses hook\_form\_alter to prepopulate the location field in the node creation form.

Here goes a similar question:

How to pre-populate fields on a node creation form based on fields from Profile2 module?
> 0 votes

# Answer
AFAIK there is not a standard way to do this. I recall writing a little module to make it possible to set a default value for a field which is a token string (and therefore dynamic), but I don't think anyone's written a public module along the same lines.

If you are up for a little coding you could write a form\_alter hook to achieve it, something like:

```
function mymodule_form_mycontenttype_node_form_alter(&$form, &$form_state) {
  if(empty($form['field_location'][LANGUAGE_NONE][0]['#default_value'])) {
    global $user;
    $account = user_load($user->uid);
    if(!empty($user->field_location[LANGUAGE_NONE][0]['value'])) {
      $form['field_location'][LANGUAGE_NONE][0]['#default_value'] = $user->field_location[LANGUAGE_NONE][0]['value'];
    }
  }
}

```

This code is not tested and may also need to some adjustment depending on the field type you have used for location.
> 0 votes

# Answer
Thanks for the help everyone. Using Alfred's post I was able to write some code that does the trick:

```
function smg_site_articles_form_alter(&$form, &$form_state){
global $user;
$account = user_load($user->uid);
if(!empty($form['field_site_news_article_location'])){
    $entity_node = node_load($account->field_user_location['und'][0]['target_id']);
     $form['field_site_news_article_location'] = array(
      '#title' => 'location',
      '#type' => 'select' ,
      '#options' => array(
          0 => t($entity_node->title)
        ),
      '#default_value' => $entity_node->title);

```

} }

This does what I need it to, however, I'm having another problem with the entity references that has cropped up. It can be see here HEREand if anyone can help I certainly appreciate it.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Is it bad practice to add markup to title or label fields?
The title might not make sense because I'm not sure what the correct wording is. But here is the example that explains what I mean.

I am creating a block view to go at the bottom of a node page that links in extra info relevant to the node (a users blog post on their profile page).

I titled the block `Blog Posts` but it was small and smashed up against the bottom of the content above it. So I tried calling it `<h4>Blog Posts</h4>` and it displayed as an `<h4>`. So I got more creative and now the title is `<br><hr><h4>Blog Posts</h4>`. It looks nice and works the way you would expect (with the html being rendered properly).

This method kind of seems like a bad hack, but inexperienced as I am with Drupal, I'm not sure why.

Is this bad practice, and why?

# Answer
> 2 votes
That'll work, but best practice is to theme it. The following answer describes how to theme a custom block: https://drupal.stackexchange.com/a/39270/23063

# Answer
> 1 votes
it is seriously bad practice... since you wrote markup in the title, it is stored in database. Storing unnecessary markups in database is BAD PRACTICE. That is why we have CSS for designing. Drupal also has jQuery which lets you change elements easily.

---
Tags: theming
---


# Question
Title: A ton of errors in panels content editor
There's a whole slew of errors at the top of my panels varient content editor page and I have no clue where to start in even fixing them. Most of these errors have been here since I started working and I have no clue how they got there or how to fix them. I've had this exact problem on more than one site.

Also, my content got messed up and it won't let me change settings or anything. It stopped letting me change things after I added the Responsive Navigation modules block.

The theme I'm using is aurora and all it's suggested modules:

* Magic
* HTML5 Tools
* jquery update
* modernizr
* blockify
* borealis suite
* fences
* panels

The site is built on top of the Bear Distro.

Attached is a picture of what I'm looking at.

# Answer
> 2 votes
Known CTools bug - see https://drupal.org/node/1991496 and https://drupal.org/node/1925018

Fixed in http://drupalcode.org/project/ctools.git/commitdiff/280ccd0 and the fix is available without patching if you use 7.x-1.x-dev.

---
Tags: panels, theming
---


title: How do I change the primary key?

text:
# Question
Title: How do I change the primary key?
I have created an update that adds a fields to an existing database table. I would like to add that field to the list of primary keys already defined. How do I do this? Do I need to execute the following code?

```
db_drop_primary_key('table_name');
db_change_field('table_name', 'field_name', 'field_name',
array('type' => 'int', 'not null' => TRUE, 'unsigned' => TRUE),
array('primary key' => array(...list of field names...)));

```

I essentially recreate either an existing field or the new one I just added. Is there a simpler method where I can just add the field name to primary key list?

# Answer
> 14 votes
Very close. In a hook\_update\_N:

```
// Drop all primary keys.
db_drop_primary_key('table_name');
// Add primary keys.
db_add_primary_key('table_name', array('field_a', 'field_b'...);

```

See db\_drop\_primary\_key and db\_add\_primary\_key for details and links to usage.

---
Tags: 7, database
---


title: Why is the region in Drupal blank?

text:
# Question
Title: Why is the region in Drupal blank?
I my .info file I have this:

```
regions[footermenu] = Footer Menu

```

The region--footer.tp.php has this:

```
<?php
    print render($page['footermenu']);
?>

```

I've placed a menu block in the "Footer Menu" (it shows up under structure-\>blocks). However, it's blank. If I place the block in region I know works the menu content is seen fine. Any idea why the region wouldn't see the block?

# Answer
> 1 votes
as your question doesn't have any proper explanation, people most likely cant help you. but I can guess that what you are doing wrong is that you make a `region--footer.tpL.php` file (you missed the L in the end), you also need to render it on the page you want it there to be, so practically it wont show you anything since its not rendering at all.

my suggestion is forget about `region--footer.tpl.php` and add

```
<?php
    print render($page['footermenu']);
?>

```

right into your `page.tpl.php` or any other theme hooks you might want it there.

by the way a very rookie mistake is that you already done everything right but after editing your `.info` file you forgot to clear the cache in `admin/config/settings/development/performance`

---
Tags: 7, blocks, theming
---


# Question
Title: Limit Teaser to display only the first value of a Field
I have a Content Type with an Image Field. This field will typically be populated with 0 to 4 values. By default the teaser for this Content Type outputs all 0 to 4 images. How can I adjust the Teaser to only display the first image?

# Answer
Create a custom module, replace `MODULENAME` with the name of the module and `field_image` with the name of your field:

```
/**
 * Implements hook_entity_view().
 */
function MODULENAME_entity_view($entity, $type, $view_mode, $langcode) {
  if ($view_mode == 'teaser') {
    $entity->content['field_image']['#items'] = array_slice($entity->content['field_image']['#items'], 0, 1);
  }
}

```

See the hook\_entity\_view() documentation for more details.
> 12 votes

# Answer
No need to write custom code.

Try using Field multiple limit module.

> It allows you to go into the display settings for your content type and configure the teaser settings to display only a certain amount of values. You can even make it skip vales, for example if you want it to display values 2 to 5

.
> 12 votes

# Answer
If using a teaser template (ie: **node--CONTENT-TYPE--teaser.tpl.php**), this works:

```
  <?php print render($content['IMAGE-FIELD'][0]); ?>

```
> 4 votes

# Answer
I used hook\_field\_extra\_fields() and hook\_node\_view() to create a new field to display the first image so that I wasn't tampering with the original images field.

hook\_field\_extra\_fields() initialises the new field which will appear on the manage display tab of your node type.

```
function HOOK_field_extra_fields() {
  $extra['node']['NODE_TYPE'] = array(
    'display' => array(
      'primary_image' => array(
        'label' => t('Primary Image'),
        'weight' => 0,
      )
    ),
  );
  return $extra;
}

```

Then hook\_node\_view() is used to add the first image to be the content of your new field.

```
function HOOK_node_view($node, $view_mode, $langcode) {
  if($node->type == 'NODE_TYPE' && $view_mode == 'teaser') {

    //make sure there are images
    if(!empty($node->field_images)) {
      $node->content['primary_image'] = $node->content['field_images'][0];

      //hide the original field with multiple images
      hide($node->content['field_images']);
    }
  }
}

```

NOTE: If you have display suite enabled you can do this in the manage display tab.
> 1 votes

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


# Question
Title: Hook or rules event to identify payment failure in Drupal commerce
Is there any hook or rules event that will help to catch the payment failure in Drupal Commerce?

Thank you

# Answer
There is no direct hook or event, but essential to payment transactions in Drupal Commerce is that they should be created for every *attempted* transaction, not just complete ones. This means when a payment fails, a payment transaction will still be created for your order. Thus you can hook into the payment transaction creation process (or use Rules on the related event) to look for failed transactions based on the transaction status.
> 2 votes

# Answer
Try using the `hook_commerce_payment_transaction_status_info()`

Here is a link to the api and link to documentation,
> 0 votes

---
Tags: 7, hooks, rules, commerce
---


# Question
Title: What is the maximum number of elements allowed in a form?
I have googled and binged and yahooed this question but can't seem to find an answer. I was working on a form that included over 800 fields but the form's submit function would never execute. After I pared the form down, the submit function ran. So now I'm curious if there's an actual built in maximum number of elements.

# Answer
> 10 votes
I think, the issue is related to Server configuration, not with Drupal.

There is `max_input_vars` variable in `php.ini` which define the maximum number of variable form elements that can be submitted to a single page.

> The “max\_input\_vars” setting in the php.ini file is a relatively new option starting last year from PHP 5.3.9. It allows you to control the maximum number of form elements on a page. Some webpages have a large amount of forms/fields for administrative or page configuration purposes. In those cases, we need to increase the number of this value in order to properly view those pages.

There is also `post_max_size` variable in `php.ini`.

> `post_max_size` sets max size of post data allowed. This setting also affects file upload. To upload large files, this value must be larger than `upload_max_filesize`. If memory limit is enabled by your configure script, `memory_limit` also affects file uploading. Generally speaking, memory\_limit should be larger than `post_max_size`. If the size of post data is greater than `post_max_size`, the `$_POST` and `$_FILES` superglobals are empty.

You can check the this for more details.

---
Tags: 7, forms
---


# Question
Title: Cannot configure settings for menu breadcrumbs
I installed and enabled the Menu Breadcrumb module, however I cannot access or find the configuration settings page (even when I click the configure link on the modules page). I'm currently using the STARTERKIT from Zen theme.

Is there anything else I need to enable to get it to work?

# Answer
You should be able to find it at `/admin/config/user-interface/menu-breadcrumb`.

If nothing appears then clear your menu caches and try again, but it's definitely there in the code.

If that doesn't fix it, then this is a problem for the issue queue I'm afraid.
> 1 votes

---
Tags: routes, breadcrumbs
---


# Question
Title: Does Multiupload Filefield Widget for Drupal provides a Form API element?
I have a form in on of my Drupal page that uses Multiupload Filefield Widget to upload multiple images at once.

I want to alter the functionality of this Multiupload Filefield Widget from my custom module using hook\_form\_alter.

At first I thought It will be a `managed_file` widget. But it is not.

Is there a way to do it?

# Answer
Yes it does, as defined in `multiupload_filefield_widget_element_info()`. The element type is `mfw_managed_file`, so you can use something like:

```
$form['multi_upload_element'] = array(
  '#type' => 'mfw_managed_file',
  '#title' => t('Some file'),
  '#upload_location' => 'public://',
);

```
> 2 votes

---
Tags: forms, files
---


title: Views show referencing nodes

text:
# Question
Title: Views show referencing nodes
I have a custom content type called "questions" and few others , "A", "B","C" . (the naming is irrelevant, actually). Each one of the following content types "A","B","C" has a field that is referencing to a particular node with content type "question".

What I would like to do is to display in a View all questions and next to each question, the titles of referencing nodes(with links to the node).

What approach should be taken ?

# Answer
You could do the following.

1. Add the title node with link.
2. Filter it with Content Type A B and C (Which all content types you want to display.
3. Add the reference field in Content Type A B and C
4. Group by the Reference Field.
> 2 votes

---
Tags: views, nodes
---


# Question
Title: D7 Custom Module: Turning tabs into contextual links
Created a module (D7) that turns every nodes edit tabs into contextual links instead. Works great... But on the first initial load to the page I get a warning. Disappears after I refresh once. Then it comes back around surfing to another page and back again.

```
Warning: Invalid argument supplied for foreach()
in mytheme_contextual_contextual_links_view_alter()
line 19....

```

Driving me bonkers. Code below. It's having an issue with my `foreach($tabs as $tab)...`

```
  function mytheme_contextual_block_view_system_main_alter(&$data, $block) {
      if (user_access('access contextual links')) {
        $tabs = menu_primary_local_tasks();
        $data['content']['#contextual_links']['block'] = array(
          'admin/structure/block/manage',
          array('system', 'main'),
        );
      }
  }

  function mytheme_contextual_contextual_links_view_alter(&$element, &$items) {
      if (arg(2) != 'edit' && arg(3) != 'edit' && arg(0) != 'admin' && arg(1) != 'add') {
        if (isset($element['#element']['#block']) && $element['#element']['#block']->delta == "main") {
          $tabs = menu_primary_local_tasks();
          foreach( $tabs as $tab ){
              $element['#links'][$tab['#link']['path']] = array(
                'title' => $tab['#link']['title'],
                'href' => url($tab['#link']['href'], array('absolute' => TRUE)),
              );
          }
        }
      }
  }

  function mytheme_contextual_preprocess_page(&$variables) {
      if (arg(2) != 'edit' && arg(3) != 'edit' && arg(0) != 'admin' && arg(1) != 'add') {
        $variables['tabs']['#primary'] = array();
      }
  }

```

# Answer
Place the for loop inside an if statement

```
$tabs = menu_primary_local_tasks();
if($tabs)
{
      foreach( $tabs as $tab ){
          $element['#links'][$tab['#link']['path']] = array(
            'title' => $tab['#link']['title'],
            'href' => url($tab['#link']['href'], array('absolute' => TRUE)),
          );
      }
}

```
> 1 votes

---
Tags: 7, routes, navigation
---


title: Lightbox2 module does not allow hover?

text:
# Question
Title: Lightbox2 module does not allow hover?
I am using the Lightbox2 module in Views to make a image larger on click. This works great, but I also want to show a preview of the image on mouse\_over. I also use hover\_preview module, but I can't seem to use both module with a single view.

Here's a example of what I want:http://gochicorgohome.com/shop/15975,242,49668 (this link is ironic because its Hover\_Preview module's example and shows what Lightbox does as well).

So How do I get/find a module that will enlarge image on click AND preview and image on mouse\_over like link above.

EDIT. I am using the REWRITE OUTPUT option in order for my image view to show the lightbox formatter effect.

UPDATE: Ok I figured it out: Rewrite However this outputs two images, no link, and "\> after the image. I'm guessing my syntax is wrong?

# Answer
I would install both module, set the Lightbox field format in your view, and then try to replicate the output used by the hover\_preview module. If you use the browser inspector you will notice that you need two images in top of each other and some classes assigned to them in order to work.

In your view, add those images fields and rewrite the results. See image attached. I hope it helps.
> 1 votes

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


# Question
Title: drupal 7 automatically create and populate a field reference per node after node creation
How can I automatically create multiple nodes (content type B) after creating the node (content type A), and then there was a relationship to the nodes (content type B) to the node (content type A) Thanks

# Answer
You can check out the following module

**Autocreate Node Reference**

> Autocreate Node Reference adds a node reference field and automatically creates the referred node by cloning a template node.
> 0 votes

---
Tags: nodes
---


# Question
Title: Views multi field exposed free-text filter/search
I have a view displaying some course listings. I want to enable a free-text search on some of the fields. Some of these fields will be a term-reference type, and some will be text fields.

What's the best way to enable this type of search functionality? I've stumbled upon this: http://drupal.org/project/search\_api but wanted someone else's opinion.

# Answer
You could do that without the help of the search filters.

On my Drupal instance I have Views 7.x-3.7 there is a filter `Global: Combine fields filter (exposed)` This lets me add multiple fields and then enables users to `search on selected fields` using a single filter.
> 3 votes

# Answer
If you enable the core Search module, and then wait for the site to be fully indexed, you can add the views filter:

```
Search: Search Terms
The terms to search for.

```

When this filter is exposed, it will provide a free-text search box which filters items in the view by any of their indexed keywords.
> 0 votes

# Answer
For the "Search: Search Terms", you also have to enable "Use AJAX" under Advanced -\> OTHER in your view for the searchbox to be visible.
> 0 votes

---
Tags: views
---


# Question
Title: How do i add custom jquerry script to omega theme?
I found this code:

```
 (function ($) {
 Drupal.behaviors.betterExposedFiltersExpandCollapseNested = {
   attach:function (context, settings) {
     // first collapse the children
     $('ul.bef-tree-child').css('display', 'none');
     $('.form-checkboxes.bef-select-all-none li').has('ul').once('bef-tree', function () {
       $(this)
         .find('input.form-checkboxes:first')
         .click(function() {
           $ul = $(this).parents('li:first').find('ul');
           if($(this).attr('checked')) {
             $ul.slideDown('fast');
           }
           else {
             $ul.slideUp('fast');
           }
         })
     });
   }   } }) (jQuery);

```

for expandable hierarchy filters from here

I have no idea how to put it in my theme, what files and how to edit. Anyone could tell me the steps to do that?

# Answer
> 3 votes
There are (at least) two ways to add a JavaScript file to an Omega subtheme. The Omega Theme Documentation Handbook adds it as a library that can then be toggled on in the theme settings. I tend to use drupal\_add\_js, with a slight workaround to point it to the subtheme (more about why that's necessary in the Docs issue queue).

## **As a library**

First, add the file to a js folder in your theme. The path to mine was sites/all/themes/webbykat/js/webbykat.js.

Second, add a reference to the new file in your theme's .info file. During this step, you'll also add some identifying information for your new file, like a name and a description, as well as its weight. Here's what mine looked like:

```
libraries[MYTHEME_custom][name] = Some custom name
libraries[MYTHEME_custom][description] = Some custom description
libraries[MYTHEME_custom][js][0][file] = script.js
libraries[MYTHEME_custom][js][0][options][weight] = 15

```

Be sure to clear your cache after you update your .info file.

**Please note:** If you're adding more than one file, you'll need to up that number for each file - libraries\[MYTHEME\_custom\]\[js\]\[0\]\[file\] = script.js and then libraries\[MYTHEME\_custom\]\[js\]\[file\] = secondfile.js. Be sure to adjust it next to the weight as well. (Thanks, Screenack, for pointing that out in the comments.)

Third, now that the Omega theme is aware of your new file, formally inform Omega that you'd like to use it. Under Appearance \> Settings \> \[Theme name\], go to the Toggle libraries tab. Check the box next to the name of your file. Save.

## **With drupal\_add\_js**

In template.php, you might think you could use drupal\_add\_js to add it like this:

```
function MYTHEME_preprocess_page(&$variables) {
  drupal_add_js(path_to_theme() . '/js/script.js');
}

```

However, path\_to\_theme doesn't reference the active theme (more on that here), so we need a slight workaround. Instead, use the following:

```
function MYTHEME_preprocess_html(&$variables) {
  drupal_add_js(drupal_get_path('theme', 'MYTHEME') . '/js/script.js', array(
    'scope' => 'header',
    'weight' => '15'
  ));
}

```

Scope tells the function that the file should be called in the header or footer, and the weight tells it what order it should be called in relative to other files.

I prefer the two methods above because one is featured in the Omega documentation, and the other allows you to control what pages the JavaScript is called on if you want to (post on that to come). But as a developer friend pointed out, if you just want something quick and dirty to get a JavaScript file called on every page of your site, scripts\[\] = js/script.js in the .info file works too.

Source

# Answer
> 1 votes
You add custom stylesheets and scripts to an Omega subtheme by adding them to yourtheme.info and then (after clearing caches) enabling them in your theme's appearance settings.

Like so:

```
scripts[] = script.js

```

As mentioned in this comment on d.o.

There are also other questions on this site with useful answers.

# Answer
> 0 votes
you can use JS injector which offers many functions but puts code in sql, or learn how-to with that well-done page, which will lead you to the function drupal\_add\_js .

---
Tags: views, theming, javascript
---


# Question
Title: How do you configure a Drupal linux dev system for sending email?
My current dev system is a multi-site dual-boot windows/linux box with Apache 2.4/PHP 5.4.

In windows mode with a fresh install of D6 or D7, a verification email is properly sent when registering a new user. No contributed modules are required.

In linux mode (Ubuntu 12.04 LTS) the email does not work. I have tried using the ubuntu default (sendmail dummy?), **sendmail**, **ssmtp**, and **postfix** email packages with assorted configuration settings.

Most of the email packages seemed to have work from the command line.

With default or sendmail, a *Create new account* request causes the "wait" mouse-pointer to appear and remain like that for 30 secs or longer. The *"email has been sent"* message eventually appears but no email is ever received. With the postfix or ssmtp package installed, the same message appears within a second or two but no email is received.

I have searched for an answer on how to configure a Drupal linux system for email without much success.

The D6/D7 SMPT Authentication Support module solves this problem but it is a dependency that should not be necessary.

I don't have these problems running in Windows mode; never have in 3 years. I now have a shared NTFS partition so both modes use exactly the same code base.

# Answer
Here is another attempt to answer the *now questionable* question...

---

Drupal core uses the php mail() function by default. See /modules/system/system.mail.inc

## Context

Do you have a Linux based Drupal dev system? Does a fresh install of Drupal (6,7 or 8) appear to work? If an anonymous user attempts to create a new account, does it appear that an email is sent but NEVER received? Yes to all of the above?

A brief history. It was in the Fall of 2010 that I downloaded and installed this thing called Drupal (version 6). After creating a new account the system sent an email with a keyed link to set the new member password. I was impressed.

I was using a **Windows XP** laptop at the time. Mail systems are not my speciality but I had managed to get websites to send emails. The sum total of my expertise at the time was this -- I was using *some kind of SMTP thingy*.

In the Spring of 2013 I switched to Ubuntu 12 for Drupal development. I recently discovered that the linux configuration did not send a new user email. The Win system (Windows 7) works like it always has since the XP days - it just works.

Most of us use email systems managed by our ISP, employer, or internet offerings such as Hotmail or Goggle's gmail.

I have since discovered I configured an smtp relay. A Drupal call to mail() will relay the message (with authentication if necessary) to my preferred mail server.

## Windows install

On a windows (WAMP) system, there is a "window only" section in the php.ini file that allows the setting of a mail server.

## Linux install

A search for 'mail' using the Synaptic package manager revealed that the default **lsb-invalid-mta package** was installed (Linux Standard Base sendmail dummy).

Linux has many mail systems available, **sendmail, ssmtp, postfix, qmail exim** or **nullmailer**, to name a few. They can get complicated. Most everybody with any experience prefers something other than *sendmail*.

## Postfix

The **postfix** package seems to be the most popular. The trick here is to configure postfix as an SMTP relay. This means a call to mail() will relay the request to the mail server of your choice.

Here is a suggestion on how to configure your Drupal development system using postfix as an SMTP relay:

## Step 1 - Prepare system

Uninstall and remove each mail package that you have tried but have failed to get working:

```
sudo apt-get remove --purge [mail package that did not work]

```

Rinse and repeat as necessary. I have read somewhere that this is a good idea. If all goes well, *sendmail for dummies* (lsb-invalid-mta) will be left.

## Step 2 - Install postfix (again if necessary)

```
sudo apt-get update
sudo apt-get install postfix

```

## Step 3 - Configure postfix

**Cut and paste** the following code into your editor. Replace every occurrence of **mailserver:port** with something that works. Modify **username** and **password** accordingly.

*Note the 'myorigin' setting does not include a port number.*

You may then cut and paste these commands onto the command line. It is recommended that it be done in steps, *one line at a time*, just to see how things go.

```
# Open up a sudo session so you don't have to preface every
# command with 'sudo' - remember to exit when done!
sudo -s

```

The following commands work as s when logged in as 'root':

```
# postconf is a program that can modify the postfix config file /etc/postfix/main.cf
postconf -e 'relayhost = mailserver:587'
postconf -e 'myorigin = mailserver'

postconf -e 'smtp_sasl_auth_enable = yes'
postconf -e 'smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd'
postconf -e 'smtp_sasl_security_options ='

# Authentication -- Substitute mailserver, username and password here:
echo "mailserver:587   username:password" > /etc/postfix/sasl_passwd

# Protect this password file
chown root:root /etc/postfix/sasl_passwd
chmod 600 /etc/postfix/sasl_passwd

# update the sasl_password.db file using the new password file
postmap /etc/postfix/sasl_passwd

# Restart
service postfix restart

# and exit the sudo session
exit

```

## Step 4 - Test

If everything goes well, a variation of this command:

```
mail name@whatever.com

```

should work. You should be prompted for a Subject. After entering the subject line, follow with the body of the text (i.e. "Hello world!"). There is no prompt for "Body". I am not sure why.

Use Ctrl-D to complete the command.

Now check the email address for the message.

## Acknowledgements

Maybe I should acknowledge Google because I used it to find these links, but the search was exhausting. Here are some of the pages I bookmarked. Some of them are quite old.

http://developernote.com/2012/07/how-i-configured-sendmail-for-php-on-ubuntu-server-12-04/#comment-27377

http://www.howtoforge.com/postfix\_relaying\_through\_another\_mailserver

http://www.howtoforge.com/how-to-relay-email-on-a-postfix-server

http://lenss.nl/2009/01/making-php-mail-work-on-ubuntu-through-postfix/
> 2 votes

---
Tags: emails, configuration
---


# Question
Title: How can i integrate java application with drupal?
I a new to Drupal. As per my knowledge drupal is based on PHP. How can I get the contents from drupal and use in my java web application?

Is there any way to get the contents from drupal schema which I need complete information of drupal table structure, how contents get saved in tables?

# Answer
This is a very broad question so the answer can only be a broad one...

You can use the Services module to expose resources from your site to interested consumers:

> A standardized solution of integrating external applications with Drupal. Service callbacks may be used with multiple interfaces like REST, XMLRPC, JSON, JSON-RPC, SOAP, AMF, etc. This allows a Drupal site to provide web services via multiple interfaces while using the same callback code.

There's an Example of Java XML-RPC client with Drupal7 and Services 3.x, which (trust me) is the best documentation you'll be able to find.
> 6 votes

---
Tags: 7
---


# Question
Title: Executing jQuery code during form submission
I developed a module to show an "End" button on the node edit form, and it works fine.

```
function renew_form_alter(&$form, &$form_state, $form_id) {
  $form['actions']['property_endlease'] = array(
    '#type' => 'submit',
    '#value' => t('End'),
    '#access' => TRUE,
    '#weight' => 15,
  );

  return $form;
}

```

I want that, when users click on that button, some fields are changed from jQuery code.

I tried the following code, but it doesn't show any alert, even though the form is submitted.

```
jQuery('#edit-property-end').click(function (event) {
  alert('');
});

```

I want to submit the form after the jQuery code is executed.

Does anybody have an idea on how to do this?

Thanks

# Answer
Try this

```
   $form['actions']['property_endlease'] = array(
            '#type' => 'submit',
            '#value' => t('End'),
            '#access' => TRUE,
            '#weight' => 15,
            '#attributes' => array("onclick" => "javascript:test();"),

        );

```

and create a custom js

```
function test()  {
//your code
}

```

Hope it will work
> 1 votes

---
Tags: forms
---


# Question
Title: Update Entity Reference field programmatically
I'm kind of new to Drupal development and I'm a little lost on something I'm trying to do:

My company has several locations and I am developing a method whereby each location can have their own page on my company's website.

I want location managers to be able to log in and post news articles about their respective locations and have those articles appear on the appropriate location page.

I have content types set up for 'Location' and 'Site Articles'. 'Site Articles' has a 'Location' field that is a reference type back to Location.

In an effort to restrict the ability of various site managers to select a location that is not theirs, I am using hook\_form\_alter() to adjust the 'Location' entity reference in the 'Site Article' content type that reads what Site a manager belongs to in their User Account Settings, and adjusts the form so that ONLY the managers site shows up. That code looks like this:

```
function smg_site_articles_form_alter(&$form, &$form_state){
global $user;
$account = user_load($user->uid);
if(!empty($form['field_site_news_article_location'])){
     $entity_node = node_load($account->field_user_location['und'][0]['target_id']);
     $form['field_site_news_article_location'] = array(
      '#title' => 'location',
      '#type' => 'select',
      '#options' => array(
          0 => t($entity_node->title)
        ),
      '#default_value' => $entity_node->title);

```

The problem that I'm running into is when I save the Article, the "Location" entity reference does not get populated and I can't add Views filters to it the way that I want.

I'm assuming the problem lies with how I'm altering the 'Location' entity refernce field in hook\_form\_alter(), but I'm a little lost as to how I get the data updated correctly.

Can anyone help??

# Answer
> 2 votes
Fields in forms are fun, there's some info about those here

To summarise, the element you're looking to alter will be something like

```
$form['field_site_news_article_location'][LANGUAGE_NONE][0]['target_id'];

```

Rather than replace the whole thing it would be wiser just to replace the existing options array, but that'll need a small change as well.

Select options are key =\> display, so if you use `0` as the key, it won't match up with anything on the backend (namely a node ID in this case), and the form won't save properly. Similarly the `#default_value` is expecting the key rather than the node title.

Something similar to the following should do the trick:

```
...
$options = array($entity_node->nid => $entity_node->title);
$form['field_site_news_article_location'][LANGUAGE_NONE][0]['target_id']['#options'] = $options;
$form['field_site_news_article_location'][LANGUAGE_NONE][0]['target_id']['#default_value'] = $entity_node->nid;

```

# Answer
> 1 votes
I managed to get it working by changing

```
$form['field_site_news_article_location'][LANGUAGE_NONE][0]['target_id']['#options'] = $options;
$form['field_site_news_article_location'][LANGUAGE_NONE][0]['target_id']['#default_value'] = $entity_node->nid;

```

to

```
$form['field_site_news_article_location']['und']['#options'] = $options;
$form['field_site_news_article_location']['und']['#default_value'] = $entity_node->nid;

```

essentially removing the \[0\] and \['target\_id'\] and it sets the values and works perfect!

However, I don't understand why this works and the other way doesn't. Is there anybody that explain how this all works??

Thanks for help!

---
Tags: hooks, nodes, entities, forms
---


# Question
Title: i18n translate vocabulary field description
I want to localise vocabulary fields especially description field. Does it exist some function like `i18n_taxonomy_localize_terms( taxonomy_term_load($tid)` for `taxonomy_vocabulary_load($vid)`. Or maybe some different method.

Thanks

# Answer
You can localize the taxonomy description field out-of-the-box with the Entity Translation module. While Entity Translation can be used in combination with the i18n suite of modules, note that **you cannot use Entity Translation for taxonomy in conjunction with the i18n Taxonomy translation module; you must select one or the other.**

If you use Entity Translation, to translate the taxonomy term names you will also need the Title module.
> 1 votes

# Answer
I made simple function. I don't know is it properly but it do job for me. Where $lid Unique identifier of this string, you can find it on page Configuration » Regional and language » Translate interface, edit link.

```
function t_lid($lid,$lang){
    $translation=db_query('SELECT l.translation FROM {locales_target} l WHERE l.lid = :lid AND l.language=:lang', array(':lid' => $lid,':lang'=>$lang))->fetchField();
        return $translation;
    }

```

I hate to install module for one simple thing :)
> 1 votes

---
Tags: 7, taxonomy-terms, i18n-l10n
---


# Question
Title: trying to dynamically change drupal commerce order
I am trying to create a pane on the drupal commerce checkout page which will will give the user some options to change which product is in the cart. I want this done with ajax, without leaving the checkout page.

This is the code I have written so far:

```
  global $user;
  $product_id = 3;
  $order_id = commerce_cart_order_id($user->uid);
  commerce_order_delete($order_id); //delete the present order
  $newOrder = commerce_order_new($user->uid); //and create a new one
  commerce_order_save($newOrder);   //NEED?
  $product = commerce_product_load($product_id);
  $lineItem = commerce_product_line_item_new($product, 1, $newOrder->order_id);
  commerce_line_item_save($lineItem); //NEED?

  // Add the line item to the order using fago's rockin' wrapper.
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $order_wrapper->commerce_line_items[] = $line_item;

  // Save the order again to update its line item reference field.
  commerce_order_save($newOrder);
  commerce_cart_order_refresh($newOrder);

  return $form;

```

However, this code gives me an ajax error

> Failed to load resource: the server responded with a status of 500 (Internal Server Error) http://example.com/system/ajax

Am I making a code error? A Commerce error?

# Answer
Going out on a limb a bit...

There's no function called `commerce_new_order`, you probably mean `commerce_order_new()`

Same thing with `commerce_load_product()` and `commerce_product_load()`
> 1 votes

---
Tags: commerce
---


title: Can't use super user account

text:
# Question
Title: Can't use super user account
I have a Drupal 6 installation, and wanted to make some changes for the client. However, this fails, because as soon as I log in with the super user account it says:

> Access Denied: You don't have sufficient permissions to access this page

So I can't even log in using the super user account (uid 1). The password is already reset several times. The cache tables and session tables are emptied. What can I do?

# Answer
I hada look into my watchdog table. It said the sessions table was corrupted and needed to be repaired. So I did it, and after that I could login with the super user again. Thanks everybody for helping out, but it was something different this time.
> 2 votes

# Answer
It's highly possible its because of htaccess configuration of your drupal installation which is not ok with server's configuration.

I think it must be because of `+FollowSymLinks`, just edit htaccess in your drupal root and `sites/default/files` directory and comment the line that says:

```
Options +FollowSymLinks

```

and change it to:

```
#Options +FollowSymLinks

```

and if it still didnt work out try commenting out `Options -Indexes` as well.

by the way it's always good to check your server errors in `cpanel > error logs`
> 0 votes

---
Tags: 6, users
---


title: Migrate content of CCK fields

text:
# Question
Title: Migrate content of CCK fields
I need to transfer the content of a specific content type with CCK fields from Drupal 5 to Drupal 7.

What's the best and easiest and fastest way to do so?

# Answer
Once I had a same problem and after couple of hours testing/working with couple of approaches I figured out that the best way to deal with this is using views bonus pack module to get a CSV export file:

> This group of modules is sort of a recipe module that makes things easier by showing how to integrate some other modules as well as providing miscellaneous features that aren't distributed by Views itself. Sometimes these modules are only base recipes that will need to be themed and spiced up to fit your needs so be creative!

and import it via feeds module:

> Import or aggregate data as nodes, users, taxonomy terms or simple database records.
> 2 votes

# Answer
You should use Migrate module.

> The migrate module provides a flexible framework for migrating content into Drupal from other sources (e.g., when converting a web site from another CMS to Drupal). Out-of-the-box, support for creating core Drupal objects such as nodes, users, files, terms, and comments are included - it can easily be extended for migrating other kinds of content. Content is imported and rolled back using a bundled web interface (Migrate UI module) or included Drush commands

check out the other modules as given in LINK

Node import
Backup and migrate
Table wizard + Migrate

...
> 1 votes

---
Tags: 7, entities, migrations
---


# Question
Title: How can I create a variable with different values for each domain using Domain Access?
I have a numeric value that is unique to each domain (using Domain Access) on my site. I'd like to use the same variable name so I can use the same theme and display this value on all domains. Is this possible?

I'm currently defining the variable in a custom module, but I'm only storing 1 value. Can I alter the code in the custom module so that each domain can have it's own unique value for this variable?

UPDATE:

Adding the following when defining the variable in my custom module worked :D

```
'multidomain' => true,

```

I can edit the variable through admin/config/system/variable/edit/ and I get unique values across my domains stored in the variable\_store table. The problem I now have is that I want to create an admin form for getting/setting a bunch of domain variables and the usual variable\_get/variable\_set don't work...any thoughts?

# Answer
Ok, here is how I solved it...I hope this is the "right" way:

Define the variable, 'multidomain' being the import difference

```
function MODULENAME_variable_info($options) {

  $variable['social_media_link_twitter'] = array(
    'title' => t('Twitter', array(), $options),
    'description' => t('Twitter URL', array(), $options),
    'type' => 'string',
    'multidomain' => true,
    'access' => 'social media links'
  );

```

Create a menu to get to the admin form

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

  $items['admin/social-media-links'] = array(
      'title' => t('Social Media Links'),
      'page callback' => 'MODULENAME_social_media_links_admin',
      'access arguments' => array('social media links'),
    );

    return $items;
}

```

Menu Page Callback

```
function MODULENAME_social_media_links_admin() {
  return drupal_get_form('MODULENAME_socialmedialinks_form');
}

```

Form Declaration

```
function MODULENAME_socialmedialinks_form($form_state) {

  /* Just regular old variable_get() */
  $form['social_media_link_twitter'] = array(
    '#title' => t('Twitter'),
    '#type' => 'textfield',
    '#description' => t('Enter your twitter URL. Example: http://twitter.com/SomethingOn'),
    '#default_value' => variable_get('social_media_link_twitter', '')
  );

  /* return the system settings form, not just $form */
  return system_settings_form($form);
}

```

Form Submit

```
function MODULENAME_socialmedialinks_form_submit($form, &$form_state) {

  /* For some reason I have to manually get the domain and set the realm?! */
  $domain = domain_get_domain();
  variable_realm_switch('domain', $domain['subdomain']);

  domain_conf_variable_set($domain['domain_id'], 'social_media_link_twitter', $form_state['values']['social_media_link_twitter']);
}

```
> 1 votes

# Answer
You must enable "domain configuration" submodule (domain\_conf) This will provide you the save per domain option:

```
function your_module_form($form, &$form_state) {

  $form['variable'] = array(
    '#type' => 'value',
    '#value' => time(),
  );

  return system_settings_form($form);

}

```

getting the variable manually:

```
function domain_conf_variable_get($domain_id, $variable = '', $all = FALSE, $reset = FALSE)

```

seeting the variable manually:

```
function domain_conf_variable_set($domain_id, $variable, $value = NULL)

```

There is a module which aims to be a replacement variable handling module for Domain Access,If you need setting different variable values for each domain and for each language at the same time you need domain variable module https://drupal.org/project/domain\_variable
> 4 votes

# Answer
Another way to do it is with

hook\_domain\_batch

which gives you a nice settings UI under Domain \> Settings

For example, I wrote an implementation of that hook for per-domain apachesolr site hash settings:

```
/**
* Implements hook_domain_batch().
*
* Add batch settings to Domain Conf.
*/
function MODULENAME_domain_batch() {

  $batch = array();

  if(function_exists('apachesolr_site_hash')){
    $batch['apachesolr_site_hash'] = array(
      '#form' => array(
        '#title' => t('Apache Solr site hash'),
        '#type' => 'textfield',
        '#description' => t('Unique site hash for Apache Solr.'),
      ),
      '#domain_action' => 'domain_conf',
      '#permission' => 'administer site configuration',
      '#system_default' => apachesolr_site_hash(),
      '#meta_description' => t('Set Apache Solr site hash for each domain.'),
      '#variable' => 'apachesolr_site_hash',
      '#data_type' => 'string',
      '#weight' => -1,
      '#group' => t('Apache Solr'),
      '#update_all' => TRUE,
      '#module' => t('Apache Solr'),
    );
  }

  return $batch;

}

```

Then you can just use variable\_get to retrieve the value on that domain.
> 2 votes

---
Tags: 7, domain-access, configuration
---


# Question
Title: Webform override only certain groups of fields in webform-form template
My question is about overriding webform-form.tpl.php. I am using Webform 4.x-beta1 and Twitter Bootstrap framework. I would like to reuse bootstrap classes in my form to make it responsive. I got already how the override works. I would want to find out is it possible to only override the markup of certain groups of fields, for example to put 3 fields that are in the middle of the form inline using row-fluid class in the wrapper div, without changing the placement of these fields.
Ex:
---some fields that don't need to be overwritten---
---3 overwritten fields----
---some other fields keeping the correct order---
---2 overwritten fields---
etc.
My form is about 100 fields, and as far as I understand, I will have to revisit each and every field in order to achieve what I need.
I am sorry if I mixed you up in my explanation, I am pretty new to Drupal.
Thank you in advance

# Answer
> 0 votes
Finally I created several css classes that I add either to element wrapper or to the input element itself, and I position each element accordingly.

If your form is not too long, and you don't mind creating other webform elements, you might want to wrap the fields that you want to put on the same line in a fieldset, you give row-fluid class to the fieldset, and all is good. This obviously also depends on the functioning of the form, some modules don't work as expected with nested fieldsets, ex. webform add more module (at leat las I checked it didn't, was about a month ago)

In my case I didn't want to do this, as the form is long and complicated and it could've broken some functioning.

Cheers!

---
Tags: theming, webforms
---


# Question
Title: How to Skip the Workflow Launch by admin/user in Drupal-Commons using Maestro Module?
I have installed and configure the "Maestro" Module in Drupal Commons.

In Maestro Module every time we should Load the Workflow and it will go through step by step:

1. *Admin*: Publishing Workflow Load
2. *User1*: Assigend to add new Content
3. *User2*: Review Content
4. *User3*: Publish Content

How can I remove first step? When user creates new content, it should automatically go for review.

**My Workflow**

Using the rules module Can I define any rule when New Content is created means click on "Add Content" Workflow automatic Load....

# Answer
A solution we have used where we needed to have a menu item launch a workflow for expense approval using an entityform. The menu URL just needed to pass in the maestro workflow template\_id

The callback function for the menu hook launches the workflow and then executes past the START task in the maestro template, to the first interactive task for the user (fill out form). It redirects the user to the task console and automatically opens the expense form to be filled in. The following code can be added to a custom module and re-purposed for your use.

```
/**
 * Implements hook_menu()
 */
function MODULE_NAME_menu() {
  $items = array();

  $items['pi_workflow/launch_eform'] = array(
    'title' => 'Launch Entityform Workflow',
    'page callback' => 'nextide_launch_eform_workflow',
    'page arguments' => array(2) ,      // Passing in wildcard which should be the maestro workflow template_id
    'type' => MENU_CALLBACK,
    'access arguments' => array('maestro taskconsole')
  );

  return $items;
}

/* Launch an entityform workflow where the first task
 * after the start task is the entityform task.
 * User will be redirected to the taskconsole and launch the first task (open form for editing)
 */
function nextide_launch_eform_workflow($template) {
  if (intval($template) > 0) {
    $sec_token = drupal_get_token('maestro_user');
    $new_process_id = maestro_launch_workflow($template, $sec_token);

    // Run the orchestrator to execute the first task after the start task which is the interactive entityform task
    maestro_orchestrator();
    $maestro = Maestro::createMaestroObject(1);
    $process_data = $maestro->engine()->getQueueHistory($new_process_id);

    $task = MaestroTask::createTaskObject($process_data[1]->id);
    $data = $task->prepareTask();
    $task_data = unserialize($data['serialized_data']);

    // Default will be to redirect user to the task console unless overlay module is available
    $link = 'maestro/taskconsole';
    $options = array();
    // Test that we have valid process data and then test for the task we are looking for to get the task id
    if (is_array($process_data) AND isset($process_data[1])) {
      // If overlay module is enabled and user has overlay permission, open entityform up in overlay
      if (module_exists('overlay') && overlay_get_mode() ) {
        $options = array('fragment' => "overlay=eform/submit/{$task_data['entityform_id']}/maestro/" . $process_data[1]->id);
      }
    }
    drupal_goto($link, $options);
  } else {
    drupal_set_message(t("New Process Code FAIL! - No Template ID Given"));
  }

}

```
> 3 votes

---
Tags: 7
---


# Question
Title: What's this strange error during entity_creation?
I'm trying to create a (no bundle) entity from a feed using entity API, but I keep running into strange issue. The code for the entities is this:

```
function my_entity_provision() {
  $a = entity_create('entityType', array(
    'pid' => NULL,
    'aid' => 1,
    ...

  ))->save();
}

```

But when running it I run into these errors:

```
Warning: class_implements() [function.class-implements]: object or string expected in entity_create() (line 420 of ...../sites/all/modules/entity/entity.module).
Warning: in_array() expects parameter 2 to be array, boolean given in entity_create() (line 420 of ...../sites/all/modules/entity/entity.module).

```

I've tried looking on drupal and drupalcontrib for the correct implementation, but all code blocks show no text? :s

My code looks similar to Create Entity Programmatically in Drupal which does seem to work. (Since I have no bundle, I didn't define the type in the array, I read somewhere it can be omitted . But that made no difference anyway).

My entity info is as follows:

```
/**
 * Implements hook_entity_info().
 */
function my_entity_entity_info() {
  $return = array(
    'entityType' => array(
      'label' => t('entityType'),
      'controller class' => 'EntityAPIController',
      'base table' => 'entityTypes',
      'fieldable' => FALSE,
      'entity keys' => array(
        'id' => 'pid',
      ),
      'static cache' => TRUE,
      'view modes' => array(
        'full' => array(
          'label' => t('Full Entity'),
        ),
      ),
      'views controller class' => 'EntityDefaultViewsController',
    ),
  );

  return $return;
}

```

# Answer
Argh, it seems the two different entity modules (core & contrib) have confused me once again.

The EntityAPIController I chose as controller class has no method save(). It uses `entity_save($entity_type, $entity);` instead.

So the function had to be:

```
function my_entity_provision() {
  $a = entity_create('entityType', array(
    'pid' => NULL,
    'aid' => 1,
    ...

  ));
  entity_save('entityType', $a);
}

```
> 3 votes

---
Tags: 7, entities
---


# Question
Title: How to add a filepath to a file uploaded in form API
**Problem**

I have a custom form which creates a node. It's based off this link and uses the entity metadata wrapper to create the node.

The node created has an image field and you can use the form to upload an image on creation.

How can I set an upload directory for the image that's uploaded? At the moment they just default to my public folder.

**Set-Up**

There's more to this form, but these are the important parts. I declare a file field.

```
function postajob_form($form, &$form_state){
   ....
   $form['file'] = array(
     '#type' => 'file',
     '#title' => t('Thumbnail/Advert Picture.'),
     '#size' => 5,
   );
 }

```

I then submit that file using an entity metadata wrapper.

```
function postajob_form_submit($form, &$form_state) {

  global $user;

  $values = array(
    'type' => 'job_advert',
    'uid' => $user->uid,
    'status' => 1,
    'comment' => 1,
    'promote' => 0,
  );
  $entity = entity_create('node', $values);

  $ewrapper = entity_metadata_wrapper('node', $entity);

  if (array_key_exists('storage', $form_state)) {
      //if is required incase no image is uploaded.
      $ewrapper->field_req_thumbnail_school->file = $form_state['storage']['file'];
      //field is unset now it's no longer needed.
      unset($form_state['storage']['file']);
   }
}

```

I tried changing the URI inside the `form_state`, however this had no effect.

```
 if (array_key_exists('storage', $form_state)) {
      //altering the uri where the files are uploaded too
      $imagefilename = $form_state['storage']['file']->filename;
      $form_state['storage']['file']->uri = "public://user-upload/job-advert/$imagefilename";
      //save the file
      $ewrapper->field_req_thumbnail_school->file = $form_state['storage']['file'];

   }

```

But this didn't effect anything.

# Answer
> 0 votes
Clearly was not having a good day when I posted this question. I already had the code I just needed to change the path.

Taken straight from one of the form examples the following piece of code goes into the form validation function. It validates the file (this shows image validation) and then moves it to the desired path.

```
function mymodule_form_validate($form, &$form_state) {

   //I upload the file with file_save upload
    $file = file_save_upload('file', array(
      'file_validate_is_image' => array(), // Validates file is really an image.
      'file_validate_extensions' => array('png gif jpg jpeg'), // Validate extensions.
    ));
    // If the file passed validation:
    if ($file) {
      // Move the file, into the Drupal file system
      // This is where you set the path.
      drupal_mkdir("public://user-upload/job-advert/$usermail");
      if ($file = file_move($file, "public:///user-upload/job-advert/$usermail")) {
        // Save the file for use in the submit handler.
        $form_state['storage']['file'] = $file;
      }

    }
  }

```

# Answer
> 1 votes
Whenever I use a file field in the submit handler I use:

```
$validators = array('file_validate_extensions' => array('csv'));
if ($file = file_save_upload('upload', $validators)) {

```

You can add an optional argument to file\_save\_upload after $validators which is $destination, take a look at https://api.drupal.org/api/drupal/includes!file.inc/function/file\_save\_upload/7 for more details

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


# Question
Title: How to validate temporary files with form API
**Problem**

I have a custom form with three file fields. The files are selected, then on submit they're attached to an email and sent off with a call to `hook_mail`.

I'm pretty sure the files aren't saved to the server and I don't want them saved as the files might be sensitive information.

But I want the fields to support certain file extensions. How can I validate them?

**So Far**

There is a function: `file_validate_extensions` which can validate but it only works for Drupal file objects and since these are never uploaded I'm not sure that works.

I tried using `file_save_upload`, as when a file is selected in a form (and not immediately uploaded) it's information appears in $\_FILES so I tried to load the temporary path given there however it doesn't work.

(The path is of the form: `C:\XAMPP\tmp\phpEDC6.tmp`)

```
function mymodule_form_submit($form, $form_state) {
    $coverincluded = file_save_upload($_FILES['files']['tmp_name']['cover_letter_included'],
       array(
          'file_validate_is_image' => array(), // Validates file is really an image.
          'file_validate_extensions' => array('png gif jpg jpeg'), // Validate extensions.
       ));

     //unfortunately this dpm never shows, presumably because file_save_upload hasn't worked
      dpm($coverincluded);
 }

```

# Answer
This isn't a particularly clever solution, but hopefully it's ok. As far as I could tell you can't validate temporary files, they have to be uploaded.

So I ended up uploading them to the private directory and then immediately deleting them. Because some of the data might be sensitive I don't want to store them and this form takes place on a secure page.

```
function mymodule_form($form, &$form_state) {

   $form['file1'] = array(
     '#type' => 'file',
     '#title' => t('File1'),
   );

   $form['file2'] = array(
     '#type' => 'file',
     '#title' => t('File2'),
   );

}

```

Now for the important bit.

```
function mymodule_form_submit ($form, &$form_state) {
    //check if any file was attached
    if($_FILES['files']['tmp_name']['file1'] != '') {
      //Save and validate the file to the private file area
      $file1_included = file_save_upload('file1_included',
                                     array(
                                        'file_validate_is_image' => array(), // Validates file is really an image.
                                        'file_validate_extensions' => array('png gif jpg jpeg'), // Validate extensions.
                                      ), 'private://');
      //This is set-up for the email. Mimemail stores attachments in $params.
      $params['4'] =  array('uri'    => $file1_included->uri,
                          'filename' => $file1_included->filename,);
      //The file has been uploaded. So we'll set a variable which will be called later to delete it.
      $del_files['file1'] = $file1_included;

    }

   if($_FILES['files']['tmp_name']['file2'] != '') {
   //.... same as file 1...
   }

  //this will send an email. Note $params. We've put all our attachment information in
  //there.
  $message = drupal_mail('mymodule', 'notify', $email, language_default(), $params);

  //This function will delete all the files we've just uploaded. We check if
  //the variable has been set. And if it has then we call it and delete the relevant
  //files.

  if (isset($del_files)){
    _tellafriend_filedelete($del_files);
  }

}

```

This is the function we call to delete the files

```
function _mymodule_filedelete(&$del_files){
   //we know the variable exists, but now we have to check which files were uploaded.
   if(array_key_exists('file1' , $del_files)) {
    //and if they were uploaded. We delete them.
    file_delete($del_files['file1']);
  }
   if(array_key_exists('file2' , $del_files)) {
    file_delete($del_files['file2']);
  }
}

```
> 1 votes

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


title: Drupal 7 css and js compression

text:
# Question
Title: Drupal 7 css and js compression
When I turn on Drupal 7 css and js compression in the performance part, it is aggregating too much files.(5 css files and 5js files). Why?

The page:

Is there any way to force drupal to aggregate more the files?

# Answer
> 5 votes
No, not really, and you wouldn't want to do this.

The thing is, Drupal aggregates CSS files into groups to be able to easily load different CSS sets for different 'media' and 'browser' values, as well as for different pages being viewed, without the need to regenerate them.

If you look into `$groups` variable generated by `drupal_group_css()` in `includes/common.inc`, there are 5 keys which different combination of values between each group: `type`, `every_page`, `media`, `preprocess` and `browsers`.

This allows for different groups to be loaded on different pages/in different situations without regenerating them (or including not-needed CSS), which would be the case if only one aggregated CSS file would exist.

# Answer
> 1 votes
You might want to take a look at the Advanced CSS/JS Aggregation contrib module, especially the Bundler Submodule.

The Bundler Submodule might be capable of doing what you want. On top of that, you can also compress JS which might also be useful for you.

Do also check Simple Aggregation contrib module.

Good luck.

# Answer
> 0 votes
You can alter the CSS / JS and regroup everything in one group. This will aggregate into one or multiple CSS / JS files (depending the media types used within CSS declaration and JS files, external, inline, ...)

```
/**
 * Regroup all CSS files to the same GROUP name.
 * @param type $css
 */
function MYMODULE_css_alter(&$css)
{
    uasort($css, 'drupal_sort_css_js');
    $i = 0;
    foreach ($css as $name => $style) {
        $i++;
        $css[$name]['weight'] = ($style['type'] == 'external' ? $i + 100 : $i);
        $css[$name]['group'] = CSS_DEFAULT;
        $css[$name]['every_page'] = true;
    }
}

/**
 * Regroup all JS files to the same GROUP name.
 * @param type $javascript
 */
function MYMODULE_js_alter(&$javascript)
{
    uasort($javascript, 'drupal_sort_css_js');
    $i = 0;
    foreach ($javascript as $name => $script) {
        $javascript[$name]['weight'] = $i++;
        $javascript[$name]['group'] = JS_DEFAULT;
        $javascript[$name]['every_page'] = true;
    }
}

```

---
Tags: 7, javascript, theming, css-js-aggregation
---


# Question
Title: HTTPS and SecurePages Infinite Redirect - How do I reset which pages are always HTTPS?
Using Secure Pages, I checked the option to have the site always be using HTTPS when logged in as an administrator, but now I have an infinite redirection issue, and I cannot log-in and navigate the site, leaving me to edit the settings manually.

How do I "uncheck", or revert the option that I selected manually in SecurePages?

# Answer
I pulled this directly from the README.txt of the module.

> ## Configuration
>
> Generally on test/development servers you do not have access to SSL, so generally you would like to disable secure pages on these systems.
>
> To do this add the following to your settings.php
>
> $conf\['securepages\_enable'\] = 0;
>
> ## Removal of SecurePages
>
> In the case where your SSL mode has been disabled and you can no longer access the administration section of your site to disable securepages you can do one of the 2 following things.
>
> 1. Use the above method to disable securepages.
> 2. delete the secure pages module from your site.
>
> If you can use the first option but if you can't edit your settings.php then deleting it will not break your site, but will leave some variables that are set by secure pages.
> 2 votes

---
Tags: redirection, security
---


# Question
Title: How do convert mysql query with sub queries to a db_select version?
Below is a mysql query that returns a proper result set. How can I convert this into a db\_select() version?

```
SELECT p.id, u.name, pa.field_address_2_value, pa2.display, pa3.field_company_value
FROM ms_order_products p
LEFT JOIN ms_orders o ON p.oid = o.oid
LEFT JOIN users u ON o.uid = u.uid
LEFT JOIN
(
    select *
    from field_data_field_address_2

) pa
ON u.uid = pa.entity_id
LEFT JOIN
(
    select *
    from ms_order_adjustments

) pa2
ON o.oid = pa2.oid
LEFT JOIN
(
    select *
    from field_data_field_company

) pa3
ON u.uid = pa3.entity_id
WHERE p.id = 'RM11'

```

# Answer
I found the answer, see below. (I added a few more fields as well)

```
  $sub_query_1 = db_select('field_data_field_address_2', 'addr2');
  $sub_query_1->fields('addr2', array('field_address_2_value', 'entity_id'));

  $sub_query_2 = db_select('ms_order_adjustments', 'a');
  $sub_query_2->fields('a', array('display', 'oid'));

  $sub_query_3 = db_select('field_data_field_company', 'comp');
  $sub_query_3->fields('comp', array('field_company_value', 'entity_id'));

  $query = db_select('ms_order_products', 'p');

  $query->fields('p', array('id', 'oid', 'type', 'amount'));
  $query->fields('o', array('oid', 'uid', 'status', 'order_type', 'created'));
  $query->fields('u', array('uid', 'mail', 'name'));
  $query->fields('fn', array('field_first_name_value'));
  $query->fields('ln', array('field_last_name_value'));
  $query->fields('adr1', array('field_address_1_value'));
  $query->fields('city', array('field_city_value'));
  $query->fields('state', array('field_state_value'));
  $query->fields('zip', array('field_zip_code_value'));
  $query->fields('pa', array('field_address_2_value'));
  $query->fields('pa2', array('display'));
  $query->fields('pa3', array('field_company_value'));

  $query->leftjoin('ms_orders', 'o', 'o.oid = p.oid');
  $query->leftjoin('users', 'u', 'o.uid = u.uid');
  $query->leftjoin('field_data_field_first_name', 'fn', 'u.uid = fn.entity_id');
  $query->leftjoin('field_data_field_last_name', 'ln', 'u.uid = ln.entity_id');
  $query->leftjoin('field_data_field_address_1', 'adr1', 'u.uid = adr1.entity_id');
  $query->leftjoin('field_data_field_city', 'city', 'u.uid = city.entity_id');
  $query->leftjoin('field_data_field_state', 'state', 'u.uid = state.entity_id');
  $query->leftjoin('field_data_field_zip_code', 'zip', 'u.uid = zip.entity_id');

  $query->addJoin('LEFT', $sub_query_1, 'pa', 'u.uid = pa.entity_id');
  $query->addJoin('LEFT', $sub_query_2, 'pa2', 'o.oid = pa2.oid');
  $query->addJoin('LEFT', $sub_query_3, 'pa3', 'u.uid = pa3.entity_id');

  $query->condition('p.id', 'RM11', '=');

  $result = $query->execute();

```
> 0 votes

---
Tags: database
---


title: A flexible front page layout tool

text:
# Question
Title: A flexible front page layout tool
I want to build a front page in which the site administrator has a lot of control (through the UI) over the layout. Panels is the only thing that comes close, but I still don't think it can do everything I need (and admittedly, I'm not a big fan of panels).

**requirements**

The front page will have a couple of sections; I'll call them "news", "products" and "store" in this example. The administrator must be able to control the order of the sections on the page.

Each section will contain a selection of news nodes for the news section and a selection of products for the products section. (The nodequeue module would be an obvious choice here.) The order of the nodes can be controlled by the administrator too. Also, the admin must be able to choose if a node is rendered full width, or if two are rendered half width, placing them side-by-side.

The "store" section must contain a maximum of 4 blocks (not nodes). The admin must be able to make a selection out of 6 or 7 blocks and gain control the order.

**question**

I'm sure I can make this work all by myself, but I'm curious: Which module (or combination of modules, if any) would you use to accomplish this? Needless to say, I would like this to be as easy and user friendly as possible, preferrably with as least different forms and interfaces as possible.

# Answer
> 4 votes
EDIT: I realize there is a more generic question here, so I copied my answer over there.

A combination of the following modules can get you quite far:

How?

* Create a node type "frontpage".
* Add a multiple-value block reference field with "Multiple Selects list" widget.
* Set up some bean types to allow different kinds of fancy boxes that can be placed on the frontpage.
* In addition you can have Views blocks to be used in the block reference.
* One of the bean types could have a multiple-value entityreference to e.g. reference a bunch of products (and have them sortable). I generally prefer this over nodequeue.
* Use Display suite to define how each bean and the frontpage itself should be displayed.
* Use Display suite custom field templates to have decorated boxes around each bean/block in the blockreference, or each product, etc. Check hook\_ds\_field\_theme\_functions\_info(). This stuff is powerful and awesome!
* Tell the client / content editor to use the contextual links to edit individual beans.

This should give you some material to play with .. More detailed questions should be discussed in dedicated stackexchange questions, since this is quite broad.

# Answer
> 3 votes
Panels seems what you are looking for.

> The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout.

# Answer
> 1 votes
The module with which I can't live without for block layout is the Context module. You can easily define multiple "context" where you want each block to appear and their order.

You can set the side by side blocks with CSS by adding the class directly in the block settings with Block Class module.

---
Tags: 7, panels, theming
---


title: Best practices for page layouts

text:
# Question
Title: Best practices for page layouts
I'm trying to figure out what the best practices are for page layouts in Drupal. Many pages have several different elements on them like main content, a header image, etc. I'm not looking at creating a 'basic page' or anything similar (ie one node for the whole page).

Is it good to use panels for every page and them drop blocks into them? I could drop views, possibly a node, a contact form, etc...

# Answer
Panels is a great module, but it can also be complex and it can take a while before you completely understand it. If you're interested in using panels for every page, the Panels Everywhere module is an interesting project.

Another great project that provides more flexible layouts is Display Suite.

Although people tend to use either Panels or DS, they are not competitors. They can be even used together as you can read on the blog of the author/maintainer of DS: Using panels on view modes in Drupal 7.
> 11 votes

# Answer
Views and panels are a good possibility but with the use of a great framework as 960gs!
> 2 votes

# Answer
Yes, panels gives you layouts into which you can drop elements.

Panelizer is the most straightforward panels module that simply adds a panel to your pre-existing nodes. (Node Panels is deprecated, but this fact is not widely pointed out.)

So, use the regular node system, but "panelize" nodes if or when you need to.
> 0 votes

# Answer
If you are looking to reuse the layout for more then one page, then Display suite with a bunch of fields seems like the best choice.

If you want individual layouts per page, then Panels might be the right thing.

---

If you want the latter, but are afraid of Panels (as I am), then there is something else you can try. (from https://drupal.stackexchange.com/a/90744/2974)

Modules:

How?

* Create a node type "frontpage".
* Add a multiple-value block reference field with "Multiple Selects list" widget.
* Set up some bean types to allow different kinds of fancy boxes that can be placed on the frontpage.
* Use blockreference within a bean for nested layouts.
* One of the bean types could have a multiple-value entityreference to e.g. reference a bunch of products (and have them sortable). I generally prefer this over nodequeue.
* Use Display suite to define how each bean and the frontpage itself should be displayed.
* Use Display suite custom field templates to have decorated boxes around each bean/block in the blockreference, or each product, etc. Check hook\_ds\_field\_theme\_functions\_info(). This stuff is powerful and awesome!
* Tell the client / content editor to use the contextual links to edit individual beans.
* In addition you can have Views blocks to be used in the block reference.
* Inline entity form might be useful, but I have not actually tried it in this combination. This is homework :)

The strategy is that everything that is unique to one page should be a block (or bean instance). We can afford that because those blocks don't pollute any theme regions.

This should give you some material to play with ..
More detailed questions should be discussed in dedicated stackexchange questions, since this is quite broad.
> 0 votes

---
Tags: 7, panels, theming
---


# Question
Title: How to check if a node has a photo/video to use as an exposed filter in views?
I am interested in creating an exposed filter with the following values:

* Has photo
* Has video
* Has both photo and video

So this filter will check nodes and show only those with photos, if this filter is selected etc.

How can i do this? Should I create a new field on the content type and populate this according to having image/video?

Any ideas?

thanks

# Answer
> 1 votes
You should be able to add the photo field or fields as filters and set their criteria to "not empty". Then, only those records with a photo should be visible. The same applies for the video field.

---
Tags: views
---


title: Structured layout in Drupal

text:
# Question
Title: Structured layout in Drupal
I'm having trouble understanding how to approach layout in Drupal. I want to create a structure where (authorized) users with no designing skills can add content by simply adding content selecting a particular content type.

So e.g. I want to have one type of page that consists of a number of sections (rows) with an image on one side (should be possible to alternate which side) and a heading and text on the other side. If the heading and text is on the right, the heading should be just above the text, and not above the image to the left.

An arbitrary number of sections/rows should be possible to add.

I've managed to do something like this with panels and mini-panels. But it seems like I'm trying very hard to achieve something that feels rather basic... In any case, what I did was I added a page selecting panels with the 1-column layout. This allows me to add rows arbitrarily. First problem here is, the end user would have to select this on their own, I would have liked to have a preset content type with this.

Secondly, I created some mini-panels with content that can be added to the sections of the panel page. More problems: to create these mini-panels and make them lay out as described I have to create mini-panels of a 2-column format, omit the title, add only an image to one of the columns using add custom content selection - no title, and add a title and some text to the other column.

All of this is rather complex just to achieve this layout. It makes me think it would be much easier to just use a wysiwyg editor and lay it all out manually instead. But that is just what I'm trying to avoid. End users would come up with all kinds of layouts, creating a site that does not have a structured feel at all...

Previously I have only done sites in php and CodeIgniter framework, where I naturally have full control and can just add the divs I want, using something like 960 or blueprint to help with layouts, and style it individually with css. But that is dependent on doing it all yourself or at least with only others who know at least some web design. I don't know if modules based on 960 or something like that would help, since I need to be able to add sections etc arbitrarily? All I've seen for this is panels, but maybe I'm wrong?

So how do you approach this in Drupal? Any help will be greatly appreciated, because I'm really having a hard time understanding the basic thinking of layout in Drupal...

Edit:

this is a good example of the type of layout I'm referring: http://www.teamworkpm.net/features

# Answer
First of all, I'm a big Panels fan, so I definitely think you should be using it, but I'm not sure it's the best for the task you are trying to achieve.

Some options, in what I feel is descending order of usefulness to you.

1. Since it sounds like it's necessary for you to mix several fields into a single render element, you could implement a Ctools "content type". How does one create a new ctools plugin should be helpful here. This easily allows you any custom logic in rendering the fields on a per entity basis. You should still separete the logic from the rendering, by declaring your own template. See Correct way to render a modules output through a template?
2. If the output you describe above completely dominates the page, then perhaps it would make sense to move the rendering up a level. A panels "layout"-plugin could be useful instead. The plugin link from above is still the source for more information.
3. If it makes sense to work with individual fields, which I doubt in your case, a custom field formatter could be what you are looking for. See How do I make the output of field X look like Y?
4. This one is mostly speculcation, I haven't attempted it, but if you are working with a Field collection, it being an entity, perhaps you can use Display suite to control it's output, and then have Panels render it inline. Or you could skip DS and directly template the FC entity.
> 3 votes

# Answer
Did you have a look at content types? You can define you're own types with what ever field types you need. Once you have the data you can adjust your CSS and may be some theme overrides to your liking. There are also a lot of modules providing additional functionality for content types and fields.

I also sugest to start with a standar theme like zen and create a subtheme.

Some tools that her very helpfull:
> 0 votes

# Answer
You're looking for something like Panopoly. Take a look at it.
> 0 votes

# Answer
Panels and friends (panopoly, etc) could be a solution. Personally I am the no-panels man, so I am going to explain a solution without panels, for the sake of diversity.

> So e.g. I want to have one type of page that consists of a number of sections (rows) with an image on one side (should be possible to alternate which side) and a heading and text on the other side.

Looks like a typical case of "same layout for each node of type X". So you could create a node type with some fields (an image field, a text field) and then use Display suite to arrange this stuff.

It seems you want two different ways to display these pages: Either the image is on the left or on the right. This can be done by defining an additional "View mode" with Display suite, and then enable an option where you can choose the View mode per node.

For the "sections", if you want something more fancy than just text, you could use a "block reference" field. More on this here.

This all depends on how much you want to allow the client to do, and what you consider too complicated and rather want to do yourself instead of explaining to the client.
> 0 votes

---
Tags: panels, theming
---


title: PDF file open new tab

text:
# Question
Title: PDF file open new tab
I'm using Drupal 7. My theme Omega. And have got file field in my site. Uploaded all pdf files and everything working.

But, when i click pdf files on Firefox, my pdf file starting download. When i click on Chrome, pdf open in same page.

Checked by Firebug, pdf file html code is here:

```
<span class="file"><img src="/modules/file/icons/application-pdf.png" title="application/pdf" alt="" class="file-icon"> <a title="myfile.pdf" type="application/pdf; length=1620377" href="http://mysite.net/sites/default/files/myfile.pdf">Click to Download</a></span>

```

I want when click pdf file, open a new tab, so make attribute. Drupal file module is (file.js):

```
 *
 * This file provides progress bar support (if available), popup windows for
 * file previews, and disabling of other file fields during Ajax uploads (which
 * prevents separate file fields from accidentally uploading files).
 */

(function ($) {

/**
 * Attach behaviors to managed file element upload fields.
 */
Drupal.behaviors.fileValidateAutoAttach = {
  attach: function (context, settings) {
    if (settings.file && settings.file.elements) {
      $.each(settings.file.elements, function(selector) {
        var extensions = settings.file.elements[selector];
        $(selector, context).bind('change', {extensions: extensions}, Drupal.file.validateExtension);
      });
    }
  },
  detach: function (context, settings) {
    if (settings.file && settings.file.elements) {
      $.each(settings.file.elements, function(selector) {
        $(selector, context).unbind('change', Drupal.file.validateExtension);
      });
    }
  }
};

/**
 * Attach behaviors to the file upload and remove buttons.
 */
Drupal.behaviors.fileButtons = {
  attach: function (context) {
    $('input.form-submit', context).bind('mousedown', Drupal.file.disableFields);
    $('div.form-managed-file input.form-submit', context).bind('mousedown', Drupal.file.progressBar);
  },
  detach: function (context) {
    $('input.form-submit', context).unbind('mousedown', Drupal.file.disableFields);
    $('div.form-managed-file input.form-submit', context).unbind('mousedown', Drupal.file.progressBar);
  }
};

/**
 * Attach behaviors to links within managed file elements.
 */
Drupal.behaviors.filePreviewLinks = {
  attach: function (context) {
    $('div.form-managed-file .file a, .file-widget .file a', context).bind('click',Drupal.file.openInNewWindow);
  },
  detach: function (context){
    $('div.form-managed-file .file a, .file-widget .file a', context).unbind('click', Drupal.file.openInNewWindow);
  }
};

/**
 * File upload utility functions.
 */
Drupal.file = Drupal.file || {
  /**
   * Client-side file input validation of file extensions.
   */
  validateExtension: function (event) {
    // Remove any previous errors.
    $('.file-upload-js-error').remove();

    // Add client side validation for the input[type=file].
    var extensionPattern = event.data.extensions.replace(/,\s*/g, '|');
    if (extensionPattern.length > 1 && this.value.length > 0) {
      var acceptableMatch = new RegExp('\\.(' + extensionPattern + ')$', 'gi');
      if (!acceptableMatch.test(this.value)) {
        var error = Drupal.t("The selected file %filename cannot be uploaded. Only files with the following extensions are allowed: %extensions.", {
          '%filename': this.value,
          '%extensions': extensionPattern.replace(/\|/g, ', ')
        });
        $(this).parents('div.form-managed-file').prepend('<div class="messages error file-upload-js-error">' + error + '</div>');
        this.value = '';
        return false;
      }
    }
  },
  /**
   * Prevent file uploads when using buttons not intended to upload.
   */
  disableFields: function (event){
    var clickedButton = this;

    // Only disable upload fields for Ajax buttons.
    if (!$(clickedButton).hasClass('ajax-processed')) {
      return;
    }

    // Check if we're working with an "Upload" button.
    var $enabledFields = [];
    if ($(this).parents('div.form-managed-file').size() > 0) {
      $enabledFields = $(this).parents('div.form-managed-file').find('input.form-file');
    }

    // Temporarily disable upload fields other than the one we're currently
    // working with. Filter out fields that are already disabled so that they
    // do not get enabled when we re-enable these fields at the end of behavior
    // processing. Re-enable in a setTimeout set to a relatively short amount
    // of time (1 second). All the other mousedown handlers (like Drupal's Ajax
    // behaviors) are excuted before any timeout functions are called, so we
    // don't have to worry about the fields being re-enabled too soon.
    // @todo If the previous sentence is true, why not set the timeout to 0?
    var $fieldsToTemporarilyDisable = $('div.form-managed-file input.form-file').not($enabledFields).not(':disabled');
    $fieldsToTemporarilyDisable.attr('disabled', 'disabled');
    setTimeout(function (){
      $fieldsToTemporarilyDisable.attr('disabled', '');
    }, 1000);
  },
  /**
   * Add progress bar support if possible.
   */
  progressBar: function (event) {
    var clickedButton = this;
    var $progressId = $(clickedButton).parents('div.form-managed-file').find('input.file-progress');
    if ($progressId.size()) {
      var originalName = $progressId.attr('name');

      // Replace the name with the required identifier.
      $progressId.attr('name', originalName.match(/APC_UPLOAD_PROGRESS|UPLOAD_IDENTIFIER/)[0]);

      // Restore the original name after the upload begins.
      setTimeout(function () {
        $progressId.attr('name', originalName);
      }, 1000);
    }
    // Show the progress bar if the upload takes longer than half a second.
    setTimeout(function () {
      $(clickedButton).parents('div.form-managed-file').find('div.ajax-progress-bar').slideDown();
    }, 500);
  },
  /**
   * Open links to files within forms in a new window.
   */
  openInNewWindow: function (event) {
    $(this).attr('target', '_new');
    window.open(this.href, 'filePreview', 'toolbar=0,scrollbars=1,location=1,statusbar=1,menubar=0,resizable=1,width=500,height=550');
    return false;
  }
};

})(jQuery);

```

I don't have page.tpl files, so must this jQuery or another way. How can i do this?

# Answer
Patrick is right that this is more of a issue with how different browsers (and the users' individual settings) than anything with your template. That said there is some research support (useit.com) for at least trying to implement this functionality for users but its probably outside the scope of Drupal so if you want this, you're going to need to update your theme to rewrite these links to add a jquery override for PDF files, like this one:

http://www.webcredible.co.uk/user-friendly-resources/dom-scripting/pdf-new-window.shtml
> 0 votes

# Answer
In case anybody else have the same problem, I recommend the External Links module. To use this module for PDF files, just type .\*.pdf in the matching pattern field, being careful of typing the complete regular expression, to avoid conflicts with the javascript. For some screenshots of the process, follow: http://www.inqbation.com/open-pdf-files-in-new-tab/ ... It is pretty simple.
> -1 votes

---
Tags: 7, entities, javascript, files
---


title: Add search to the Drupal 7 find content

text:
# Question
Title: Add search to the Drupal 7 find content
By default drupal 7 find content page comes with filter by type and status. I wanted to give one more filter, where user can type the few letters from the title they are looking for so that they can find the article/page with ease even when theres 100's of content in the site.

I did something similar using views and exposing title as a filter. But it would be great to add this field and search to the default filters we find in the drupal 7 find content page.

# Answer
> 10 votes
Try the Administration Views module:

> Replaces administrative overview/listing pages with actual views for superior usability.

It will let you replace the standard content admin page with a view, to which you can add as many filters as you need.

# Answer
> 1 votes
Use Find Content, simpler and newer than Administration Views.

> Adds a search box to the Find Content screen
>
> *Requires: Node (enabled), Field (enabled), Field SQL storage (enabled)*

# Answer
> -1 votes
I think it's admin accessible area and instead of modifying it why don't you try search module with Search Autocomplete module

hope it will help you :)

---
Tags: 7, nodes
---


title: Views 3 Template or UI question

text:
# Question
Title: Views 3 Template or UI question
I have a text field that contains multiple values. That field does not always contain any values. The field needs to have a label when displayed.

IOW, the row should look like one rows below

CoAuthor: Person X, Person Y

or

CoAuthor: Person X

Here is my issue: When I use the view UI to add the label I get

CoAuthor: Person X, CoAuthor: Person Y

When I use the template,

```
print $fields['field_coauthor']->content;

```

I can not hide the field when empty so I end up with

CoAuthor: (and no value)

Is there a way to add a conditional to the template so that I do not end up with a label and no data? Or configure the view to include the label once... and not add it for every entry?

# Answer
I am actually a bit puzzled by your View result, because the default settings for fields should give you:

> CoAuthor: Person X, Person Y

when there is more than one author (and this I presume, is what you want?)

And since Views also have a setting: "Hide if empty" under \*No results behavior", it should be trivial to get this right using fields.

Anyway, this is how I've set this up using Views:

First, I click on *Format - Show: Content* and switch that to *Fields*.

Second, I tick *Provide default field wrapper elements* and *Hide empty fields*.

Third, under *Fields* I click *Add* and add the "CoAuthor" field. I tick *Create a label*, and *Place a colon after the label*. Under *Multiple field settings*, I tick *Display all values in the same line*. I also tick *Simple separator* and make sure it is `,`  (comma followed by space, which is the default).Then under *No results behavior*, I leave *No results text* blank, and tick *Hide if empty* and *Hide rewriting if empty*.

Fourth, I navigate to *Format - Show: Settings* and tick to make sure *CoAuthor* is an inline field.

After doing all this, the output should be nothing if there are no CoAuthor, and for the other two cases:

> CoAuthor: Person X
>
> CoAuthor: Person X, Person Y

As for using a template, you should be able to wrap the PHP generating the output in a test that checks for a non-empty field, e.g.:

```
if (!empty(print $fields['field_coauthor']->content)) {

```

I not sure where the template fragment you post come from, so I haven't posted the full code, but I hope you get the idea.
> 0 votes

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