title: Drupal Commerce Bestsellers

text:
# Question
Title: Drupal Commerce Bestsellers
We have the following view.

```
$view = new view();
$view->name = 'bestsellers';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'commerce_order';
$view->human_name = 'Bestsellers';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */
/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['default_row_class'] = FALSE;
$handler->display->display_options['style_options']['columns'] = array(
  'title_1' => 'title_1',
  'view_node' => 'view_node',
  'title' => 'title',
  'product_id' => 'product_id',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title_1' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'view_node' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'product_id' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Relationship: Commerce Order: Referenced line items */
$handler->display->display_options['relationships']['commerce_line_items_line_item_id']['id'] = 'commerce_line_items_line_item_id';
$handler->display->display_options['relationships']['commerce_line_items_line_item_id']['table'] = 'field_data_commerce_line_items';
$handler->display->display_options['relationships']['commerce_line_items_line_item_id']['field'] = 'commerce_line_items_line_item_id';
$handler->display->display_options['relationships']['commerce_line_items_line_item_id']['label'] = 'line_items';
$handler->display->display_options['relationships']['commerce_line_items_line_item_id']['required'] = TRUE;
/* Relationship: Commerce Line item: Referenced products */
$handler->display->display_options['relationships']['commerce_product_product_id']['id'] = 'commerce_product_product_id';
$handler->display->display_options['relationships']['commerce_product_product_id']['table'] = 'field_data_commerce_product';
$handler->display->display_options['relationships']['commerce_product_product_id']['field'] = 'commerce_product_product_id';
$handler->display->display_options['relationships']['commerce_product_product_id']['relationship'] = 'commerce_line_items_line_item_id';
$handler->display->display_options['relationships']['commerce_product_product_id']['label'] = 'products';
$handler->display->display_options['relationships']['commerce_product_product_id']['required'] = TRUE;
/* Field: Commerce Product: SKU */
$handler->display->display_options['fields']['sku']['id'] = 'sku';
$handler->display->display_options['fields']['sku']['table'] = 'commerce_product';
$handler->display->display_options['fields']['sku']['field'] = 'sku';
$handler->display->display_options['fields']['sku']['relationship'] = 'commerce_product_product_id';
$handler->display->display_options['fields']['sku']['link_to_product'] = 0;
/* Field: Commerce Product: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'commerce_product';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['relationship'] = 'commerce_product_product_id';
/* Field: COUNT(Commerce Product: Product ID) */
$handler->display->display_options['fields']['product_id']['id'] = 'product_id';
$handler->display->display_options['fields']['product_id']['table'] = 'commerce_product';
$handler->display->display_options['fields']['product_id']['field'] = 'product_id';
$handler->display->display_options['fields']['product_id']['relationship'] = 'commerce_product_product_id';
$handler->display->display_options['fields']['product_id']['group_type'] = 'count';
$handler->display->display_options['fields']['product_id']['label'] = 'Count';
$handler->display->display_options['fields']['product_id']['separator'] = '';
/* Sort criterion: COUNT(Commerce Product: Product ID) */
$handler->display->display_options['sorts']['product_id']['id'] = 'product_id';
$handler->display->display_options['sorts']['product_id']['table'] = 'commerce_product';
$handler->display->display_options['sorts']['product_id']['field'] = 'product_id';
$handler->display->display_options['sorts']['product_id']['relationship'] = 'commerce_product_product_id';
$handler->display->display_options['sorts']['product_id']['group_type'] = 'count';
$handler->display->display_options['sorts']['product_id']['order'] = 'DESC';
/* Filter criterion: Commerce Line Item: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'commerce_line_item';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['relationship'] = 'commerce_line_items_line_item_id';
$handler->display->display_options['filters']['type']['value'] = array(
  'product' => 'product',
);
/* Filter criterion: Commerce Product: Type */
$handler->display->display_options['filters']['type_1']['id'] = 'type_1';
$handler->display->display_options['filters']['type_1']['table'] = 'commerce_product';
$handler->display->display_options['filters']['type_1']['field'] = 'type';
$handler->display->display_options['filters']['type_1']['relationship'] = 'commerce_product_product_id';
$handler->display->display_options['filters']['type_1']['value'] = array(
  'product' => 'product',
);

```

It displays Bestsellers with buy counter, but it also displays the ones that are in shopping cart (wasn't even bought). Does anybody know how to delete shopping cart results from the counter, and display only the really bought product counter?

I want it to display 0 when there aren't bought products. I tried rewriting the view, but it didn't work. "No results" doesn't work. I verified there aren't hide empty fields anywhere. I tried to add the "No results" behavior for whole site, but it doesn't allow me as well. How should I do, to get a 0 shown when there aren't bought products?

# Answer
> 0 votes
In Filter Criteria I have added Commerce Order: Order status field and specified which status do I want to be counted only.

To display 0 I needed to add No results behavior for whole display. I have added Global: Text area field. Unfortunately 0 didn't want to get displayed so I needed to display it with PHP.

```
$count = '<strong>0</strong>';
print $count;

```

Actually I needed it to be strong so it wasn't an issue.

---
Tags: commerce
---


title: Display Rate module results via Panels

text:
# Question
Title: Display Rate module results via Panels
So many of us know that the Rate module does not smoothly integrate with Panels.

I discovered out a way to get the voting widget to show using a custom content with the following PHP code:

```
<?php
if (arg(0) == 'node' && is_numeric(arg(1)) && ($node = node_load(arg(1)))) {
   print rate_embed($node, 'bias', RATE_FULL);
}
?>

```

Has anyone had any luck with doing something similar to display only the vote results (i.e. display total percent of that vote)?

I'm not a PHP wizard, but I think there is way by doing something like the following.

```
<?php
if (arg(0) == 'node' && is_numeric(arg(1)) && ($node = node_load(arg(1)))) {
   print get_rate_resluts($node, 'bias', RATE_FULL);
}
?>

```

But end up getting either blank pages or some fatal database errors. Thoughts?

Update: I think I figured out that I need to create a custom content to print the output after reading it here. Tried this:

```
$block['content'] = rate_get_results('bias', $nid, $widget_id) $output['rating'];

```

But it looks like it does not do anything which is better then seeing a blank page.

# Answer
```
print rate_embed($node, 'NAME', RATE_FULL);

```

Replace *NAME* with the machine name of the widget; the view mode can be `RATE_FULL`, `RATE_COMPACT`, `RATE_DISABLED`, `RATE_CLOSED`, `RATE_COMPACT_DISABLED`.
> -1 votes

---
Tags: 7, panels, rating
---


title: Content items with multiple images

text:
# Question
Title: Content items with multiple images
I have created a content item in Drupal 7 which has multiple image fields (well it has an image field that accepts multiple images).

When I display the item, the images are displayed one under the other, or I can put them into a lightbox gallery.

How can I change or over-ride the CSS and JavaScript code associated with these content items? Additionally, I eventually want to be able to count up the number of images in the content item and write some js to do this. But I am not sure how to find the names of the items and/or if that is indeed necessary.

My goal is to make a gallery of images that can be flicked through like many JavaScript galleries that place content in hidden tags.

# Answer
> 1 votes
You can use javascript to add css to your page after all the other css files have been listed.

```
<?php
  drupal_add_js();

  // Then in the js file you can add the css file

```

If you are still stuck then place a link here of your site and contact me.

# Answer
> 0 votes
Create a template for the node type. If your content type is called 'gallery', create a template called 'node--gallery.tpl.php'

In it define your teasers (displayed on the view gallery page) using

```
 <?php if (!$page):
  // code goes here for teaser display
  // for example add a thumbnail of the first image,
  // the title of the gallery, the amount of images in it
  // add your own classes and divs etc ...
 <?php endif; ?>

```

Then define the page layout...

```
   <?php if ($page): ?>
     // here display the actual gallery
     // alternatively you can simply avoid showing the page
     // if you enable a lightbox style slideshow gallery on the first teaser view image
     // then it would degrade nicely if javascriopt was disabled to show this page
    <?php endif; ?>

```

to find the available fields you can print in the template, use

```
    print_r($node);

```

or

```
    <?php
       drupal_set_message(dprint_r($node, TRUE));
     ?>

```

# Answer
> 0 votes
When you use Drupal try to use what available in Drupal.

You always can use views module to manipulate content and output it in the shape you want, if you want more customization than what Views provide you (which I believe you can achieve what you want using views and lightbox module) you can use with that Custom formatters which let you control on the output of the field and you can use it with views or directly in content field format if you don't want to use views

# Answer
> -1 votes
```
// used to add your own stylesheet
drupal_add_css();
// used to add your own script
drupal_add_js();

```

then you can *catch* all your image fiels with something like this:

```
 jQuery(document).ready(function() {
     jQuery('.your-image-class').hide();
 });

```

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


title: how can i create new region in theme?

text:
# Question
Title: how can i create new region in theme?
I just want to create a new region in my theme on the top right side of page. with height = 50 px and width=200 px

i'm using drupal version 7

# Answer
First you need to define region in your\_theme.info https://drupal.org/node/171205#regions

for example

```
regions[search_bar]         = Top Search bar

```

then you probably want to output that region in your page.tpl.php:

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

```

to make it height = 50 px and width=200 px you need to write some css. You can also add some wrapping div with id:

```
<?php if ($page['search_bar']): ?>
<div id="search-bar">
    <?php print render($page['search_bar']); ?>
</div>
<?php endif; ?>

```
> 1 votes

---
Tags: theming
---


title: Conflict with languages at home page

text:
# Question
Title: Conflict with languages at home page
I have enabled 2 languages on the site (Russian and English). The conflict is only happening at the home page where the URL alias is */*. All the strings at sitename.ru/ are in English (the ones I would expect on sitename.co.uk), except for blocks. Language seems set to Russian, if that is the language set for the blocks. All the other pages (sitename.ru/pagename) are working correctly.

Here are some screenshots of page configuration, modules list and language configuration from admin.

How do I make it work on / for all languages based on their TLD?

Please advise

# Answer
> 0 votes
I suppose this is happening because you set the default language as English (see: /admin/config/regional/language) and set Russian as default to have Russian language on "/" .

---
Tags: i18n-l10n
---


# Question
Title: How to put a link / menu at the top of the edit-user profile page?
How can I put a link / menu in the edit-user-profile page, in the upper right corner? This link will open a new page with a form created. I've been watching a few examples but I could not understand.Sorry for the question, the more I'm starting.

# Answer
> 1 votes
Assuming your problem is with the link and not the form, I have done the following to accomplish something similar in the past:

* create a new block
* enter the link information in the block (you can also do this with a straight menu and use a block menu module)
* put the block in the appropriate section of the page where you want it to appear
* restrict it to only "user/\*/edit" pages

---
Tags: routes, users, forms
---


# Question
Title: Create a view with the contents of "self"
I am creating a View that will list all the current user's submissions of a specific content type. It is called "My Submissions".

However, I can't find a way to filter all results to "where author is me". Where could I achieve such thing?

# Answer
> 4 votes
You need to use contexts which is located under advanced to the right.

See below:

# Answer
> 1 votes
You can also use a relationship (advanced tab) for author. Then filter by current logged in user. This way also allows you to add author information to the view itself.

---
Tags: 7, views
---


# Question
Title: Webform show result table on webform node tpl
I am trying to display results of a certain content type (webform: event)

So my idea is that i would embed the table into the the tpl (node--event.tpl.php) I tried many different ways and the closest i can get is the following code

```
module_load_include('inc','webform','includes/webform.submissions');
$submissions = webform_get_submissions(array('nid'=> 4));

foreach ($submissions as $submission){
    foreach ($submission->data as $row=>$data){
        print '<pre>';print_r($row);print '</pre>';
        print '<pre>';print_r($data);print '</pre>';
    }
}

```

This works but just for a single node, in this case node 4, I would like to show this of the current node.

# Answer
I guess this is gonna hurt a lot of eyes but it works perfect for my case.

This is not the way I am suppose to work in drupal so if anyone can (help me) convert this to a hook or small module, i would love that.

I added the following code to my node--event.tpl.php to show a table of all results for the current node without a few unwanted results like e-mail.

```
        // Create connection
        $con=mysqli_connect("******","*******","********","*********");

        // Check connection
        if (mysqli_connect_errno()) {
          echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }
        // Get submitted data from current nodeform
        $result = mysqli_query($con,"SELECT data, cid, sid, nid FROM webform_submitted_data WHERE nid=".$nid);
        $data = array();
        $i =0;
        while($row = mysqli_fetch_array($result)) {
          $data[$i]['data'] = $row['data'];
          $data[$i]['sid'] = $row['sid'];
          $data[$i]['cid'] = $row['cid'];
          $data[$i]['nid'] = $row['nid'];
          $i++;
        }
        // Get headers for submitted data
        $result = mysqli_query($con,"SELECT name, form_key, cid FROM webform_component WHERE nid=".$nid);
        $headers = array();
        while($row = mysqli_fetch_array($result)) {
          $headers[$row['cid']]['name'] = $row['name'];
          $headers[$row['cid']]['form_key'] = $row['form_key'];
        }

        // Declare variables for composing table
            //unwanted fields
            $unwanted[] = 'productid';
            $unwanted[] = 'e_mail';
            $unwanted[] = 'algemene_voorwaarden';
        $newCello = '<td>';
        $newCellc = '</td>';
        $presid = (isset($data[0]['sid'])) ? $data[0]['sid'] : '' ;
        $tablehead = '<tr class="head">';
        $tabledata ='<tr>';
        $even = TRUE;
        //render table
        foreach ($data as $key) {
            if ($key['sid'] != $presid) {
                $tabledata .= "</tr>";
                $tabledata .= ($even) ? '<tr class="even">' : '<tr>' ;
                $firstrow = TRUE;
                $even = ($even) ? FALSE : TRUE ;
            }
            //filter unwanted fields
            $formkey = $headers[$key['cid']]['form_key'];
            if (!in_array($formkey, $unwanted)) {
                //create table headers
                if (!isset($firstrow)) {
                    $tablehead .= $newCello;
                    $tablehead .= $headers[$key['cid']]['name'];
                    $tablehead .= $newCellc;
                }
                $tabledata .= $newCello;
                $tabledata .= $key['data'];
                $tabledata .= $newCellc;

                //Get current field sid to compare with the next
                $presid = $key['sid'];
            }
        }

        $tablehead .= '</tr>';
        echo $tablehead;
        echo $tabledata;
        mysqli_close($con);
        ?>
        </tr>
    </tbody>
</table>

```
> 0 votes

# Answer
Try the Webform Report module, it looks perfect for what you need.

Or, Why not use views?

It would be easier to use webform 7.x-4.0-rc3 and create a view table for webform submission data. You can easily grab the separate values and arrange them into a table.

You also have the ability to create a reference so only the results from node 4 are being shown.

EDIT: use $node-\>nid; , so...

```
$nid = $node->nid;

module_load_include('inc','webform','includes/webform.submissions');
$submissions = webform_get_submissions(array('nid'=> $nid));

foreach ($submissions as $submission){
    foreach ($submission->data as $row=>$data){
        print '<pre>';print_r($row);print '</pre>';
        print '<pre>';print_r($data);print '</pre>';
    }
}

```
> 0 votes

---
Tags: theming, webforms
---


# Question
Title: Restrict node for anonymous user programmatically
First of all I've seen lot's of threads about restriction, but didn't find what I'm looking for.

So, my goal is to restrict the access for a specific node to anonymous users and when they try to enter that node, it will redirect them to the user/login page.

I was using Content Access module till now. It works like it should, but the problem is when this module is enabled, block caching is not working. As I know the Context module has the same issue.

I have one big menu block and without caching, the website is 4 times slower. When the Content Access module is disabled, the block is cached and the performance is great.

Let's say the url of the page is 'apple'.

I'm looking for a way to restrict only this page programmatically, without breaking the block caching.

I'm using Drupal 7.

# Answer
> 1 votes
hook\_init:

```
<?php
// Get the current active node object if present.
$node = menu_get_object();
// Redirect to login page if NID == 42 and user is anonymous.
// User will then go back to node page due to destination being set.
if (   user_is_anonymous()
    && !empty($node)
    && !empty($node->nid)
    && $node->nid == 42
    ) {
  drupal_goto('user/login', array('query' => array('destination' => 'node/' . $node->nid)), 307);
}
?>

```

hook\_boot:

```
<?php
$args = arg();
if (   user_is_anonymous()
    && isset($args[0]) && $args[0] == 'node'
    && isset($args[1]) && is_numeric($args[1])
    ) {
  drupal_goto('user/login', array('query' => array('destination' => 'node/' . $node->nid)), 307);
}
?>

```

---
Tags: caching, users
---


title: Link to exposed filter

text:
# Question
Title: Link to exposed filter
I have a view with two exposed filters. When a user changes the filter criteria, the results change accordingly. I need the URL that shows what the view is currently showing, with the current filter criteria.

How do I find the correct URL?

# Answer
> 1 votes
To find the generated URL for an exposed filter, select the filter in the view -\> scroll to the bottom -\> click More -\> look under Filter identifier. Copy and paste this after the url (e.g. www.mysite.com/myview?**field\_story\_category\_tid**=3). To identify a specific filter, get the number from the URL aliases page (admin/config/search/path).

---
Tags: views, navigation
---


# Question
Title: Show 1 random node out of the 5 most recent in views
I would like to create a block on my homepage where I show my visitors the most recent node (of a specific content-type) I've created. The block should load the 5 most recent nodes but only show one of them on page load.

I've managed to show a random product on page load, but the views takes a random node from all my nodes of that content-type. Is there a way I can limit the nodes, where the random block can chose from, to 5?

# Answer
> 2 votes
I wasn't able to get this working within views proper, so I added a subquery instead.

There are three relevant things that need to be set up in your initial view to get this to work:

1. Filter Criteria: Content: Type = 'my content type' (blog post in the attached image)
2. Sort Criteria: Global: Random
3. Pager: Use Pager: Display a specified number of items: 1

As it is, that will get you a view that will pull in 1 random result from among all content of type "my content type".

But the question is asking you to pull in 1 item from the last 5 created posts, not from all posts.

To do that, you need to add an additional where condition. That can be accomplished with this snippet:

```
/**
 * Implements hook_views_query_alter().
 *
 * Limits results to the most 3 recent blog posts.
 */
function MY_MODULE_views_query_alter(&$view, &$query) {
  if ($view->name == 'MY_VIEW_NAME' && $view->current_display == 'MY_CURRENT_DISPLAY') {
    $query->add_where_expression('AND', "node.created > (SELECT node.created AS created
      FROM
      node node
      WHERE  (type = 'MY_CONTENT_TYPE')
      ORDER BY created DESC
      LIMIT 1 OFFSET 5)");
  }
}

```

That snippet says: "Find me the creation timestamp of the node that is the fifth-newest. Then filter my final result by nodes with creation timestamps greater than that."

There might be a better way, but this works for me.

# Answer
> 0 votes
I know it's probably too late, but in the 'Pager' section, you can use a pager and 'Display a specified number of items'. You can choose to display 5 items and then in the 'Sort Criteria' section sort by the 'Post Date'.

This way the view will only look at the 5 most recent posts and then randomly choose from one of them.

---
Tags: 7, views
---


# Question
Title: Notify site users based on user account field (e.g. apt number)
I run a site for my condo, the HOA wants to setup a way to notify residents when they get a package, that needs to get picked up from the office.

In the users account settings their are both unit number and email fields.

How would you solve this problem?

# Answer
> 0 votes
I would use the Rules module

Rules

---
Tags: users, actions
---


# Question
Title: Applying image style to authors pictures in comments without preprocess function
Is there anyway I could apply an image style to the user picture in comments without using a preprocess function (YOURTHEME\_preprocess\_user\_picture?)

The reason I ask this is because the preprocess function scales and crops the user pictures and I can no longer use the uncropped version (the original) in Views for example.

Any and all help on this is greatly appreciated.

Thank you. :)

# Answer
You should be able to do it through straight css, or look into a module that will allow you to customize image styles for different applications.

.comment .user-picture

.comment .user-picture img
> 1 votes

# Answer
I found a module that will allow for applying styles to pictures in comments (and other pictures too, like avatars, node pictures, etc.) It did require a lot of tinkering for my site but it is working now. It can be found there: Imagecache Profiles

Instructions can be found there: How to use Imagecache Profiles
> 0 votes

---
Tags: users, comments, theming, media
---


title: Translating the title of a custom block

text:
# Question
Title: Translating the title of a custom block
I am using the Bluemaster theme on a Drupal 7 site. I want to translate my site and everything is OK, but the title of the block I adde is not translated and still shows as "User menu" even when the language is not English.

How can I change the block title so that it appears in the language set for the site?

# Answer
> 2 votes
Try this: in '/admin/structure/block' find your block, click on `configure` link beside it then in `Language setting tab` Check "Make this block's title translatable" Then Go to Translate interface admin/config/regional/translate/translate Then enter the block title above and limit search to "block"

# Answer
> 0 votes
Make sure to activate the module "Block Language" for this steps (from @Val Budkin) to work.

---
Tags: users, i18n-l10n
---


title: Set default menu link as default menu?

text:
# Question
Title: Set default menu link as default menu?
I have sub menu of Main menu. I need to set 2nd sub menu as default menu, so when user visit a site 2nd sub menu should open.

# Answer
> 0 votes
You can use the following modules

* Context : It allows you to highlight a menu item if certain condition has been met.
* Menu position : This module allows for the creation of rules that will dynamically add the current page into the menu system at the requested spots.

Reference:

---
Tags: routes
---


title: How do I migrate this module?

text:
# Question
Title: How do I migrate this module?
I just migrate my Drupal 6 website to Drupal 7 successfully, using migrate\_d2d module. Is there an easy way to migrate Drupal 6 xml sitemap to Drupal 7 too?

Should I just install the XML sitemap module in Drupal 7 and it'll create its own?

# Answer
Your D7 may not remain unchanged forever. When it change, you will want its sitemap to change in concert with the site. In other words, you need something like XML Sitemap on your site.

You should therefore install the XML Sitemap module (as you suggest yourself). The module actually has an upgrade path if you used the D6 version of the module to generate the D6 sitemap.

If your D6 sitemap was generated by some other means, or if you don't care about preserving the D6 settings for the sitemap, just install at as a fresh module on D7, and it will create a new sitemap.
> 1 votes

---
Tags: migrations, xml-sitemap
---


# Question
Title: drupal 7: my hook module make my site slow?
I create my own hooks module, in a simple frame (to test it) to change in exposed filter of view to 'All' , but when I enable this module, it's work fine but make my site slow .. and just when I disable it , my site back to fast, what is my mistake?

myhooks.info

```
name = my hooks module
description = hooks website module.
package = myhooks
core = 7.x

```

myhooks.module

```
function myhooks_form_views_exposed_form_alter(&$form, $form_state, $form_id) {
  if($form_id == 'views_exposed_form') {
    $form['name_list']['#options']['All'] = 'All';
  }
}

```

# Answer
I see two possible reasons:

1. You pass form state by value. It should be passed by reference. It is a really, really big array, so copying it when there is no need to may eat up quite a lot of memory, slowing down everything.
2. You alter `$form['name_list']['#options']` in all views exposed forms. But probably most of these forms does not have `name_list` element at all. So what you do can generate array items that are bad from form api point of view, slowing down form processing, and generate warnings. Server will not show you warnings, but it will save them to error logs, and writing to disk is slow.
> 1 votes

# Answer
I think the reason for the site becoming slow is the `$form_id`.

`views_exposed_form` is the `$form_id` of all the exposed forms, and will get applied to all the views with exposed filters. You could try filtering the exact view by something like `$form['#id']`.

Also, if you implement `hook_form_FORM_ID_alter`, you don't have to check the `$form_id` again inside the hook implementation.
> 0 votes

# Answer
$form\['name\_list'\]\['#options'\]\['All'\] = 'All'; -\> That return all result on the page .So loading process is very slow. If You need to fast the page that if you will check "**options\[expose\]\[required\]**" the check box .if exposed filter is not taken a empty or null value due to loading page .when enter the value that return all page.

Reference : https://drupal.org/node/138374
> 0 votes

---
Tags: hooks, views
---


# Question
Title: How to stop cache_field table from growing?
I have a website with **LOTS** of nodes and **LOTS** comments. I have lesser space in the hosting plan and don't wont to buy more. The cache\_field table of the site keeps on growing due to caching.

I disabled "Cache pages for anonymous users" in admin/config/development/performance and kept "Cache blocks" enabled. The current performance and load time with the current settings and after a cache clear is at an OK level. But still the cache\_field grows. Same with the "Cache blocks" disabled.

Due to the size of the site I feel that caching of nodes and comment are not necessary.

How to stop cache\_field table from growing?

More:

1. I'm ok with coding
2. I have a VPS with 20GB Disk, and **60% filled when cache is cleared**. Once I cleared the cache when it was **75% filled and growing (with the cached data)**.
3. Sorry for the late data I have 512MB ram.

# Answer
You could switch that cache bin so it uses something like file cache https://drupal.org/project/filecache

Also look into using memcache as that will evict the older cache data so that memcache stays within the parameters you give it.

Also consider optimizing the database; it should help to reduce the overhead http://dominiquedecooman.com/optimize-mysql-tables-gives-35-drop-disk-usage-drupal-7-performance-tip

Finally if you really want to disable that cache you can use the DrupalFakeCache backend for those cache bins https://drupal.org/node/797346
> 0 votes

# Answer
If it's VPS, then you probably have enough control over it to use APC or memcached. Modules that may help with it:

And probably more. But they all are based on the same philosophy:

1. Keep data in RAM, as disk access is slow
2. Have a limited amount of storage, that never can be crossed
3. If there is too much data, silently delete the least used elements

So just move cache\_field bin to RAM and all your problems should be solved.
> 0 votes

---
Tags: caching
---


# Question
Title: Where does drupal store content-type display settings?
I have several similar sites built by drupal. When I finished configuring one site, I wanna clone first site's setting to others(by importing SQL exported from the first site).But I can't find where drupal store content-type(ex:article)'s display setting in mysql?

# Answer
> 3 votes
By Default it stores in field\_config\_instance table.. For relevant code check below function in field.crud.inc file

```
function _field_write_instance($instance, $update = FALSE) {
  $field = field_read_field($instance['field_name']);
  $field_type = field_info_field_types($field['type']);

  // Set defaults.
  $instance += array(
    'settings' => array(),
    'display' => array(),
    'widget' => array(),
    'required' => FALSE,
    'label' => $instance['field_name'],
    'description' => '',
    'deleted' => 0,
  );

  // Set default instance settings.
  $instance['settings'] += field_info_instance_settings($field['type']);

  // Set default widget and settings.
  $instance['widget'] += array(
    // TODO: what if no 'default_widget' specified ?
    'type' => $field_type['default_widget'],
    'settings' => array(),
  );
  // If no weight specified, make sure the field sinks at the bottom.
  if (!isset($instance['widget']['weight'])) {
    $max_weight = field_info_max_weight($instance['entity_type'], $instance['bundle'], 'form');
    $instance['widget']['weight'] = isset($max_weight) ? $max_weight + 1 : 0;
  }
  // Check widget module.
  $widget_type = field_info_widget_types($instance['widget']['type']);
  $instance['widget']['module'] = $widget_type['module'];
  $instance['widget']['settings'] += field_info_widget_settings($instance['widget']['type']);

  // Make sure there are at least display settings for the 'default' view mode,
  // and fill in defaults for each view mode specified in the definition.
  $instance['display'] += array(
    'default' => array(),
  );
  foreach ($instance['display'] as $view_mode => $display) {
    $display += array(
      'label' => 'above',
      'type' => isset($field_type['default_formatter']) ? $field_type['default_formatter'] : 'hidden',
      'settings' => array(),
    );
    if ($display['type'] != 'hidden') {
      $formatter_type = field_info_formatter_types($display['type']);
      $display['module'] = $formatter_type['module'];
      $display['settings'] += field_info_formatter_settings($display['type']);
    }
    // If no weight specified, make sure the field sinks at the bottom.
    if (!isset($display['weight'])) {
      $max_weight = field_info_max_weight($instance['entity_type'], $instance['bundle'], $view_mode);
      $display['weight'] = isset($max_weight) ? $max_weight + 1 : 0;
    }
    $instance['display'][$view_mode] = $display;
  }

  // The serialized 'data' column contains everything from $instance that does
  // not have its own column and is not automatically populated when the
  // instance is read.
  $data = $instance;
  unset($data['id'], $data['field_id'], $data['field_name'], $data['entity_type'], $data['bundle'], $data['deleted']);

  $record = array(
    'field_id' => $instance['field_id'],
    'field_name' => $instance['field_name'],
    'entity_type' => $instance['entity_type'],
    'bundle' => $instance['bundle'],
    'data' => $data,
    'deleted' => $instance['deleted'],
  );
  // We need to tell drupal_update_record() the primary keys to trigger an
  // update.
  if ($update) {
    $record['id'] = $instance['id'];
    $primary_key = array('id');
  }
  else {
    $primary_key = array();
  }
  drupal_write_record('field_config_instance', $record, $primary_key);
}

```

It stores in above table data column as blob format... Sample example goes below inside blob..

```
a:6:{s:5:"label";s:7:"Comment";s:8:"settings";a:2:{s:15:"text_processing";i:1;s:18:"user_register_form";b:0;}s:8:"required";b:1;s:7:"display";a:1:{s:7:"default";a:5:{s:5:"label";s:6:"hidden";s:4:"type";s:12:"text_default";s:6:"weight";i:0;s:8:"settings";a:0:{}s:6:"module";s:4:"text";}}s:6:"widget";a:4:{s:4:"type";s:13:"text_textarea";s:8:"settings";a:1:{s:4:"rows";i:5;}s:6:"weight";i:0;s:6:"module";s:4:"text";}s:11:"description";s:0:"";}

```

# Answer
> 0 votes
Maybe I found the answer myself.

I use display suite, so export table with 'ds\_' prefix and import them to others is OK. If using the default display setting, datas probably stored in field\_config and field\_config\_instance..

---
Tags: nodes
---


title: How to import entities?

text:
# Question
Title: How to import entities?
When using nodes, I use the rather good Feeds Import module and all is well with the world. I now need to use an entity as don't need URLS, comments etc so have created one called 'Cars' and have various fields attached to this.

I now need to import 1000 cars but have no clue how to do it? Using nodes this is very simple from csv, xml etc but entity seems to have no such module.

Does anyone know what I need to use to do this? Would I need to create a custom script that connects directly to the mysql and that writes to the fields I created?

# Answer
it all depends on what functionality your entity provides. are you defining entity yourself or are you using some other module?

anyway simplest way is to create entity manually

```
$entity = entity_get_controller($entity_type)->create(array('bundle' => $bundle_type));//this could look this way ->create($bundle_type); depending on your constructor

$entity->your_field['und'] = $value;//assuming you don't use entity translation then language is und

entity_get_controller($entity_type)->save($entity);

```

in case your controller extends EntityAPIControllerExportable then you could use import/export but if you importing from external source probably custom code would be easier
> 1 votes

---
Tags: 7, entities
---


# Question
Title: How to layout the theme within the regions?
I'm very much beginner to the drupal and learning to themeing, and I'm confused how to make regions within the regions?

```
+----------------------------------------------------------+
| +--------------+                +---------------------+  |
| |              |                |                     |  |
| |    header1   |                |   header2           |  |
| |              |                |                     |  |
| +--------------+                +---------------------+  |
|                       header                             |
+----------------------------------------------------------+

```

page--front.tpl.php

```
<header>
   <div id="header1">
    .....
   <?php print render($page['header1']); ?>
   </div>

   <div id="header2">
    .....
   <?php print render($page['header2']); ?>
   </div>

<?php print render($page['header']); ?>
</header>

```

And I did the change in .info file like:

```
regions[header1]        = Logo Area
regions[header2]        = Search bar and Navigation

```

But it's not displaying as the picture describes better it:

---

**Update:**

The rendered html is like this:

```
<header role="banner" id="header" class="header">
    <div id="header1">

    </div>
    <div id="header2">

    </div>

<div class="region region-header">

</div>
</header>

```

But What I wanted to be like this:

```
<header role="banner" id="header" class="header">

<div class="region region-header">
    <div id="header1">

    </div>
    <div id="header2">

    </div>
</div>
</header>

```

# Answer
> 4 votes
You cannot make region within region. You can place block in a region. Fix the width of block and float that. You have to use only css to achieve that.

Print wrapper like this

```
<header>
<?php if($page['header1'] || $page['header2']) :?>
    <div class="region region-header">
    <?php if($page['header1'] ) :?>
        <div id="header1">
        <?php print render($page['header1']); ?>
        </div>
    <?php endif;?>
    <?php if($page['header2'] ) :?>
        <div id="header2">
        <?php print render($page['header2']); ?>
        </div>
    <?php endif;?>
    </div>
<?php endif;?>
</header>

```

# Answer
> 1 votes
you cannot put region into region, but you can fake it

```
<header>
  <div class="region region-header">
   <div id="header1">
    .....
   <?php print render($page['header1']); ?>
   </div>

   <div id="header2">
    .....
   <?php print render($page['header2']); ?>
   </div>

   <?php print render($page['header']); ?>
 </div>
</header>

```

now you dont want that extra div with classes to appear in header region so you theme it and remove div. create region--header.tpl.php

and put this inside:

```
<?php if ($content): ?>
    <?php print $content; ?>
<?php endif; ?>

```

---
Tags: 7
---


# Question
Title: Pass nid variable to Ubercart order in D7
How can I pass a node's nid variable to Ubercart so that when the user pays for publishing his node, the nid shows in the cart?

I tried to add a field to the Ubercart Order fields, with widget node reference which is passed by the URL. When my user clicks on "Pay for node" link, it sends him to the Ubercart "node" product page "pay?23" 23 being the node they are paying for. When the user presses Add to Cart, I cannot see this value 23 in any of the user's order or checkout details. How can I get this value attached to the order?

I've googled for a while now and cannot find anything about this for D7. Any help will be much appreciated!

# Answer
> 2 votes
1. If you are using Cart Links (`/admin/help/uc_cart_links`), you could pass a value for a text-field type of attribute on your product.
2. You'd have to add an attribute to the product node, and hide it via css or form\_alter method on the product view page so that they couldn't overwrite it or delete it.
3. When they add attribute to the cart with the cart link, you can feed in the value with the url parameter like ( `/cart/add/e-p23_q5_aThisNiceEscapedString`. ).
4. Note that you can't just pass an integer to it, or Cart Links will think you are passing the AID (attribute ID)

# Answer
> 0 votes
I guess you may populate your own custom order field \[ admin/store/settings/orders/fields \] from URL.

---
Tags: 7, ubercart
---


# Question
Title: Override html.tpl.php per node type does not work
I saw that this was asked few times before, and I tried the answers, and I tried modifying the answers, yet nothing.

Case:
I have **Advanced Forum** installed, and I am using HTML5 Application Cache (**appcache**) (don't you dear to run away now!).

Obviously I need to turn **appcache** off when surffing forums, and I managed to make custom `html.tpl.html` for `/forum` and `/forums`, so when I am looking forum list and topic list I won't get cached.

But then:
When I am looking at forum topic, it is a post ofc, and post type (machine type is `forum`) and I have defined in `template.php`:

```
$node = menu_get_object();

if ($node && $node->nid) {
    $vars['theme_hook_suggestion'][] = 'html__' . $node->type;
}

```

and it won't make change.

So I am able to change `html.tpl.php` for path but not for node type.

Help me please and correct my knowledge for making such things.

Thanks for all!!!
(btw i dont need a lesson of **appcache**, sincerely if you have manifest = x.appcache" in your html tag it will cache it, even if it's in network section)

# Answer
you don't need different template for this. you can set variable in preprocess function and print it.

```
function MYTHEME_preprocess_html (&$variables, $hook)
  $node = menu_get_object();
  $dont_cache = array('some_type');
  if (!empty($node->nid) && in_array($node->type, $dont_cache)) {//check if it is node and if it shouldnt be cached
    $variables['appcache'] = '';
  }
  else {
    $variables['appcache'] = 'manifest = x.appcache';//put your value here
  }
 }

```

and then print $appcache in you html.tpl.php
> 0 votes

---
Tags: theming, nodes, caching
---


# Question
Title: Why is my Strongarm feature immediately overridden?
I am using features to save a content type. Here are the fields that my new feature contains:

```
body  field_product_site_id  field_product_repair_price  field_product_manufacturer  field_product_description  field_product_terms  field_product_url  field_product_model  field_assigned_to  field_role_designater

node-product-body  node-product-field_product_description  node-product-field_product_manufacturer  node-product-field_product_model  node-product-field_product_repair_price  node-product-field_product_site_id  node-product-field_product_terms  node-product-field_product_url  node-user_role_marker-field_assigned_to  node-user_role_marker-field_role_designater

```

I decided to add the Strongarm module to capture additional fields (and hopefully save the field order/weights of my content types.) The strongarm module added a few new variables to the list:

```
 field_bundle_settings_node__product  menu_options_product  menu_parent_product  node_options_product  node_preview_product  node_submitted_product

```

After recreating the feature, I discovered that it had become overridden. As I understand it, features are only overridden if the data stored within it is difference that the data stored in the database. How can this feature be overridden as soon as it is created?

Edit =========================================

The feature now seems to be in the Default state. All I did was install the diff module. Could this have been a cache issue?

# Answer
I can't tell why it's telling you something is changed, but you can use Diff module to see what changed. Diff module
> 2 votes

---
Tags: 7, features, strongarm
---


# Question
Title: Is it possible to manage Drupal running on a Windows server using drush on linux via a Samba mount?
I have been trying to set up drush on my linux desktop (hereafter called client) to control a remote Drupal site running on Windows using XAMPP (herafter called server).

The Drupal root on the remote server is mounted via Samba on the client at this location : `/path/to/remote/server1/drupal`

I am using the following drush alias:

```
$aliases['drupalserver1'] = array(
  'root' => '/path/to/remote/server1/drupal',
  #'remote-host' => 'drupalserver1.mydomain',
  #'remote-user' => 'myuser',
  'uri' => 'http://drupalserver1.mydomain',
  'os' => 'Windows',
);

```

Now, as I understand it, this tells drush that it is a *local* installation of Drupal, not a remote one since I left commented the `remote-host` and `remote-user` entries.

Drush then reads the `settings.php` file on the server (via the samba mount on my client), which specifies `drupalserver1.mydomain` (rather than `localhost`) and the necessary other configurations.

Database connection is successful as is bootstrapping:

```
 Site URI                        :  http://drupalserver1.mydomain
 Database driver                 :  mysql
 Database hostname               :  drupalserver1.mydomain
 Database username               :  root
 Database name                   :  drupal
 Database                        :  Connected
 Drupal bootstrap                :  Successful
 Drupal user                     :  Anonymous
 Default theme                   :  acquia_marina
 Administration theme            :  seven
 PHP configuration               :  /etc/php5/cli/php.ini /home/myuser/.drush/php.ini
 Drush version                   :  5.9
 Drush configuration             :
 Drush alias files               :  /home/myuser/.drush/examples_example.aliases.drushrc.php /home/myuser/.drush/myorg.aliases.drushrc.php
 Drupal root                     :  /path/to/remote/server1/drupal
 Site path                       :  sites/default
 File directory path             :  sites/default/files
 Temporary file directory path   :  C:\xampp\tmp

```

Now, both the Drupal files (/path/to/remote/server1/drupal) and the mysql DB are hosted on a Windows machine, so using `'os' => 'Windows'` in the alias makes sense. I even wonder if this line is even taken into account since `remote_host` is not used.

Is there any hope that the configuration I am proposing works at all ?

Using Drupal 7.

# Answer
> 1 votes
In your case, `'os' => 'Linux'`. This variable tells Drush how to do things such as filesystem path escaping. As you supposed, this variable is primarily used during remote calls, but I believe it may occasionally be referenced when building commands that are used locally.

I have never tried to set up Drush as you describe above; in theory, it should be possible, as long as you can connect to the database, but you might run into some problems. Post issues in the Drush issue queue if you find bugs. PRs with fixes would be particularly welcome.

---
Tags: 7, drush
---


title: Convert seconds to time format

text:
# Question
Title: Convert seconds to time format
I have 10396080 seconds, and I want it to look like this: xxx hours, xxx minutes. Is there some function for that?

# Answer
> 1 votes
> I have 10396080 seconds, and I want it to look like this: xxx hours, xxx minutes. Is there some function for that?

Not really. What you want is 10396080 seconds converted to 2887 hours 48 minutes, and I know of now existing function that does that.

There is `format_interval()`.

```
 $seconds = 10396080;
 $string = format_interval($seconds, 2);
 echo $string;

```

But that will output "4 months 7 hours".

However, the following custom function:

```
 function _hoursminutes($interval, $granularity = 2, $langcode = NULL) {
   $units = array(
    '1 hour|@count hours' => 3600,
    '1 minute|@count minutes' => 60,
    '1 seconds|@count seconds' => 1,
  );  $output = '';
  foreach ($units as $key => $value) {
    $key = explode('|', $key);
    if ($interval >= $value) {
      $output .= ($output ? ' ' : '') .
        format_plural(floor($interval / $value), $key[0], $key[1], array(),
        array('langcode' => $langcode));
      $interval %= $value;
      $granularity--;
    }
    if ($granularity == 0) {
      break;
    }
  }
  return $output ? $output : t('0 second', array(), array('langcode' => $langcode));
}

 $seconds = 10396080;
 $string = _hoursminutes($seconds, 2);
 echo $string;

```

This will output: "2887 hours 48 minutes", which presumably what you want.

# Answer
> 0 votes
It depends what you mean - whether you want the hours and minute in the day, or an interval representation of the timestamp.

For the first, there's: `format_date()`

> Formats a date, using a date type or a custom date format string.

e.g.

```
$formatted_date = format_date($timestamp, 'custom', 'H \h\o\u\r\s, m \m\i\n\u\t\e\s');

```

For the second, you might get some use out of `format_interval`:

> Formats a time interval with the requested granularity.

But it might not do exactly what you want.

---
Tags: datetime
---


# Question
Title: Parameter comment must be on the next line at position 1
I review my module code with http://pareview.sh and it returns an error:

Line #94 - ERROR | Parameter comment must be on the next line at position 1

```
/**
 * Fetch node object properties. //<---  THIS IS LINE #94
 *
 * @param object $node contains information about campaign.
 *
 * @return array
 *   Webform properties.
*/

```

http://pareview.sh/pareview/httpgitdrupalorgprojectbounceconvertgit

If I add the comment on next line, it says: it requires a blank newline after it. How to fix this error?

# Answer
> 2 votes
As it clearly says *Parameter comment must be on the next line at position 1*...

Correct way of documenting your function is..

```
/**
 * Fetch node object properties.
 *
 * @param object $node
 *   contains information about campaign.
 *
 * @return array
 *   Webform properties.
 */

```

For more information on commenting standards check Drupal Coding Standards Documentation in D.O

---
Tags: 7, coding-standards
---


# Question
Title: Add checkbox setting to a multiple value field
I have an image field with unlimited values. I want to add a checkbox to each image to use this image on the homepage. I would then check for that value in tpl file. How do I add a checkbox setting to this field?

Looks like a user did it in this post but didn't state how: Add a configuration checkbox in field setting

# Answer
> 0 votes
You need to use field collections to group fields together.. Field settings is used for field configuration...

According to your requirement you would like to choose for each field value associated value to track whether image should be displayed or not in home page.. Field collections does this and have integration with views..

---
Tags: entities
---


title: Formless admin/config page

text:
# Question
Title: Formless admin/config page
I'm a n00b regarding Drupal (I'm using Drupal 7), and I learned how to do a simple form for a configuration page. Currently I have this code:

In toyotaec.info (this one will appear in the module 'configuration' link):

```
configure = admin/config/toyotaec

```

In toyotaec.module:

```
function toyotaec_menu() {
    return array(
        //...
        'admin/config/toyotaec' => array(
            'title' => 'Configuración de Toyota del Ecuador',
            'description' => 'Opciones de configuración de la base de datos de Toyota del Ecuador y acceso a los formularios de contacto',
            'page callback' => 'drupal_get_form',
            'page arguments' => array('toyotaec_configuracion'),
            'access arguments' => array('administer toyotaec pages'),
            'type' => MENU_NORMAL_ITEM,
        ),
        //...
    );
}

```

In an included - and reachable - script (assume the missing functions and constants exist, since I will not post the whole code):

```
function toyotaec_configuracion() {
    $form_specs_alt = array(
        'formularios' => array(
            '#markup' => sprintf(<<<MARKUP
<div class="forms">
    <span class="caption">Listados de los formularios</span>
    <ul class="form-results-menu">
        <li><a href="?q=%s/webform-results/table">Registros de Contacto (Tomebamba)</a></li>
        <li><a href="?q=%s/webform-results/table">Registros de Cotización (Tomebamba)</a></li>
        <li><a href="?q=%s/webform-results/table">Registros de Redirección</a></li>
        <li><a href="?q=%s/webform-results/table">Registros de Currículum</a></li>
        <li><a href="?q=%s/webform-results/table">Registros de Solicitudes de Actualización de Software de Chasis Prius 3g</a></li>
    </ul>
</div>
MARKUP
                , drupal_lookup_path('source', FORM_ALIAS_CONTACTO)
                , drupal_lookup_path('source', FORM_ALIAS_COTIZAR)
                , drupal_lookup_path('source', FORM_ALIAS_SELECCIONAR)
                , drupal_lookup_path('source', FORM_ALIAS_TRABAJA_CON_NOSOTROS)
                , drupal_lookup_path('source', FORM_ALIAS_CAMPANIA_SERVICIO_3G)
            )
        )
    );
    if (!user_access('access all webform results'))
    {
        $form_specs_alt = array();
    }
    $form_specs = array(
        'nuevos_numeros_de_chasis' => array(
            '#type' => 'managed_file',
            '#title' => t('Números de Chasis'),
            '#description' => t("Archivo .csv con el contenido de la tabla de chasis necesarios para la actualización"),
            '#required' => false,
            '#upload_validators' => array(
                'file_validate_extensions' => array(0 => 'csv'),
                'file_validate_size' => array(32*1024*1024),
            ),
        ),
        'instrucciones_nuevos' => array(
            '#markup' => '<div class="instrucciones">Para obtener el archivo necesario, tome el archivo de hoja de calculo (formato .xls o .xlsx, de Microsoft Excel) de chasis registrados y, seleccionando la primer hoja de cálculo, vaya al menú "Archivo" > "Guardar como", y elija el formato "csv". Luego, en los campos más abajo en este formulario, coloque respectivamente el archivo exportado.</div>'
        ),
        'adjuntar' => array(
            '#type' => 'checkbox',
            '#title' => 'Conservar las entradas anteriores (no se incluirían los números repetidos)',
            '#attributes' => array('checked' => 'checked'),
            '#order_by' => 'text',
            '#sort_oerder' => 'asc'
        ),
        'borrar' => array(
            '#attributes' => array("style" => "min-width: 150px; min-height: 150px"),
            '#type' => 'select',
            '#title' => 'Elementos a borrar',
            '#multiple' => true,
            '#options' => array(),
        ),
        'instrucciones_existentes' => array(
            '#markup' => '<div class="instrucciones">Puede borrar uno o más números de chasis existentes. Mantenga la tecla Ctrl presionada al mismo tiempo que hace click sobre un elemento para seleccionarlo sin perder los anteriormente seleccionados. De esta forma usted podrá seleccionar más de un elemento en simultáneo para su eliminación.</div>'
        ),
        'instrucciones' => array(
            '#markup' => '<div class="instrucciones">El proceso de actualización consistirá en lo siguiente:<ul><li>Se borrarán aquellas entradas que se hayan seleccionado en la lista anterior.</li><li>Si no está seleccionada la tilde para conservar las entradas anteriores, y se sube un archivo, entonces todas las entradas se eliminarán.</li><li>Se agregarán las entradas incluídas en el archivo, si el mismo fue subido y es un archivo válido.</li></ul>Puede omitir la carga del archivo o el borrado de elementos existentes.</div>'
        )
    );
    $form = system_settings_form($form_specs_alt + $form_specs);
    array_pop($form['#submit']); //no quiero que me guarde variables de configuracion
    return $form;
}

```

This whole code **works** \- have no trouble at all with it - and creates an administration **FORM** which is displayed in the admin module pages and overlay.

**My question is**: How can I do to create a **SIMPLE** page - suitable for the admin module pages and overlay - with no form (in this case I use system\_settings\_form) at all?

# Answer
> 2 votes
Create a new hook\_menu entry but as 'page callback' use a custom function. That custom function must return the content that will be delivered to user (as a renderable array or HTML code).

Maker sure your path is under admin/config/\*.

Something like this:

```
    'admin/config/toyotaec-antoher' => array(
        'title' => 'Configuración de Toyota del Ecuador',
        'description' => 'Opciones de configuración de la base de datos de Toyota del Ecuador y acceso a los formularios de contacto',
        'page callback' => 'my_custom_function',
        'access arguments' => array('administer toyotaec pages'),
        'type' => MENU_NORMAL_ITEM,
    ),

```

And:

```
function my_custom_function() {
  return '<div>My custom page content.</div>';
}

```

---
Tags: 7
---


# Question
Title: Assessing admin when site is not hosted in the root of the domain
We set up a site with a url like www.mysite.com the site is being served by a proxy to come up as

www.theirsite.com/mysite/

We set $base\_url to www.theirsite/mysite

This is working correctly to load all the assets on the page but does not work on the admin.

The admin login and all pages on the admin try to post to the root of www.theirsite.com so for instance the /user page tries to post to www.theirsite.com/user this is obviously not working.

We tried clearing the cache on drupal to rebuild all urls as was recommended on many sites, but did not have any effect.

We are hosting our site via iis7 on windows. The version of Drupal is 7.2

What can be done to fix the admin form urls?

# Answer
> 0 votes
Our solution was to create a virtual folder mysite and host the site as www.mysite.com/mysite

After that the proxy was pointed to the new virtual folder. This made the admin work correctly.

This is not a satisfying answer as it still leaves unanswered how to control the admin form urls

---
Tags: uri
---


# Question
Title: How do I create an exposed filter for a localized taxonomy term?
How do I create an exposed filter for a localized taxonomy term? My vocabulary is set to 'Localize' and I'm able to create a translation for each term in this vocabulary. In my View, however, I can't add a localized taxonomy term to the filter. This is an exposed filter and I'd like the selection items to show up in the user's language.

How do I display localized taxonomy terms in a filter?

# Answer
you need to install i18nviews module and then use one of these:

* Content: Has taxonomy term (translated)
* Content: Has taxonomy terms (with depth, translated)

instead of regular filters
> 1 votes

---
Tags: views, i18n-l10n
---


title: Cannot make query substitutions

text:
# Question
Title: Cannot make query substitutions
I am using Drupal 7 and Views 7.x-3.7 . I am trying to display posts on my site using a SQL query that looks like this:

```
SELECT DISTINCT node.title AS node_title, node.nid AS nid, node.language AS node_language

FROM

{node} node

ORDER BY node_title ASC

```

The problem with this query is that if I have multiple posts with the same title,then all are being displayed because the nid, which is the primary key, was added by Drupal. I have been trying to remove the nid by using the `hook_views_query_substitutions()` method, but I have had no success. The method is getting called, but my query is not being updated.

I call zz\_views\_api() from my zz.module, and have the following zz.views.inc

```
function zz_views_query_substitutions($view) {
  // description of  zz_views_query_substitutions().

  return array(
    'node.nid AS nid,' => ' ',
  );
}

```

# Answer
I think this is a similar situation to a question I asked a little while ago.

I solved it by using `hook_views_query_alter()` to remove the fields I didn't need in the query. In your case, it would probably look like:

```
function MYMOODULE_views_query_alter(&$view, &$query) {
  if ($view->name == 'MY_VIEW') {
    unset($query->fields['nid']);
  }
}

```

`dpm()` the `$query` to see what array keys are in `$query->fields` if that doesn't work.
> 1 votes

---
Tags: hooks, views, database
---


# Question
Title: Properly building array and using with drupal_json_encode()?
I am trying to pass data from my database to a javascript variable, however I'm not sure if I'm correctly using `drupal_json_encode()`, or correctly building my 2D array.

When I check my console, the javascript variable only displays `[]`, so the data is not being passed.

I know this isn't the very best way of doing this, but I am only trying to make a functioning prototype, and not a finished product

Here is a portion of my php code that is making the sql query, as well as the 2D array, and is located in my `page--front.tpl.php`:

```
<?php
$server = 'db.*****';$user = '*****';$database = '*****';$password = '*****';
$db = mysqli_connect($server, $user, $password, $database);

  if (isset($_GET['routeselected']))
  {
  $result = mysqli_query($db, "SELECT * FROM STOP INNER JOIN RouteStop ON Stop.Stop_ID = RouteStop.Stop_ID WHERE RouteStop.Route_ID = " . (int)$_GET['routeselected'] . " AND RouteStop.Company_ID = " . (int)$_GET['companyselected']);
  $items = array();
  while (($row = mysqli_fetch_array($result))){
      $markers[$row['title']] = array($row['Stop_ID']);
      $markers[$row['lat']] = array($row['Latitude']);
      $markers[$row['lng']] = array($row['Longitude']);
      $markers[$row['description']] = array($row['StopName']);
      }
    drupal_json_encode($markers);
    drupal_add_js(array('markers' => drupal_json_encode($markers)), 'setting');
  }
  ?>
];

```

and here is my google map javascript that is in my js folder and is being implemented to the front page via `drupal_add_js`:

```
var map = null;
var infowindow = new google.maps.InfoWindow();
var markers = [Drupal.settings.markers];

window.onload = function () {

var mapOptions = {
    center: new google.maps.LatLng(
        parseFloat(markers[0].lat),
        parseFloat(markers[0].lng)),
    zoom: 13,
    mapTypeId: google.maps.MapTypeId.ROADMAP
};
var path = new google.maps.MVCArray();
var service = new google.maps.DirectionsService();
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var poly = new google.maps.Polyline({map: map, strokeColor: '#F3443C'});

var lat_lng = new Array();
           for (i = 0; i < markers.length; i++) {
           var data = markers[i]
           var myLatlng = new google.maps.LatLng(data.lat, data.lng);
           lat_lng.push(myLatlng);
           var marker = new google.maps.Marker({
               position: myLatlng,
               map: map,
               title: data.title
           });
           (function (marker, data) {
               google.maps.event.addListener(marker, "click", function (e) {
                   infoWindow.setContent(data.description);
                   infoWindow.open(map, marker);
               });
           })(marker, data);
       }
for (var i = 0; i < markers.length; i++) {
    if ((i + 1) < markers.length) {
        var src = new google.maps.LatLng(parseFloat(markers[i].lat),
                                         parseFloat(markers[i].lng));
        var des = new google.maps.LatLng(parseFloat(markers[i+1].lat),
                                         parseFloat(markers[i+1].lng));
        service.route({
            origin: src,
            destination: des,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        }, function (result, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
                    path.push(result.routes[0].overview_path[i]);
                }
                poly.setPath(path);
            }
        });
    }
}
}

```

Does anyone possibly know a solution to my issue? Thank you for all and any help!

# Answer
> 2 votes
`drupal_add_js(array('markers' => drupal_json_encode($markers)), 'setting');`

Should be

`drupal_add_js(array('markers' => $markers), 'setting');`

See https://api.drupal.org/api/drupal/includes!common.inc/function/drupal\_add\_js/7. You will probably want to remove the `drupal_json_encode($markers);` as well.

Also noted that you should use db\_query instead of mysqli\_connect/mysqli\_query https://stackoverflow.com/questions/11369447/drupal-7-db-query

# Answer
> 0 votes
Modify mysql fetch array statement like

```
$key = 0;
while ($row = mysqli_fetch_array($result)){

      $markers[$key][$row['title']] = $row['Stop_ID'];
      $markers[$key][$row['lat']] = $row['Latitude'];
      $markers[$key][$row['lng']] = $row['Longitude'];
      $markers[$key][$row['description']] = $row['StopName'];
      $key = $key + 1;
}

```

and add Js like

```
drupal_add_js(array('markers' => $markers), 'setting');

```

Fatch that value in JS like

```
var markers = Drupal.settings.markers;

```

---
Tags: javascript, google-maps
---


# Question
Title: Does Commerce Physical Convert Imperial to Metric?
Developing a commerce for an international audience and would like to be able to show the sizes (dimenstions of the pieces) in both SI and Imperial. I was approaching this by simply having to Height and Width fields for both SI and Imperial, but wondered if this was the best approach. At least right now, I don't have to figure the dimensions into my pricing logic so I wanted to know if Commerce Physical had conversion capabilities that might let me clean up my layout a little bit? I can forsee using their logic as the site develops, but for now it's unnecessary. So, does Commerce Physical convert units? and or does anyone have advice on approaching this? Thanks!

# Answer
Commerce Physical invokes `physical_dimensions_convert` which is part of the Physical module. This provides a means to converting data between Metric and Imperial.

`physical_dimensions_convert` is on line 771 of Physical module - http://drupalcode.org/project/physical.git/blob/refs/heads/7.x-1.x:/physical.module#l771
> 1 votes

---
Tags: commerce
---


title: 302 Redirect with cron.php

text:
# Question
Title: 302 Redirect with cron.php
On a rather old drupal site (D5) I get a 302 on calling cron.php when doing this via wget or curl. It worked fine for many years (via crontab). If I use a browser for that I get a 200 and a blank page (which is normal) the cron runner runs successfully. After trying to find a solution for a couple of hours it works fine with curl for no apparent reason, but not with wget and only if I run it directly (still 302 with crontab). As I type this I try again just to make sure and now neither wget nor curl work anymore, but running it through the browser still works just fine. Strange.

```
curl: curl -s http://www.mysite.com/cron.php
wget: wget -O - -q -t 1 http://www.mysite.com/cron.php

```

Any ideas?

# Answer
> 2 votes
302 redirect can happen due to Either server settings or manual redirect inside modules using functions like `drupal_goto`....

You need to debug to understand the problem.. Here are the steps to find out where it is going wrong...

* To make sure it's not related to server settings go and comment below line in `drupal_cron_run` function inside `includes/common.inc`...

```
// module_invoke_all('cron')

```
* If you cannot able to replicate 302 error then it's for sure some module which is implementing hook\_cron is doing above redirect other wise check your `.htaccess` or server settings to debug more..
* If you don't see 302 error go and uncomment above code you have commented to debug further...
* Run below code in any page to understand which are modules implementing hook\_cron.....

Code:

```
foreach (module_implements('cron') as $module) {
  drupal_set_message($module);
}

```
* Verify all above modules which implements hook\_cron doesn't have any redirect code.. Check custom modules in particular...
* If nothing works.. Use Debugger like XDebug to debug step by step.

---
Tags: cron, 5
---


# Question
Title: adding css in fresh.css nothing change is made
I'm using sub theme zenophile and created sub theme and now in my own sub theme I added some css rules in fresh.css but it's changing nothing.

I did clean refresh, but nothing happening...

# Answer
You need to tell your theme to pickup your css file.. You can do that using .info file of theme using below code..

```
stylesheets[all][] = fresh.css

```

Clear Drupal Cache to see changes...

For more information refer Writing theme.info files...
> 1 votes

---
Tags: 7
---


# Question
Title: How do I use an image as term reference in Drupal 7 and Commerce Kickstart?
I want to display a list of fruits in flavours taxonomy. I can easily display the term as term reference but I want an image (specifically the taxonomy image) as the list and clicking the image of the taxonomy the main image of the product should change, i.e. when clicked in strawberry it should show up strawberry cake.

Its term reference is working perfectly fine but I just want the images in place of text. I have done with color and it works fine. In other words I need a solution for how to display taxonomy image in the same way as they display color in Commerce Kickstart.

# Answer
> 2 votes
\[Acknowledgement: The solution given in comments to self by Saurav works. Since Saurav hasn't been seen in nearly a year, and comments are ephemeral at SE, I've taken the liberty of expanding the solution suggested in these comments into a full answer, so that the question and answer shall not be deleted as "abandoned" as defined on SE.\]

First, install and enable the **Commerce Fancy Attributes** module.

Then, follow the steps suggested under "Example usage" on the **Commerce Fancy Attributes** project page, but instead of adding a text field, add an image field for Vocabulary and add the image you want to display:

1. Create an Image vocabulary. Add an image field that shall hold the images you want to use.
2. Go to the "Manage Display" screen of that vocabulary, click the tab called "Add to Cart form - Attribute", enable only the Image field (with the label hidden).
3. Create several terms with images associated. Use the image small icon size so that the display wont be distorted.
4. Add an Image `taxonomy_term_reference` field to a product type.
5. When you add the Image field on the product type, tick the checkbox "Enable this field to function as an attribute field on Add to Cart forms". For the "Attribute selection widget", and choose the type "Rendered term".

Example:

---
Tags: commerce, taxonomy-terms
---


# Question
Title: How to add multiple field groups to a node
I have a node type "Project", and users can add multiple tasks for this Project node. e.g. There is a Project named "Building website", it contains two tasks "Design" and "Code", and every Task has another two fields: time and budget.

The **Field Group** module can solve part of the problem, it can mix multiple fields into one field. But this mixed field amount can only be 1. That means I can only add one Task field in a Project, however I need add unlimited Task field to Project. Do you know any modules can do this job?

# Answer
> 1 votes
**Field collection Modules**

Provides a field-collection field, to which any number of fields can be attached.

A field collection is internally represented as an entity, which is embedded in the host entity. Thus, if desired field collections may be viewed and edited separately too.

---
Tags: nodes, entities
---


# Question
Title: Form data get converted into uppercase at the time of saving
I have big drupal form and when the form get save, at that time I need all form data should be converted into upper case and then should get save.

# Answer
> 0 votes
You can alter node data before saving using hook\_node\_presave which will be implemented in a custom module... You can read values and change it to uppercase using strtoupper php function...

OR

You can simply use Simple Field Formatter module

Project page says

> The Simple Field Formatter module allows site administrators to easily control the display of field values with following features

Features:

Prepend the field value with specified text/HTML

Append the field value with specified text/HTML

Reverse the Field Value

Trim the Field Value

Convert the field value to lowercase letters

**Convert the field value to uppercase letters**

Convert the first character of the field value to uppercase

Convert the first character of each word in the field value to uppercase (7.x-1.x-dev)

Replace some characters with some other characters in the field value (7.x-1.x-dev)

Link the field value to node(7.x-2.x-dev)

---
Tags: forms
---


# Question
Title: header("Location: /") redirect in template file only works if user is logged in. Why?
I was developing a new feature for a client, and deployed it live today. However, due to circumstances out of my control, they decided to implement an alternative solution and asked me to implement a temporary redirect.

This feature was a standalone full screen flash app that did not fit the site theme at all. So, I implemented the page as a custom `html--pagename.tpl.php` file and loaded the page-specific JS and CSS. It is a custom template for an existing content type.

Now, since the client wants a temporary redirect, I added

```
header("Location: /");

```

as the first line of PHP code in the template to redirect any access to that URL to the index page. However, this only works if the user is logged in. Anyone else can view this page and the header code seems to be ignored for some reason.

This URL loads regardless of the Published status set to Published or Unpublished. In the morning, I will modify the `.htaccess` to execute a 302 redirect, but would like an explanation for this behavior for future reference.

# Answer
Output of the tpl files is cached for anonymous users. But only their text output is, that's how Output Control Functions in PHP works. That's why Drupal API functions will not work as intended, either. They may do their job, all right, by serving as cache breakers, but you do not want to break cache on a busy website, as it may be a server killer.

Most stable way of doing temporary redirections is, as far as I found, an .htaccess way. mod\_rewrite is already used by Drupal, so it cost you nothing in additional binaries loaded to memory, and it acts before PHP is even started. As described in this answer on SO, you can do this like that:

```
RewriteRule ^example/my-stuff/$ /example/home/ [L,R=301]

```

Put it before Drupal redirects, but in the same section.

If you need a PHP logic to decide if redirect is needed, you can do it using `hook_menu_alter()` instead:

1. Substitute original callback with yours
2. Perform any logic needed
3. Log to watchdog if you want to
4. * Call original callback and return it's result if you are not redirecting, or
    * Redirect with `drupal_goto('<front>')`
> 3 votes

# Answer
If you work drupal try to use drupal API, Drupal has simple api to redirect Drupal\_goto

For redirecting to another url just need `drupal_goto('url');`
> 0 votes

---
Tags: theming, redirection
---


title: Add Google Plus link to head

text:
# Question
Title: Add Google Plus link to head
I'm trying to add a Google Plus html tag via direct linking (see here) to my head but can't get it to work. What I'm trying is this inside my template.php file:

```
$googleplus = array(
    '#tag' => 'a',
    '#attributes' => array(
        'rel' => 'publisher',
        'href' => 'https://plus.google.com/+MyPage'
    )
);
drupal_add_html_head($googleplus, 'googleplus');

```

Nothing shows up for me. Is there a better/working way of doing this?

# Answer
Create block and place in Header Top. Go to Structure -\> Block -\> Add Block, then in Block body, write custom HTML. **Below block body, Text format should be in "FULL HTML" to display the image.**

```
<a href="https://www.google.com/.." target="_blank"><img src="YOURIMAGE" width="64" height="64"></a>

```

I think it will work.
> 3 votes

# Answer
Just came across this from a google search, and what I think you want to do is add a LINK or an A tag to the head section of your html page to tie together your Google+ page and your website..

This worked for me in template.php - remember to clear cache:

```
function YOURTHEMENAME_preprocess_html(&$vars) {
  $googleplus = array(
   '#tag' => 'link',
   '#attributes' => array(
     'href' => 'https://plus.google.com/GOOGLEPLUSACCOUNT',
     'rel' => 'publisher',
    ),
  );
 drupal_add_html_head($googleplus, 'googleplus');
}

```
> 1 votes

# Answer
Just like J singha said, create a block (full html) and as body you paste a the link google gave you. After you have submitting, you will see a Google+ link appear on the place where you have placed your block.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Attachment node field vs. file fields in a content view
Sorry, can't think of a better title...

I've created a content view for a specific content type where each node has lots of attached files in one 'attachment'' field.

I want a table of files with columns for file description and file size, grouped by node title.

This is (almost) fine if I use the Nodes 'attachment' field, giving me a list of files (one per row) with the file name or (even better) the file's description.

However, if I want the file size, I create a relationship to File Usage, but this creates a combinatorial explosion in the number of results, returning one file size per file linked to the node per file row...

If I remove the attachment field, just getting the file name and size, its fine. But I want the file description and the size.

The thing is the description seems to be a node property but the size is a file property and the relationship is at the node level, not the file level.

# Answer
> 0 votes
If I drop the relationship, I found that changing the file formatter to 'table of files' shows the size column. Magic. Gives me 98% of what I want, so I'm happy enough.

---
Tags: views, files
---


# Question
Title: Which drupal function can you use to invoke a function stored in contrib module (e.g. in an .inc file)?
Which drupal function can you use to invoke a function stored in contrib module

# Answer
> 7 votes
You can use `module_load_include`

```
  // Load node.admin.inc from the node module.
  module_load_include('inc', 'node', 'node.admin');
  // Load content_types.inc from the node module.
  module_load_include('inc', 'node', 'content_types');

```

Then you will be able to call the function that is in those files.

# Answer
> 5 votes
When you install and enable a contributed module, its functions become part of your Drupal instance runtime environment, and it can be called from other modules (including a custom module created by you). You can call it directly - there is no need to go through a specific function.

Like the Drupal core, some contributed modules has an API that is made up of functions that other modules may call. These functions are designed to be called from other modules, and is usually better documented with the intention of letting them be used by third parties.

If your Drupal site for some reason has not enabled the module, you can still bring it into scope with the use of `module_load_include`, or with the standard PHP directive `require_once`.

The difference between these two methods is that before you can call `module_load_include`, Drupal must to be loaded fully (Fully Bootstrapped). However, it is smarter than `require_once` because it references the module's path when locating the file, using `drupal_get_path().`

Syntax:

```
 module_load_include($type, $module, $name = NULL);

```

Example:

```
 module_load_include('inc','module_name','file_name');

```

Note that you don't have to specify any path to use `module_load_include`.

On the other hand, you can use `require_once` *before* Drupal is fully bootstrapped, but you need to supply the `DRUPAL_ROOT` and the full path to the module:

Example:

```
 require_once DRUPAL_ROOT . '/sites/modules/contrib/file_name.inc' .

```

Otherwise, these two methods for bringing the functions in a contributed module into scope is equivalent.

---
Tags: 7
---


# Question
Title: Avoid PDOException while connecting to an external database
I'm trying to connect to another database (not related to drupal) in drupal to show extra info. This database server could be down and is not a problem, if it's the case I don't want to show the info with no errors, maybe an info message that is now available at this moment.

I setted up the settings.php correctly with the database credentials, and when the database is up, everything is ok.

I use the next code

```
  db_set_active('external');
  $query = db_select('extra_info', 'i');
  ...

```

If the database is down, the db\_select() fails and throws an PDOException. The problem is the website is down in that case, shows the error and so on. I tryed to sorround it in a try catch.

```
  try {
      db_set_active('external');
      $query = db_select('extra_info', 'i');
      ...
  }
  catch (PDOException $e) {
      // Ok.. is not a problem
  }

```

I don't know if there is a way to check if the database connection is ok first and then do the select or do nothing if is there is a problem and continue showing the website. I tried the isActiveConnection() function, but I think is not what I need.

Thanks.

**EDIT: The solution to my problem is to use db\_set\_active() back to default.**

```
  try {
      db_set_active('external');
      $query = db_select('extra_info', 'i');
      ...
      db_set_active(); // This won't be executed!
  }
  catch (PDOException $e) {
      // Ok.. is not a problem
      db_set_active(); // Needed!
  }

```

# Answer
issue is that db\_set\_active just sets active key in some array and doesn't do any connection. when you do db\_select or any other query only then it connects.

your second code is good. also you could do something like this:

```
  db_set_active('external');
  try {
   //check connection
   db_select("select 1");
  }
  catch (PDOException $e) {
      //error. set default back
      db_set_active('default');
  }

```

as you know how to check if connection is there now you just need extra logic what todo when connection cannot be established
> 3 votes

---
Tags: database
---


# Question
Title: Check if a module is enabled with JavaScript
How do I check if a module is enabled using JavaScript? I want to avoid unnecessary Ajax calls that cause 403 errors since the module is not enabled.

```
if (mymodule_exist) {
  // Make an Ajax call.
  jQuery.ajax({
    url: "/player/status",
    type: "POST",
    async: false,
    success: function(data) {
      player_value = data;
    }
  });
}

```

I am trying to do something like this. How do I do it efficiently?

# Answer
> 6 votes
You can check module is enabled or not using module\_exists function... Ideally your .module which checks for above condition and sets variable for `JavaScript` file goes below..

See detailed steps below on adding this condition

* Create a folder called 'custom' in `sites/all/modules`
* Create a folder called 'mycustomjs' in above custom folder
* Create a file called 'mycustomjs.info' inside above folder with

below code

```
name = My Custom JS Alters
description = A custom module to interact with JS
core = 7.x
package = Custom

```

Create a file called mycustomjs.module inside 'mycustomjs' folder with below code

```
<?php

function mycustomjs_preprocess_page(&$vars) {
  $module = "MODULENAME"; // Change modulename to module you want to verify
  $does_module_enabled = module_exists($module);
  if ($does_module_enabled) {
    drupal_add_js(array('MODULENAME' => array('enabled' => TRUE)), 'setting');
  }
  else {
    drupal_add_js(array('MODULENAME' => array('enabled' => FALSE)), 'setting');
  }
}

?>

```

For more information See the Creating Drupal 7.x modules if you're not sure

# Answer
> 10 votes
I can think of two ways:

* Send a JavaScript flag as settings, indicating the module is active:

```
drupal_add_js(array('my_module' => array('enabled' => TRUE)), 'setting');

```
* If the module is enabled, modify the output in some way so the JavaScript code that makes the petition is included only when your module is enabled, or the contrary way, make sure that code is not included if your module is disabled: you will have to use another module or some kind of configuration. The exact way depends on the origin of the JavaScript code that makes the Ajax petitions.

---
Tags: 7, ajax
---


# Question
Title: CTools modal with webform unable to close
I'm using the CTools modal with a webform, the form comes in via ajax. When a user is logged in, all works normally. If an anonymous user clicks on the link for the modal, I'm seeing the following behavior:

* CTools modal close button does not work. No js errors.
* The 2nd time the link to display the modal is clicked, the page links directly to the form page (no ajax, no modal).

For logged in users, the close button works and the button to trigger the overlay behaves properly on repeat clicks.

Any tips greatly appreciated.

# Answer
> 0 votes
We figured it out - this was being caused by the ThemeKey module. The base page was one theme, and the ajax call was requesting default theme, trigging a reload of all the javascript.

The solution is to enable 'Bypass a request forgery protection in theme selection for Ajax responses.' and select the safe themes.

---
Tags: ajax, chaos-tool-suite, javascript
---


# Question
Title: Why EVA display of views is added to the manage display of content type?
There are three related content types in my website: article, sub-article, number-article. there is an entity reference from `number-article` to the `sub-article` and an entity reference from `sub-article` to the `article`. There are two views that displays these relations and in each one there is an EVA display. in the manage display of `sub-article` content type I saw this:

content of `numberarticle` is set to `all content types`, so why a display if view is added to a content type and how does Drupal find out where it should be?!

# Answer
From the EVA project page:

> "Eva" is short for "Entity Views Attachment;" it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity.

(...)

> The placement of the view in the entity's content can be reordered on the "Field Display" administration page for that entity, like other fields added using the Field UI module.

Apparently it did just what it claims it does.
> 2 votes

---
Tags: views, nodes, entities
---


# Question
Title: How to get value from field added in user settings
I am writing a module that performs a redirect based on what value was in a custom field called "field\_account\_type" that was added in user settings. How do I store this value in a variable within hook\_user\_login()?

# Answer
> 5 votes
You can access `global $user` custom field values in the hook that suits you like this :

```
function your_hook() {
  global $user;
  $current_user = user_load($user->uid);
  $vars['account_type'] = $current_user->field_account_type[LANGUAGE_NONE][0]['value'];
}

```

---
Tags: 7, entities, users
---


# Question
Title: Upload an image in a form programmatically
I'm doing a form programmatically. I need to give an option to upload an image and give an option to resize it ( like cropping option ).

I don't know how to do it, I know that I need to upload the image to a directory and also I suppose that I need to show a relation between the node and the image in the database.

I've created a field called `field_img.`

So, how can I do it?

This is the form that I've done but I don't know how to give a relation in the database...

```
form['group_anuncio']['imagen'] = array(
        '#title' => t('Image'),
        '#type' => 'managed_file',
        '#upload_validators' => array('file_validate_extensions' => array('jpeg jpg png gif')),
        '#upload_location' => 'public://sites/default/files',
        '#progress_indicator' => 'throbber',
        '#status' => FILE_STATUS_PERMANENT,
        '#progress_message' => 'One moment while we save your file...',
);

```

# Answer
I would strongly suggest to use nodes and one of these modules
Comparison of image cropping and resizing modules

If you dont want nodes then you still should be able to use one of crop modules which works with image fields if you use entities, you can use Entity Construction Kit (ECK) module to create custom entity types
> 1 votes

# Answer
The best practice is to use the File Entity module with the entity approach. When you have installed it, the points are:

* Create a form input (you've made it)
* Store the new file in a temp folder
* Create a new File() object
* Use the save() method

This method will store your file like an object, and will be easy to recover it as you want
> 0 votes

---
Tags: forms, media
---


title: RSS feed without Styling

text:
# Question
Title: RSS feed without Styling
I have a Drupal 7 webiste. I want RSS feed from a few views in my Drupal webiste. I am able to get the feed but the .xml file has a lot of CSS styling in the description tag which is causing me some issues in the RSS reader. I want to get rid of the CSS styling in the description tag. Can anyone help ?

Thanks.

# Answer
> 0 votes
you can copy views-view-row-rss.tpl.php to your theme folder and then

```
<description><?php print $description; ?></description>

```

replace with

```
<description><?php print preg_replace("/<style\\b[^>]*>(.*?)<\\/style>/s", "", $description); ?></description>

```

it will remove css

if you also have inline styles then you need this

```
<?php $description = preg_replace('/(<[^>]+) style=".*?"/i', '$1',$description); ?>
<description><?php print preg_replace("/<style\\b[^>]*>(.*?)<\\/style>/s", "", $description); ?></description>

```

---
Tags: feeds
---


# Question
Title: How to clear varnish cache using drush? I'm on acquia cloud dev account
im working in an acquia cloud environment and currently im clearing the varnish cache via the web interface. is there a drush command to clear varnish cache while using an acquia environment.

# Answer
# With Acquia Cloud API v1 Drush commands

On Acquia Could API v1 the command is `ac-domain-purge`. Here is a snippet from the drush help available from the Acquia box.

```
$ drush help ac-domain-purge

Purge a domain from the Varnish cache.

Arguments:
 domain              Domain name.

Options:
 --username          Acquia Cloud API username
 --password          Acquia Cloud API password
 --acapi-conf-path   Acquia Cloud API config files location. If not specified config will be loaded from $HOME/.drush
 --caller            Acquia Cloud API caller name. Default is the current username.
 --endpoint          Acquia Cloud API endpoint URL.
 --cainfo            Path to a file containing the SSL certificates needed to verify the ac-api-endpoint.
 --format            Format to output the object. Use "print_r" for print_r, "export" for var_export, and "json" for JSON. If not provided, the output is printed in a human-readable format.

```

Additionally, if you want to do this programmatically without drush, Acquia have an API endpoint for clearing the varnish cache.

Note that the drush commands only work with Acquia Cloud API version 1, which is EOL in 2020.

# With Acquia Cloud API v2 requests

Acquia Cloud API v2 is json-api based, and the following API v1 to v2 migration document explains the URL request homologue that replaces each v1 drush command. In this case:

The V1 drush API command `ac-domain-purge` becomes one of either:

* `POST /environments/{environmentId}/domains/actions/clear-varnish`

To clear the Varnish cache for all domains used in an environment (eg both the internal appname.prod.acquia-sites.com domain, as well as your site's public domain.
* `POST /environments/{environmentId}/domains/{domain}/actions/clear-varnish`

To clear the Varnish cache for a single specific domain.

See the Acquia Cloud API v2 documentation reference for additional information.
> 7 votes

# Answer
There is also a module for that called appropriately "Acquia Purge". Works perfectly. Details from project page:

> The Acquia Purge module allows Drupal sites hosted on Acquia Cloud to automatically purge (wipe) pages from their Varnish powered load balancers, as soon as content actually changed. The higher Drupal's "expiration of cached pages"-setting (TTL) is configured the more your site will be served directly off your load balancers. This effectively increases the efficiency of your site and lowers hardware costs, leaving more resources for back-end traffic. In most scenarios the module offers a full turn-key experience without requiring any technical configuration.

I know this doesn't answer the actual question, but its a really easy way to purge varnish cache on acquia cloud using the rules and cache expiration module as dependencies.
> 3 votes

---
Tags: proxies, acquia-cloud
---


title: Disable compass in Zen subtheme

text:
# Question
Title: Disable compass in Zen subtheme
I am using a Zen subtheme with Sass. I am using CodeKit to compile the Sass into CSS. In my workflow, I enjoy using CodeKit's visual system for project settings because then I can use autoprefixer and souremaps etc easily.

Zen comes with Compass support out of the box. In CodeKit, settings for the styles.scss file is disabled, saying "To change options & output paths for Sass files in a Compass project, you must edit the Compass 'config.rb' file directly."

I could find no way to edit the file to make it behave the way I want, so I want to disable Compass completely.

I tried deleting the lines which seemed related with Compass from the sass files, deleting the config.rb but there seems to be a setting somewhere which I cannot find. I checked out the project settigns in CodeKit but could not find a 'switch' to turn Compass off.

In short, how can I take Compass out of Zen's css system and use CodeKit to fine tune the compile settings?

# Answer
So Zen uses zen grids for its grid (in some cases) and that has a requirement for compass/css2/images. if you aren't using zen grids, you can disable that dependency.

Another option could be that you can try to delete/rename the `config.rb` file entirely, as CodeKit may see that and automatically assume you want to use compass to compile your Sass.

A third possibility could be that in the bottom of `_init.scss` `(STARTERKIT/sass/)` it pulls in zen, along with alot of other compass extensions. try disabling zen along with the others you already disabled.
> 0 votes

---
Tags: theming
---


# Question
Title: After updating to 7.27, updates don't work and Status says cannot verify Drupal core
I upgraded my site to 7.27 using drush, and my website says that it is running 7.27 under the "modules" admin page.

However, when I get a status report, it says "No update data available. No update information available. Run cron or check manually."

So I run the cron there, and it will turn green and read "Drupal 7.27" but if I try to run update my modules it just stops the page after saying "checking for updates" and the status report reads the above error again instead of reading "Drupal 7.27".

I've rebuilt the registry, and I am at a loss as what to do now.

Any advice is appreciated. Thanks.

# Answer
> 1 votes
I found the issue. It was a javascript error with the "Colorbox" library. Apparently the colorbox library was two years old and became incompatible due to the switch from .live to .on. All issues were solved when I updated my colorbox library.

---
Tags: drush, updating
---


title: Rearrange/remove content UI

text:
# Question
Title: Rearrange/remove content UI
I've seen this on Blackboard and other sites before. How in drupal could have user interaction(UI) with content on each node?

The user should be able to:

-rearrange content on each node with out being a administrator or logged in. -remove view of content from node and re-populate with more content. The content removed will not be deleted but removed from user view.

I know of panels and I have created panels, but I do not see any UI that allows me to do what I would like to above with panels.

Some help please! Image of what I am talking about. see how user can drag and drop content

# Answer
> 1 votes
Take a look at Homebox module.

> Homebox allows site administrators to create dashboards for their users, using blocks as widgets. Blocks in a Homebox page are resizeable, and reorderable by dragging.

---
Tags: nodes, panels
---