# Question
Title: How we can get custom field type which will bring custom data from custom table to use as a drop down
I need to use my custom table data as a drop down.

**for eg.** i have created one custom table which is getting list of cities and i want that list to be shown in my form as a drop down.

Thanks in advance

# Answer
To Create Custom field type you need to follow following steps

1. Create a custom module (myfield)
2. In myfield.install file add this

```
/**
* Implements hook_field_schema().
*/

function myfield_field_schema($field) {
return array(
'columns' => array(
    'code' => array(
        'type' => 'varchar',
        'length' => 2,
        'not null' => FALSE,
    ),

),
'indexes' => array(
    'code' => array('code'),
),
);
}

```
3. In myfield.module file add the following code

```
/**
  * Implements hook_field_info().
  */
 function myfield_field_info() {
return array(
    'myfield' => array(
        'label' => t('My Field'),
        'description' => t('This field stores a Field data in the database.'),
        'default_widget' => 'myfield_field',
        'default_formatter' => 'myfield_default',
    ),
   );
}

 /**
 * Implements hook_field_widget_info().
  */
    function myfield_field_widget_info() {
return array(
    'myfield_field' => array(
        'label' => t('Select list'),
        'field types' => array('myfield'),
    ),
      );
   }

    /**
    * Implements hook_field_settings_form().
    */
 function myfield_field_settings_form($field, $instance, $has_data) {
$settings = $field['settings'];
// Add your global settings fields here
$form = array();
return $form;
  }

   /**
   * Implements hook_field_instance_settings_form().
    */
 function myfield_field_instance_settings_form($field, $instance) {
$settings = $instance['settings'];
// Add your instance settings fields here.
$form = array();
return $form;
 }

  /**
     * Implements hook_field_widget_form().
   */
   function myfield_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
//Getting the select list.

$options = get_all_nodes();

switch ($instance['widget']['type']) {
    case 'myfield_field' :
        $cc = "IN";

        $element['myfield'] = array(
            '#type' => 'fieldset',
            '#title' => $element['#title'],
            '#tree' => TRUE,
            '#prefix' => '<div id="replace_model_div">',
            '#suffix' => '</div>',
        );
        $element['myfield']['code'] = array(
            '#type' => 'select',
            '#title' => t('Node'),
            '#default_value' => isset($items[$delta]['code']) ? $items[$delta]['code'] : '',
            '#options' => $options,
            '#required' => $element['#required'],

        );

        break;
    }
    return $element;
   }

  /**
   * Implements hook_field_presave().
     */
  function myfield_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
foreach ($items as $delta => $item) {
    if (isset($item['myfield']['code'])) {
        $items[$delta]['code'] = $item['myfield']['code'];

    }
        }
 }

 /**
    * Implements hook_field_is_empty().
  */
  function myfield_field_is_empty($item, $field) {
if (empty($item['myfield']['code'])) {
    return TRUE;
    }
    return FALSE;
    }

    /**
    * Implements hook_field_validate().
     */
   function myfield_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
// Loop through field items in the case of multiple values.
foreach ($items as $delta => $item) {
    if (isset($item['code']) && $item['code'] != '') {
        if (!valid_myfield($item['code'])) {
            $errors[$field['field_name']][$langcode][$delta][] = array(
                'error' => t('Field.'),
            );
        }
       }
     }
     }

   /**
    * Implements hook_field_formatter_info().
     */
   function myfield_field_formatter_info() {
return array(
    'myfield_default' => array(
        'label' => t('Default'),
        'field types' => array('myfield'),
    ),
    );
   }

     /**
         * Implements hook_field_formatter_view().
       */
      function myfield_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
//Getting the select list values
$options = get_all_nodes();
$element = array();
switch ($display['type']) {
    case 'myfield_default' :
        foreach ($items as $delta => $item) {
            if (isset($item['code'])) {
                $element[$delta]['#markup'] = $options[$item['code']];
            }
        }
        break;
       }
       return $element;
      }

  //To list out all functions
   function get_all_nodes() {
     $cflags = db_select('node', 'cf')
        ->fields('cf', array('nid', 'title'))
        ->condition('cf.status', 1, '=')
     ->condition('cf.type', 'books', '=')
        ->execute();

    foreach ($cflags as $row) {
        $options[$row->nid] = $row->title;
      }
          return $options;
  }

```

Hope this will help you
> 0 votes

# Answer
You might want to look at http://materializecss.com/badges.html#dropdown The have a pretty straight forward way of creating a dropdown menu, including code examples.

If it's for a certain Form ID you can use `hook_form_FORM_ID_alter` to specify which ID and alter it's HTML inside `$form_state`. If you don't know it's structure you can `var_dump($form_state);` first instead so you know what to alter.

P.S. also add the CSS of course: `drupal_add_css(drupal_get_path('theme', 'custom') .'https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.1/css/materialize.css', 'theme', 'screen,projection', FALSE);`
> 0 votes

---
Tags: forms
---


title: Video captions below video field

text:
# Question
Title: Video captions below video field
I'm expanding my language learning site and need a bit of help if it's possible. I am wanting to link to YouTube videos (that's easy). But I would like to have a captions field. As the video plays the captions would appear in the field. I need to do this so that the user can copy and paste the caption and there will be two lines of captioning "Language 1" and "Language 2." I might in the future add a second field below the captions that would give a grammar explanation to the caption being displayed as well.

The only thing I have found while searching around is: https://www.drupal.org/node/1927080 but it puts the captions into the video.

```
+---------------------------------+
|                                 |
|              VIDEO              |
|                                 |
+---------------------------------+
+---------------------------------+
|                                 |
|           LANGUAGE 1            |
|                                 | <= Changes based on video time
|           LANGUAGE 2            |
|                                 |
+---------------------------------+
+---------------------------------+
|                                 |
|            GRAMMAR?             | <= Changes based on video time
|                                 |
+---------------------------------+

```

# Answer
I have been unable to find any existing module to do this and would be quite surprised if one existed. You will very likely have to develop your own module.

Here is a brief rundown of how such a module might work:

1. Implement a new field type providing either a form for the user to create the subtitles or upload a subtitle file in one of the many subtitle formats. https://support.google.com/youtube/answer/2734698?hl=en
2. Parse the input from the form and store it. You'd likely want to store it as JSON or something else that will be easy to work with in JavaScript
3. Write code to pass the data to the browser
4. Use Javascript to update the Language 1 and Language 2 content to match the data in your stored subtitle file. You can use the YouTube API to get the current time of the video https://developers.google.com/youtube/iframe\_api\_reference#Playback\_status

I think it would be a lot easier to just use YouTube to do this but I'm sure you've already thought of that.
> 1 votes

---
Tags: files
---


# Question
Title: Best database collation for multilanguage site
I’m running a Multilanguage site (drupal 6) using both: Latin language and a no-Latin language characters.

Before the install. I used phpmyadmin, to change the default MySQL connection collation, from latin1\_swedish\_ci to utf8\_general\_ci. wondering if I'm doing things right? Or should I leave the default MySQL collation in latin1\_swedish\_ci ?

# Answer
> 1 votes
utf8\_general\_ci is preferred over latin1\_swedish\_ci

The good news is that as a result of this issue Drupal now defaults to utf8 so no one should have to worry about this any longer. This fix has been backported to Drupal 6 so this answer should be applicable to Drupal 6, 7, and 8 (when it is released).

---
Tags: 6, database, i18n-l10n
---


# Question
Title: How set background image for doc files when exporting nodes to Word in Drupal 7?
I used the Node to Word module in Drupal 7 to export nodes to Word. It doesn't have an official release for D7 yet, but there seems to be some D7 version of it in GIT. I downloaded this file) for it. This module supports writing template for a very convenient view mode.

How can I set the background image for the doc file when exporting a node to a doc?

I tried to use the background for the `<div>` sheathed same template but the export of the word, it has no effect.

Node template:

And result:

# Answer
> 0 votes
The functionality you are looking for does not (as right now) exist in the version of the module you have linked to.

Therefore you will not be able to set the background image of the Word document without making modifications to the module.

This would be non-trivial as your modified module would have to do the following:

1. parse the CSS of the page to determine what image should be displayed
2. load the image and embed it in a format that Microsoft Word can understand
3. set the necessary tags in the Word document to use the embed image

---
Tags: 7, nodes, theming
---


# Question
Title: Drupal 7 - Create a custom template that can be assigned to different pages
I want to have a custom template for pages. WordPress has template selection feature for Pages or Posts. Is that possible for Drupal?

# Answer
> 3 votes
See here Drupal 7 Theme Hook Suggestions

For nodes You can use

```
    node--[type|nodeid].tpl.php
    base template: node.tpl.php
    Theme hook suggestions are made based on these factors,
listed from the most specific template to the least.
Drupal will use the most specific template it finds:

    node--nodeid.tpl.php
    node--type.tpl.php
    node.tpl.php

```

Also Drupal 6 Template Suggestions

To use same tpl for multiple pages you need to use `theme_preprocess_node` Like

```
function theme_preprocess_node(&$vars, $hook) {
  $node = $vars['node'];
  if(in_array($node->nid), $myuids)
   $vars['template_file'] = 'your_template_file';
}

```

# Answer
> 1 votes
Take a look at Panelizer. It allows you to use Panels for content types, and you can define different layouts, content, contexts, etc. on a per node basis.

In my opinion, this approach is much easier to maintain than having a bunch of separate template files in your theme.

# Answer
> 1 votes
1. Create a MYMODULE module;

Put the following code:

```
function MYMODULE_theme($existing, $type, $theme, $path) {
  $theme = array();
  $theme['TEST_NAME'] = array(
    'template' => 'TEMPLATE-NAME',
    'path' => drupal_get_path('module', 'MYMODULE'),
  );
  return $theme;
}

```
2. Create a file TEMPLATE-NAME.tpl.php in the module folder;
3. Output it in places you wish with the code:

```
theme('TEST_NAME', $vars);

```

# Answer
> 0 votes
Take also a look at the Theme Guide and the Core templates.

---
Tags: 7, theming
---


# Question
Title: How to open a node form in popup after click on edit from front end?
I added a edit link using `hook_form_alter` in my node form..When I clicked on this link it goes edit content page. But I need to open this form on popup and change the form value from here.

**My question**: How to open a node form in popup after click on edit from front end?

# Answer
> 1 votes
If you want to go through custom module you need to follow instructions given here. If you are looking for contrib module colorbox or modal forms to edit your content on modal popup(using Ctool).

# Answer
> 0 votes
Try

1. **Popup** Module.

> The popup suite allows builders to popup tooltip-like text, nodes, blocks, menus, forms, views and php-generated content.

2. **Popup forms** Module.

> This module provides an easy way for developers to display any Drupal form in a popup (through jQuery UI dialog). Note: this module does nothing itself and only provides API for module or theme developers. There are plenty of modules that display something in popups, the most popular of them is Popup (for Drupal 7). The main difference from this kind of modules is that Popup forms does one thing (and does it well): it opens form in a popup.

May be this will help you..

# Answer
> 0 votes
Creating CTools popups (modal windows) is not a complicated thing, but it has many important nuances. Therefore, this article is devoted to the various nuances of popup creation.

**The simplest CTools popup**

To create the simplest Ctools popup, you just need to write one line of JS code **Drupal.CTools.Modal.show();**. This JS function will create a full-fledged Ctools popup, you will just have to add content. As an example, let us create a popup that will appear when the page loads.

```
;(function($) {
Drupal.behaviors.firstPopup = {
attach: function (context, settings) {
var content = 'my content';
     var title = 'my title';
     Drupal.CTools.Modal.show();
     $('#modal-title').html(title); // Adding title to popup;
     $('#modal-content').html(content); // Adding content to popup;
   }

}
})(jQuery);

```

Add this JS to the desired page — and your first, simplest popup is ready. However, it has one drawback — like any other JS, it can output only data generated on the client’s side. Of course, in many cases, this may be enough, but more often Ctools popups are used to output dynamic data from the server. So let us consider more complex, but more common cases of popup creation and usage.

For more details about POPUP

---
Tags: 7, nodes
---


# Question
Title: Why doesn't the function taxonomy_term_search exists?
I have an autocomplete field in an API Form. The callback function uses the following code to highlight the search query in the list of suggestions. With a taxonomy vocabulary of 3 levels of hierarchy, about 8,000 terms, it takes a whole eternity of 1 second to offer the suggestions. In a direct SQL query or a EntityFieldQuery it takes just a few tenths of a second. Why doesn't **mixed $tid\_array =** `taxonomy_tearm_search(term_name, vid)` exists, it would increase the code below in which only taxonomy API is used.

```
mymodule_providers_autocomplete($brand, $text){
   $selected_providers = array();
   $providers = get_providers_of_type($brand);
   $counter = 0;
   foreach($providers as $nid => $provider){
      if(strpos(strtoupper("." . $provider["title"]), strtoupper($text)) > 0){
           $selected_providers[$provider["title"] . ' (' . $nid . ')'] = str_ireplace($text, "<strong>" . $text . "</strong>" , $provider["title"]);
           $counter++;
           if($counter > 10) break;
       } // if
   }
 drupal_json_output($selected_providers);
} // function

function get_providers_of_type($brand){
   $children_1 = taxonomy_get_children($brand);
   $models_arr = array();
    foreach($children_1 as $key2 => $value2){
        $children_2 = taxonomy_get_children($value2->tid);
        foreach($children_2 as $key => $value){
            $models_arr[] = array("title" => $value->name);
        } // foreach
    } // foreach
}   // if
  return $models_arr;
} // function

```

# Answer
Long story short, it does not exist because either no one wrote it, or maintainers found it not suited for inclusion in taxonomy.module for whatever reasons. For most purposes, `taxonomy_get_term_by_name` is enough. When it's not, there are various search solutions in separate, search oriented modules.

If you think you can write it, and make it good, please do so, and then post entry in issue queue with appropriate patch file.
> 1 votes

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


# Question
Title: How to display a twig template via a controller's render array
I'm trying to do something you'd think was simple, but I don't find good documentation for it.

I'm trying to create a controller that displays a twig template.

I've done the following so far:

1) In my module directory, I've created a templates/ directory. It contains a `field-permission-description.html.twig` file, containing mostly HTML text. So far, I don't even have any `{{ twig_variables }}` in it:

```
<div class='examples-description>

  <p>Field permision text will be here.</p>

</div>

```

2) I have a theme function in my MY\_MODULE.module file:

```
/**
 * Implementation of hook_theme
 *
 * Since we have a lot to explain, we're going to use Twig to do it.
 */
function MY_MODULE_theme($existing, $type, $theme, $path) {
    return [
      'field_permission_description' => [
        'variables' => [
          'stuff' => NULL
        ]
      ]
    ];
}

```

3) In my controller, the function returning the render array looks like this:

```
  /**
   * A simple controller method to explain what this example is about.
   */
  public function description() {
    $build = [
      'description' => [
        '#theme' => 'field_permission_description',
        '#stuff' => 'some stuff',
      ]
    ];
    return $build;
  }

```

I clear the cache with drush, and go to the page. There's no error, even in the watchdog, but the content region of the description page is blank; the template does not render.

It's not a problem with the controller, since if I substitute something else (say, just a little HTML in a `#markup` key), it renders fine.

There's been a couple of answers a year or two ago, but these all have things that no longer work as of RC1.

What do I need to do to get a twig template to render the way I'm trying to do here?

# Answer
> 2 votes
The problem turns out to be a missing `'` mark in the twig file itself.

It turns out that the twig was rendering, but since I had

```
<div class='examples-description>

```

and not

```
<div class='examples-description'>

```

the browser refused to show the badly written HTML.

So this was user error, but a hard user error to debug. I saw what was going on by looking at the source for the page, which made it obvious.

Hopefully this will save folks some trouble. But in any event: the technique I use here is valid, and works if you don't do stupid things in your twig :-)

---
Tags: 8, theming
---


# Question
Title: How to make galleries relative to particular nodes?
I have a site with news and I want to make it possible for *admin* to add image gallery to *Articles* (nodes) the admin wants. So, the idea is to make *gallery image field* for every content type from which images should be taken. If admin wants gallery for that *article* the admin can upload images, if the admin don't the admin can just leave it alone, and Drupal renders that node without gallery perfectly normal.

So, I made that *gallery image field* for every content type, and used Views module for taking and rendering pictures. But, whereas views taking pictures at content type level not node level, that is the reason why unpleasant consequence appear: gallery from particular node, shows on every node of that type.

My question is how to make galleries relative to particular nodes (specific gallery for specific node)? And it should be extremely easy for admin to manipulate.

# Answer
**The simplest way: Use colorbox module**

In the structure of the content type add an image type (with multiple values allowed) and put its display type to be a colorbox gallery

**The complex way: use view slideshow and computed field**

Still add an image field to the content type, but set its rendering to hidden.

Add a computed field with the value equal to the node nid and the display a view that take the node nid as contextual filter and render the image field using the slideshow plugin.

Set the display of this computed field as unsanitized.

Computed code:

```
if (!$entity->nid) node_save($entity);

```

Display Code (PHP):

```
$display_output = views_embed_view('<your view name>','<your view display name>',$entity_field_item['value']);

```

You can get an example here: http://agriregionieuropa.univpm.it/content/event/test-antonello (tab "video ed immagini").

The video slideshow uses the second approach (in this case videos, in your case photoes, it's the same), while the photo gallery uses the colorbox approach.
> 0 votes

# Answer
> how to make galleries relative to particular nodes (specific gallery for specific node).

You have probably forgot the contextual filter "content nid" in your views:

In the option "When the filter value is not available":

1. add "content nid" in your view
2. check the line "Provide default value"
3. Select "Content ID from URL" from the dropdown
> 0 votes

# Answer
You could use that gallery field formatter which gives you the ability to make the image field which have multiple values to be displayed as a gallery  You could control the field display settings from its display settings per content type
> 0 votes

---
Tags: 7, nodes, media
---


title: Database get uid for menu creator

text:
# Question
Title: Database get uid for menu creator
I just want to get the user information who create a new menu item under menu section. I am not able to get any entry in database regarding the menu creator (UID). There is a entry in {menu\_links} table, but in this table or any other table there is no UID linked.

# Answer
> 1 votes
Create a custom module and use the hook `hook_menu_link_insert`. Get the active user with `global $user;` and save the user + link id in a separate table.

---
Tags: users, database
---


# Question
Title: How to change placeholder title of search box?
I have placed 2 search box in 'node/92' page at two different region one is at header region and another is at content region ,I have to change the placeholder text of both search box as abc and xyz respectively my code is:

```
function bartik_form_search_block_form_alter(&$form, &$form_state, $form_id) {      //print arg(1);
      if (arg(1) == 92)
    {

    $form['search_block_form']['#attributes']['placeholder'] = t('abc ');
}

}

```

but this code not working well after using it both the search box placeholder text having the same title "abc"

# Answer
By using hook\_form\_alter and/or any of its descendants, you are altering the placeholder everywhere and anywhere that the form occurs.

To isolate specific instances of the form, based on which region they are in, you can use hook\_preprocess\_page.

For example, in your template.php:

```
function yourthemename_preprocess_page(&$variables) {
  if (arg(1) == '92') {
     // Set the default value for the form in the header region.
    $variables['page']['header']['search_form']['search_block_form']['#attributes']['placeholder'] = t('abc');

     // Set the default value for the form in the content region.
    $variables['page']['content']['search_form']['search_block_form']['#attributes']['placeholder'] = t('def');
  }
}

```
> 0 votes

# Answer
jQuery may be a solution.

```
jQuery(document).ready(function(){
 jQuery('#id').attr("placeholder", "placeholder to show");
});

```
> 0 votes

---
Tags: hooks, search
---


# Question
Title: Install profile installation fails with "Base table or [error] view not found: 1146 Table 'xxx.system' doesn't exist'" on aegir
I tried to install a custom installation profile on aegir today, the installation failed with this message:

```
Exception 'PDOException' with message 'SQLSTATE[42S02]: Base table or
view not found: 1146 Table 'xxx.system' doesn't exist'

```

A local installation in a vagrant via drush worked without Problems.

# Answer
The reason for this obscure error message was that I had defined a dependency in the installation profile, but the module was missing. After removing the not-existing module from the profile.info-file the installation went smooth.
> 0 votes

---
Tags: 7, aegir, installation-profiles
---


title: jQuery multi and jQuery mobile 1.4.5

text:
# Question
Title: jQuery multi and jQuery mobile 1.4.5
I'm using drupal 7 and trying to develop some mobile menu effect. I've read a lot of discussion so i've install jQuery multi so my drupal run in back-end jQuery 1.5 and in front-end run jQuery 1.11.3. I've also insert jQuery mobile 1.4.5 to manage mobile touch events but for what i understand this will not execute thi is my code

`jQuery("#page").on("swipe",function(){
 if($(window).width()<=900){
 $("#nice-menu-1").children("li").children("ul").css({display: 'block', visibility: 'visible'});
 }
 })(jq1113)`
It's not a js code problem but a library loading for what i know
i've got some error like this:
`Uncaught TypeError: a.mobile.document.on is not a function
Uncaught TypeError: jQuery(...).on is not a function`
Could someone helo me? thank you

# Answer
I see there are some errors in your code, such as a missing open curly bracket for your if statement and few others.

Try this:

```
(function ($) {

 jQuery.noConflict();
     $(document).ready(function( $ ) {
         $("#page").on("swipe",function(){
         if($(window).width()<=900) {
         $("#nice-menu-1").children("li").children("ul").css({"display": "block", "visibility": "visible"});
         }
         });
     });

})(jQuery);

```
> 0 votes

# Answer
I've finally solve by using jQuery Mobile Builder selecting only mobile events so it reduce collision
> 0 votes

---
Tags: javascript
---


# Question
Title: Drupal's "Add to Cart" field shows product variations instead of individual options
This is probably a very novice question, but I'm working on a website that uses Drupal Commerce. There is a field defined for the product display called: `Product variations` which is of the format `Add to Cart form`.

On most products, this field correctly shows a combination of size and color dropdowns, whereas for some products, it just puts all products variations in a drop down and shows that instead of the color/size combination.

Any idea what might be going wrong or how to debug this issue?

**Wrong**:

**Correct**:

# Answer
It looks like the products you've referenced from the "wrong" image do not all share the same attribute fields in common. One frequent mistake in this regard is forgetting to toggle the checkbox on the field edit form to instruct Drupal Commerce to treat a product field as an attribute field on Add to Cart forms.
> 0 votes

---
Tags: entities, commerce
---


# Question
Title: How to show the values on the bars of a stacked bar graph in 3D?
I have created a Stacked Bar Graph (in 3D) using the Forena reports module, which looks like so:

I was able to successfully create this graph. But I am having problems in showing the corresponding values on the bars. The values I want to show on the graph are:

* colombia\_blue:0.75
* colombia\_red:0.25
* LATAM\_blue:0.57
* LATAM\_red:0.43

I searched for the frx attributes. I found attributes to change the color of these 2 graphs, but not the label.

Here is the relevant part of my report specification (frx file):

# Answer
> 1 votes
# Option 1 - Try another chart type

I recommend you experiment a bit with some of Forena's other Supported chart types, as documented within the "*FrxSvgGraph*" section of the "*Custom Renderers*"chapter (located with `/reports/help.renderers#frxsvggraph` of your site, and similar to this online equivalent).

More specifically, you seem to be using `frx:type="StackedBar3DGraph"`. I think you will get way better results (to show the corresponding values) if you try with some of the other chart types, especially these ones:

* MultiLineGraph
* GroupedBarGraph
* GroupedCylinderGraph

# Option 2 - Add specific SVG Graph settings

If using another chart type is not what you want (= it has to be a Stacked Bar Graph in 3D), then you need to find the appropriate SVG Graph setting(s) (there are dozens, if not hundreds, of them ...) and pass such setting(s) as extra FRX attributes.

In that case, you may want to use some of the SVG Graph general settings. I haven't experimented with them, but I think you may want to try with these settings:

* `show_data_labels`, which is a boolean (default = false), to "display labels for bars, markers or pie slices". In Forena, if you want to set this option to true, you'd specify it in your frx file like `frx:show_data_labels="yes"`.
* any of the settings starting with `data_labels_...` (there are dozens of them ...), to tune the data labels, like their fonts, positioning, etc.

**Note**: SVGGraph data labels explains some of the options related to labels, and how to use them.

---
Tags: 7, charts, forena
---


# Question
Title: How to create a payment form / pane directly from order_id
Study case : customers already have **the ability to pay only a deposit**. So they 'll have to come back and **pay the order balance later**.

How can I **create a payment form** ?

* where they will be able to directly submit a payment form and proceed to off-site payment to pay order balance
* without coming from cart/checkout process, (as it has already be done in deposit payment another day)

This will be linked from the user/%/orders/% page.

Is there any **commerce API function** that could fit that issue ? I had a look at `commerce_payment_order_transaction_add_form($form, &$form_state, $order` but I could not find any doc to implement it, .

Thank you

PS : related issue: Commerce partial payment

# Answer
I got it doing the following :

with a link in `user/%/orders/%` page like `go_to_checkout/$order_id`

```
/**
 * Implements hook_menu();
 * Callback to pass order_id to checkout fn
 */
function commerce_partial_payment_menu() {

  $items['go_to_checkout'] = array(
    'title' => 'balance',
    'description' => 'Pay order balance',
    'page callback' => 'commerce_partial_payment_redirect_to_checkout',
    'page arguments' => array(1),
    'access arguments' =>  TRUE,//still have to change that, maybe see own orders permission
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/*
 * Prepare checkout process and redirects to checkout/%/review
 */
function commerce_partial_payment_redirect_to_checkout($order_id) {

  $order = commerce_order_load($order_id);
  commerce_order_status_update($order, 'checkout_review', $skip_save = FALSE, $revision = TRUE, $log = '');

  drupal_goto('checkout/' . $order->order_id. '/review');
}

```
> 0 votes

---
Tags: commerce
---


# Question
Title: Architectural - How to setup content types for very unique editable pages
We are working on a site for a client. This page has in total about 30 different pages. Each page has a unique and complicated design. In order to give the client the possibility to edit texts on the pages without changing the design we created text fields for each content type. Each content type has around 30 fields (text or long text) which we manually render in the template files. Each field has a unique machine name. We always created a new field whenever we needed a new field in one of the content types. And each content type has only a few contents (variation of the page).

**Current structure:**

```
Content type 01
    Field 01
    Field 02
    ...
Content type 02
    Field 05
    Field 06
    ...

```

The question now is if there is a better way of building such a architecture, since we are having a quite large php memory usage. The idea of drupal is to create a content type and have then a lot of contents of that type. But that approach doesn't fit to our customized page design.

One possible solution which we gathered is to reuse the fields in all the content types. Originally we named the fields in the example above *field\_content\_type\_01\_field\_01* and *field\_content\_type\_02\_field\_05*. This solution would mean we have to change the fields to have *field\_field\_01* and reuse that field in all content types.

But is there a better way for our setup?

# Answer
# Option 1: Panels

Maybe you should check to what extend your *unique and complicated design of each page*" could be implemented using the Panels module. Some details from its project page:

> The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.

Learn Page manager! is an interesting (and amazing) set of videos. They contain various topics related to the Panels module. Here is a summary of the entire set of videos about this topic (quote from the link above):

> * Page manager allows you to collect and manage contextual information in a flexible and consistent way. It is an important part of building infrastructure on Drupal websites, and you should know how to use this module.
> * The screencast series is targeted at experienced Drupal developers.
> * Episodes 1, 2 and 3 introduces the most basic concepts, such as custom pages, variants, selection rules and (to some extent) contextual objects.
> * Episodes 4, 5, 6 and 7 talk about Panels, with emphasis on Views integration but also some words on efficient caching.
> * Episodes 8 and 9 about access control, menu items, and not least the little-known but very useful Contextual Administration module.
> * Episodes 10 and 11 talks more about using contextual objects in Page manager, including using Views as context. This is, imho, where the real power in Page manager is.
> * Episodes 12 and 13 collects various bits and pieces, such as how to use Panels to easily rearrange the node edit form, import/export settings, and some extra modules that can be used with Page manager.

Refer to Explaining Panels: An Overview for Drupal Developers for another great explanation about the Panels module.

# Option 2: Display Suite

Another approach is to use the Display Suite module. Some details from its project page:

> Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (D7 only) is available for even more drag and drop fun!
>
> By defining custom view modes (build modes in D6), you can define how one piece of content should be displayed in different places such as teaser lists, search results, the full node, views etc.

Screencasts & articles about Display Suite has numerous screencasts with more details about it.
> 1 votes

---
Tags: entities, nodes
---


# Question
Title: How To customize user account creation form
I successfully customized the user login and password reset form using this:

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

  $items['user_login'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'responsive_bartik') . '/templates',
    'template' => 'user-login',
    'preprocess functions' => array(
       'responsive_bartik_preprocess_user_login'
    ),
  );
  $items['user_pass'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'responsive_bartik') . '/templates',
    'template' => 'user-pass',
    'preprocess functions' => array(
      'responsive_bartik_preprocess_user_pass'
    ),
  );
    return $items;
}

```

then I created two files, user-login.tpl.php and user-pass.tpl.php Which each have code like this:

```
<p><?php print render($intro_text); ?></p>
<div class="responsive_bartik-user-login-form-wrapper">
  <?php print drupal_render_children($form) ?>
  <p><a href="password">Forgot Password</a></p>
  <p>Don't have an account? <a href="examplesite.com">Sign Up</a></p>

</div>

```

I tried to the the same thing with the registration form but it still looks the same. It has not overriding it. Here is the code i am used for that:

```
  $items['user_register'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'responsive_bartik') . '/templates',
    'template' => 'user-register',
    'preprocess functions' => array(
       'responsive_bartik_preprocess_user_register'
    ),
  );

```

I stuck this right before the `return $items;
}` section.

Then i created a file: user-register.tpl.php and placed this code into it:

```
<h1>Hello TEST!</h1>
<p><?php print render($intro_text); ?></p>
<div class="responsive_bartik-user-pass-form-wrapper">
  <?php print drupal_render_children($form) ?>
  <p>Already have an account?<a href="login">Log in</a></p>
  <p>Don't have an account? <a href="http://examplesite.com">Sign Up</a></p>
</div>

```

Form output didn't change. I am using Profile2 Module and Logintoboggan Module

# Answer
> 1 votes
You need to use user\_register\_form instead of user\_register.

Try using it like this :

```
$items['user_register_form'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'responsive_bartik'). '/templates',
    'template' => 'templates/user-register-form',
    'preprocess functions' => array('responsive_bartik_preprocess_user_register'),
);

```

Now create a user-register-form.tpl.php in your themes template folder.

# Answer
> 0 votes
You can use MY\_MODULE\_form\_alter(&$form, $form\_state, $form\_id) to edit it.

Try adding this to your custom module:

```
function custom_form_alter(&$form, $form_state, $form_id) {
  switch ($form_id) {
    case 'user_register_form':
    //put your code here
    break;
  }
}

```

---
Tags: theming, users
---


title: prevent webform from storing user input

text:
# Question
Title: prevent webform from storing user input
Must I use webform in order to create a custom form? I need to create a form validator that will validate if a number (social security number) is valid. I've used webform for this but whatever I enter in the form, it's always storing it and I have to clear the data by going to admin. I dont want the webform to store user input. The point of the form is just to validate. Basically client side validation (or PHP side) is the only purpose of the form. No storage needed. Is there a way to turn off the storage in webform? Or do I have no choice but to store all inputs entered by users?

I've seen this but I dont want to redirect. My form is just an ajax call..

# Answer
> 0 votes
You can edit the form with function\_form\_alter(), and modify what to do on submit. Try this:

```
function MY-MODULE_form_alter(&$form, &$form_state, $form_id){
  if( $form_id == 'YOUR-FORM-NAME' ){
    $form['actions'][]= array(
      '#submit' => array('_CUSTOM_FUNCTION')
    );
  }
}
function _CUSTOM_FUNCTION(){
  //put what to do here
}

```

---
Tags: ajax, webforms
---


title: view node reference

text:
# Question
Title: view node reference
I have a content types **Person** and **Projects** In Project I have Node reference fields of Person. when i am adding a new project and select person who worked on that project using node reference field.

I like to create a view that contains the person who worked on a project. I want to display that view as a block beneath that project. For view the people who worked on that project.

I tried a lot of things (10 hours) to create the view. But not get proper result. Now i have a view that shows all persons, also the persons that didn't work on that project. When i add a contextual filter or/and a relationship the view is empty.

# Answer
> 0 votes
If you need to create a view for this,

1. Create a new View Block of **project** content type.
2. Add your node reference field under fields and select rendered entity or label as you would want it to display.
3. Add a contextual filter **Content:Nid** and provide default value - Raw value from url. Select your proper path component and check path alias (if you are using path alias).
4. Go to structure -\> blocks and move your block to your region and set the Content type - **projects** under visibility settings.

---
Tags: views, nodes
---


title: Which tables are safe to clear?

text:
# Question
Title: Which tables are safe to clear?
I have inherited a client site that has an extremely large database for no reason. There is a moderate amount of content and very little enabled modules. However, the database is too large for moving around easily and I want to clean it out.

I have cleared out the standard cache tables, syslog and accesslog.

Are there any other tables I can safely truncate in a standard Drupal site?

# Answer
Use the backup & migrate module, it comes with good defaults for skipping not necessary data. By default it generates a DB backup without cache, watchdog and some other tables.

If this does not help have a look with phpMyAdmin and tell us which tables have a lot of entries.
> 20 votes

# Answer
# Drupal 7 tables that can be excluded

Here is a list of tables in Drupal 7 that you can either clear (to reduce the database size) or safely exclude to do a migration (as in the question about How to reduce the locally exported database size to get around my server import limit?):

* accesslog
* batch
* all cache related tables, such as:
    + cache\*
    + cache\_block
    + cache\_content
    + cache\_filter\*
    + cache\_form
    + cache\_calendar\_ical
    + cache\_menu\*
    + cache\_page\*
    + cache\_views
    + \*_cache, such as features\_cache or views\_data\_object\_export\_cache
* ctools\_views\_cache
* ctools\_object\_cache
* devel\_queries
* devel\_times
* flood
* history
* queue
* various search\_\* tables, such as:
    + search\_dataset
    + search\_index
    + search\_keywords\_log
    + search\_total
* semaphore
* sessions
* watchdog
* webform\_submitted\_data

Usually tables such as `search_index` and `watchdog` use a lot of database space, so just eliminating those 2 tables can make a huge difference already.

# Other tables that might be excluded

Check the size of your remaining tables and identify which one of them are the biggest in size.

Typically you might find session tables for which no cleanup procedure is in place. Such tables you can probably also exclude.

# Module Backup and Migrate

To further reduce the challenge as detailed in "How to reduce the locally exported database size to get around my server import limit?", look at the Backup and Migrate module also. Here is a quote from its project page (bold markup added here):

> Back up and restore your Drupal MySQL database, code, and files or migrate a site between environments. Backup and Migrate supports gzip, bzip and zip compression as well as automatic scheduled backups.
>
> With Backup and Migrate you can dump some or all of your database tables to a file download or save to a file on the server or offsite, and to restore from an uploaded or previously saved database dump. **You can choose which tables and what data to backup and cache data is excluded by default**.

And there is even more: if your local environment (e.g. Win or Mac) differs from the OS that the server of your hosted website is running (like Linux), then these differences between OS-es imply potential extra challenges. I've had good experiences with the Backup and Migrate module between different OSes, which didn't cause any problems (worked fine) in situations where the typical MySql export / import failed before.
> 30 votes

# Answer
In my experience, I purge all of the "cache\_\*" tables.

* plus "watchdog" if I don't care about past Drupal logs
* plus "accesslog" if I don't care about logged-in users
* plus "search" if I don't care about indexed nodes contents
> 19 votes

# Answer
I sometimes run this SQL to keep an eye on the growth of the top tables:

```
SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA =  'yourdbnamehere'
ORDER BY table_rows DESC

```
> 9 votes

# Answer
Watchdog and sessions can also be cleared, keep in mind that all users will be logged out.
> 7 votes

# Answer
With mySQL you can do fun things with the mysqldump program to export the database in its entirety or in parts. For instance this just exports the structure:

```
mysqldump -u root -pBatteryHorseStapleObviously -h some_host --no-data dbname > ~/dbname.sql

```

You can then use the 'ignore table' option to further export data, e.g.

```
mysqldump -u root -pBatteryHorseStapleObviously -h some_host --ignore-table=dbname.huge_table --ignore-table=dbname.massive_table --ignore-table=dbname.useless_table some_host >> ~/dbname.sql

```

That places the data on the end of the earlier file ignoring some massive tables.

If you then need the massive tables then you can export them to a different file using the above approach, you can then import them in chunks (although f k checks off might be needed).

You did gzip your file before uploading, or is that a silly question?
> 5 votes

# Answer
Use OptimizeDB module to clean the cache tables. The Database Administration is also helpful.

Don't forget to have a backup of databases.
> 4 votes

# Answer
not the super expert on this but sharing my experience... if you're not using the backup and migrate module and manually export them some of the tables you could empty/truncate would be `watchdog`, `cache`, `cache_menu`, `cache_block`, `cache_content`, `cache_form` as they might contain a large amount of cached stuff clearing which I suppose wouldn't hurt... but again this is my experience and I haven't encountered troubles or data loss because of this.
> 2 votes

# Answer
Some ideas:

* A completely different approach would be to create RSS feeds using views of the data you want to keep. Then create a fresh Drupal installation and import this data with Feed API.
* And just an other approach: Hire a student and let him/her transfer the data manually into your fresh installation.
* Or this one: Tell us more about what tables are very huge and what is the reason for this (if you know).
> 2 votes

# Answer
Additional tables that can be cleared:

* batch
* webform\_submitted\_data

Other things that might take up quite some space: \- older versions of your content (not possible to clean with a simple truncate). \- locales\_source and locales\_target. If you have languages that are not used anymore or string translations for modules that you don't use anymore. These tables seem to never get cleaned.
> 2 votes

# Answer
Check the `example.drushrc.php` which list these:

```
$options['structure-tables']['common'] = array('cache', 'cache_*', 'history', 'search_*', 'sessions', 'watchdog');
$options['skip-tables']['common'] = array('migration_*');

```

It's safe to clear them in terms of moving the database between different environments (especially when you're working with big databases). However you still need to understand what you're clearing.
> 1 votes

---
Tags: database
---


# Question
Title: what action can trigger clearing of caches?
I have a site that is cached for anonymous users. However it seems that something clears caches every now and then (many times daily.) And it is not result of admins activity. I found about it only by chance, when looking at page\_cache table, refreshed it after a while and all records were gone. Question: how to start debugging this? What can I do to track what user action or anything causes caches to be cleared? Thank you.

# Answer
Have you checked whether Cron is configured on your site under Configuration options.

When trying to speed up my site, this article was very useful as Cron will clear cache.

http://www.metaltoad.com/blog/how-drupals-cron-killing-you-your-sleep-simple-cache-warmer
> 0 votes

# Answer
If your cache is cleared on every page, this can be triggered by:

> Rebuild the theme registry on every page load

provided by Devel. Try to disable it in Appearance.

Check also your cron tasks.

---

Since there is no hook on cache clearing (at least not in Drupal 6-7), so debugging this is a bit tricky.

If you really wants to do this (at least not on the Production), enable Devel module, then add:

```
dd(debug_backtrace());

```

into `hook_flush_caches()` (or `drupal_flush_all_caches()` \- not advised).

Note: `dd` works for Drupal 5-8

To save some space, you can use `debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 3)` instead to limit the number of stack frames returned (PHP \>= 5.4.0).

This will log all functions/modules which performed clear caching in `/tmp/drupal-debug.txt`.

To check in real-time once you're using your site, try:

```
tail -f /tmp/drupal-debug.txt

```
> 0 votes

---
Tags: 6, caching
---


# Question
Title: How to create a custom home page template?
I've built a few drupal sites, and always end up creating a content type for Home Page so that I can have a custom template for my home page content, however it seems excessive to have a whole content type just for this. Is there a better way to have a custom home page template?

Wordpress has the front-page template, is there something like that for Drupal?

# Answer
> 3 votes
Yes : https://www.drupal.org/node/317461

> In Drupal 7, copy the page.tpl.php file and name it page--front.tpl.php.

Copy the file in your sites/all/themes/yourtheme/templates file (and then clear the caches of your site)

---
Tags: 7
---


# Question
Title: How to show data from external api to theme template?
I am totally new to Drupal. I have given one assignment to build Drupal site which shows courses from our company site. I am totally stuck in one point. I need to show data from our api into theme template.

Can you please guide me on this? If you have any example, please share with me. I will dig into it and I will try to solve my problem.

# Answer
> 0 votes
There are a few answers to that question, and it depends on the design (appearence and behaviors), but the Drupal foundation is usually the same.

**1st step**

Create a custom block and place it in a page (node of a generic type is a good option or a programmatically created page. **OR** Create a custom page (see ´hook\_menu´)

**2nd step**

Create a custom theme function using ´hook\_theme´ (template file is usually easier to maintain)

**3rd step (connect to the API)**

Due to performance considerations (async vs. sync request) I prefer to use JavaScript to get the data and present it on the page / block we created. (AngularJS is my friend..) If JS is not an option, then you can make the request in ´hook\_block\_view´ in case you used custom block, ´hook\_page\_build´ or in your ´hook\_menu´'s callback in case you chose a page in step 1.

---
Tags: 8
---


# Question
Title: Best way to migrate inline images in content fields to drupal 7
I am trying to create say "Articles" manually using scripts. Basically I am reading data from mysql table and creating nodes programmatically by looping the tables.

However in mysql content field which is the Body field of my Article content type has the data with inline embedded images and links.

```
<p><img src="/assets/default/85/858dee4200c7f440cd6d4dba8814d56a8e81ab1f/original.jpg"></p><h1> Some more dummy text.</h1>

```

What would be the best way to migrate images for such cases?

# Answer
> 1 votes
First off, there really can't be a ***best way*** without describing any requirements that can be objectively measured (e.g. speed, loc, number of steps, etc.). However, you can do a few things to do use those inline files in Drupal.

First thing is to sync (e.g. `rsync`) your content file dir under Drupal's publically managed file system. Depending on your organizational preference, this can be:

* The default path (**sites/default/files** from your Drupal root).
* A subdir in the default path (e.g. **sites/default/files/assets**)
* Or a completely arbitrary dir; you can use any directory in Drupal root to be the public file system by configuring it in the **admin/config/media/file-system** admin page. In fact, you could make it the same directory as your previous CMS (**assets/default**).

If you decide to use a new directory (i.e. not **assets/default**) you'll need to either:

* Create web server redirect rules (e.g. Apache .htaccess `RewriteRule`) from the old URLs to the new URLs.
* Find old URL references in your imported content and replace them with the new URL references.

The first option is the better of the 2 since it accommodates other caches of your documents (e.g. cached web crawler versions of your content) that you can't update and it's less error prone (e.g. no breaking content because regex mismatches).

The last thing to mention is programmatically inserting records into Drupal's managed files system (its `file_managed` DB table). This isn't required for your imported articles to display, but if you ever want to manage the imported files through various Drupal file-management tools, it will be needed.

Since you're already using a PHP script to programmatically, you can add to the script a function to iterate over all sync'd files in the public directory and save them to Drupal.

```
//Assume $files is an array of file paths relative to the new public directory
//(e.g. 85/858dee4200c7f440cd6d4dba8814d56a8e81ab1f/original.jpg)
foreach ($files as $filepath) {
  $uri = "public://$filepath";
  $file = file_save((object) array(
    'filename' => basename($uri),
    'uri' => $uri,
    'status' => FILE_STATUS_PERMANENT,
    'filemime' => file_get_mimetype($uri))
  );
}

```

---
Tags: 7, media, migrations, navigation
---


# Question
Title: How to access current menu level/depth when overriding THEMENAME_menu_tree__MENU($variables)?
I'm creating a custom menu for a project built in Drupal 7 and I want to add some custom HTML before every UL in the main menu.

By adding the THEMENAME\_menu\_tree\__main\_menu($variables) function to my template.php I can output my custom HTML:

`return '<div>My custom HTML</div><ul class="main-menu">' . $variables['tree'] . '</ul>';`

The function is called for every level in the menu and the HTML printed in front of every UL. But now I also want to customize this HTML in different ways for each level, but I cannot find any information regarding the current menu level in the $variables parameter.

Is it at all possible to access information about current menu level in the body of the function? If so, how?

# Answer
Looks like this question is way past its expiry date, but who knows this might help someone :)

I must confess, I have never used this hook function before (`THEMENAME_menu_tree__main_menu`). I had a quick look by implementing it in my current project, and you are only getting back HTML. I think you are going to have a tough time styling individual items in the HTML you are getting back.

In my current project I render my menu a region template file (`region--header.tpl.php` to be exact). Obviously this means I have a 'header' region defined in my `mytheme.info` file.

So in `page.tpl.php` I have

```
<?php
  if (isset($page['header'])) {
    print render($page['header']);
  }
?>

```

which basically defers rendering to `region--header.tpl.php` In this file I:

```
$menu = menu_tree_all_data('main-menu');
foreach ($menu as $menuItem) {
  // Extract info I want and render
  // $markup = ......
}

$print $markup

```

Basically I build my own HTML that will render the menu.

I have a couple of 'utility functions' to get the data out of $menuItem - let me know if you are interested.

As a side note - if you just want to figure out what level you are on - you could always call menu\_get\_active\_trail(). You should be able to figure out what 'level' you are on with the info in that array.

Hope this helps.
> 1 votes

---
Tags: routes, theming
---


# Question
Title: How to add mulitple legends in chart created with the Forena reports module?
I have created a report using the module Forena reports. It's a compound graph of 3 items.

I need to mention these 3 items in legend. But I am not able to add more than 1 legend. I am trying to create this graph from the front end itself. I don't want to use the frx file.

# Answer
> 1 votes
This is how I got it working. I fetched the values I want to show as the legends in the sql query I used itself. Then I assigned this value as the legend. Please find the screenshot.

# Answer
> 1 votes
Any attribute supported as PHP SVGGraph options may be included as ***frx attributes*** also. Checkout the PHP SVGGraph library documentation to fully understand the available options, and identify the actual SVG Graph option you should be using (there are plenty of them).

In your case, I think you're looking for SVG Graph legends. In your Forena FRX file, you should be able to specify the desired legends (say `1st Legend`, `2nd Legend` and `3rd Legend`) within the SVG tag of your chart with something similar to this example:

```
  <svg frx:renderer="FrxSVGGraph"
    frx:legend_entries_1="1st Legend"
    frx:legend_entries_2="2nd Legend"
    frx:legend_entries_3="3rd Legend"
    ...
  />

```

For many more details about how to create charts with Forena, refer to the `reports/help.renderers#frxsvggraph` in your own site (which is part of what comes with Forena), or refer to the online equivalent of it.

**Note**: if you only have 1 legend (say `MyLegend`), the SVG tag of your chart should be similar to this example (no need for the suffixes like `_1`, etc):

```
  <svg frx:renderer="FrxSVGGraph"
    frx:legend_entries="MyLegend"
    ...
  />

```

---
Tags: charts, forena
---


# Question
Title: A user-friendly, fast way to delete the same field from several content types at once?
I have a Drupal 7.39 site with about 10 content types. All of these content types contains **2 fields** which I want to delete (It's a long story why).

Is there a way to delete both of these fields from all content types **at once**, instead of manually deleting each one of them from each content-type? Thanks,

# Answer
Field tools

> A collection of useful UI tools for working with fields:
>
> * Overview of fields with links to edit single instances, and all instances at once
> * Visual overview of relationships between entity types defined by entityreference fields, taxonomy reference fields, and schema
> properties, using GraphAPI
> * Clone any field instance to multiple entities and bundles
> * Clone all field instance of a bundle to multiple entities and bundles
> * Import and export fields
> * **Delete multiple instances of a field**
> * Apply a vocabulary to multiple entities and bundles at once (the same way vocabularies were applied to content types on Drupal 6)
> * ... your idea here. Patches welcome!
> 2 votes

# Answer
You can execute this code manually

```
field_delete_field('your_field_machine_name');

```
> 2 votes

---
Tags: nodes
---


# Question
Title: How to make Ajax request from a drupal page?
I have tried to make an Ajax request from drupal page. But output data is not correct . I have tried this

Ajax code:

```
function searchemail()
{
var email =$('#email').val();
    alert(email);
        $.ajax({
        method: "POST",
        contentType: "application/json; charset=utf-8",
        url: "emailcheck.php",
        data: "email="+"test",
        success: function(ret){
     alert(ret);
        },
        error: function(x,e){
            alert("error occur");
        }
    })

}

```

Output Code

```
<?php

echo "test"+$_REQUEST['email'];

```

But it prints only a 0 instead of 'test'

# Answer
> 1 votes
Have look at jQuery.ajax():

```
$.ajax({
  method: "POST",
  url: "emailcheck.php",
  data: { email: "test" }
})
.done(function( msg ) {
  alert( "Data Saved: " + msg );
});

```

Also check your url. Your PHP file has to be in the same folder as your js file when you use relative paths.

# Answer
> 1 votes
Use jQuery's ajax as jQuery is default part of Drupal (so no extra lib needed) like this:

```
$.ajax({
  method: "POST",
  url: "some.php",
  data: { name: "John", location: "Boston" }
})
  .done(function( msg ) {
    alert( "Data Saved: " + msg );
  });

```

The php handling of the request has to be inside the file where the url part points to. The data you send is to be found inside $\_POST variable inside PHP. if you don't know for sure which array element, just `var_dump($_POST);` and find out.

**For the JSON encoding part of the AJAX call:**

I've found this great jsfiddle example http://jsfiddle.net/sxGtM/3/

This will generate a nice JSONstring to send in the data part of your AJAX call.

Good luck!

# Answer
> 0 votes
First thing is you are not sending the data in json format. If it has to be sent using json format, please try some thing like **data: {"some":"some"}**

---
Tags: views, ajax
---


# Question
Title: How can i increase the size of color box pop up window in drupal 7. .?
I have implemented Colorbox module and configured it for my image gallery. But the issue is when I load the colorbox pop up window it seems to be very small in size. Even I tried using CSS setting height and width as 100%, but it's not making any difference.

Can anyone tell me as how to adjust the height / width of colorbox pop up model window?

# Answer
> 2 votes
You should probably check the settings at

```
admin/config/media/colorbox

```

If the issue is that the image is too small then you need to change the **Image style** to a different one or perhaps make a new one.

If you want to make the Colorbox larger you can use the Custom options on that same configuration page and set your own defaults for size. The Colorbox module should allow you to specify

* initial width
* initial height
* max width
* max height

If you choose **Custom** under the **Options** setting.

# Answer
> 0 votes
**Colorbox** can be used to display content pop-ups. By default, the popup's height and width will be exactly the same as that of the original content. But there may be times, when you want to load the content as per the screen height. This can be done easily using jQuery.

1. Assign the content which is to be displayed in the colorbox, to a variable.
2. Find the width and height of the above content.
3. Find the current screen's width and height.
4. Compare height of the content with screen height. If the content's height is greater than the screen height, the content's height is set as the screen height. Same, in the case of width.
5. Load the content with proper height and width in colorbox.

The code implementation of the above steps is given below:

```
$(".popout-link").click(function() {  //.popout-link, the class in which you need the pop-up functionality.
  var popup_content = $('#content').html(); // Replace #content with the content's id
  var y = $('#content').height(); //Content's height
  var x = $('#content').width();  //Content's width
  var wy = $(window).height();   // Assigning the screen's height to wy
  var wx = $(window).width();    // Assigning the screen's width to wy
  if (y > wy) { //Compares the height
    y = wy;
  }
  else {
    y = y;
  }
  if (x > wx) { //Compares the width
    x = wx;
  }
  else {
    x = x;
  }
  $.colorbox({html:""+popup_content+"", width:x, height:y, onComplete: function() { //loads the content in colorbox with specific width and height
    $('#cboxLoadedContent').jScrollPane(); // call this function to show scroll bar (You need to enable Jscrollpane Module to use this though)
  }
}

```

---
Tags: javascript
---


title: Node creation fields in blocks

text:
# Question
Title: Node creation fields in blocks
I am using Display Suite for node creation, but would like to extend this by also using blocks provided by theme to put several fields inside them too (sidebar left and right).

How to accomplish this ?

# Answer
You may need to enable the Display Suite Extras module. (comes with display suite)

Go to manage display, scroll all the way down. Click on custom fields, add a block field.
> 1 votes

---
Tags: display-suite, nodes
---


# Question
Title: Which kind of views style to use JS image effect?
I wonder which kind of views style do I choose to make a page like it can be done with masonry.

Actually I use Susy 2, and the example present items in `div`, actually I get items in a `ul` via views. Which is better?

# Answer
> 0 votes
Try using Views Fluid Grid - jQuery Masonry module.

---
Tags: views, 6, javascript
---


# Question
Title: Programmatically geting teaser of a field other than body
I need to get teaser of a custom field. I used the below code that I used for `body`.

```
$fieldContent = field_get_items('node', $nodeObj, 'my_field_name');
$teaser = field_view_value('node', $nodeObj, 'my_field_name', $fieldContent[0],'teaser');
//Below line prints an empty array
print_r($teaser);
$teaser   = drupal_render($teaser);

```

When I try the above code for the field `body` it works. What the code expects from the field to display teaser? How to fix this?

# Answer
Go to your node type's display settings for the teaser view mode and verify that the field is not hidden.
> 2 votes

---
Tags: entities, nodes
---


# Question
Title: SQL error after using Feeds Import with Taxonomies
I have been using intensively the Feeds module. After many imports of data doing test, I sometimes get the following error message: ´SQLSTATE\[23000\]: Integrity constraint violation: `1062 Duplicate entry taxonomy_term-32591-0-0-und' for key 'PRIMARY'`

Can I clean the database in such a way that I will no longer have this error message? Of course, when it happens, the taxonomy terms are not imported. After deleting the Feeds and importing again, it goes perfect, but the problem happens from time to time.

I don't think I have many extra modules which will store taxonomy tid's on them, so maybe the problem is with the core database tables, but I cannot find where there are still rows to be deleted manually to solve the problem.

Because the data are **already corrupted**, I pretend to manually repair the integrity of database (or with the help of a module) without having to look for a previous backup, which would imply losing hours of work done on other sections (and thus tables of the database).

# Answer
Finally, I have discovered the problem. I deleted the taxonomy data with the module Taxonomy Manager. When importing the data with Feeds again, it believes that the data remains there, even if they longer no exists. From here, some failed imports can make database corrupted.

To regain integrity, I looked for the problem tid, and checked that it appears in field\_data\_\* with entity\_type = 'taxonomy\_term' and field\_revision\_\* with the same entity\_type. I also appears in url\_alias, and didn't find any more instance of tid's with the problems in any more tables. I truncated all these tables.

I also checked that both modules, when deleting taxonomy terms, if the tables are empty, they don't make an additional TRUNCATE, so the new tid's don't start at tid = 1.
> 0 votes

---
Tags: 7, database, feeds
---


# Question
Title: Weird spacing in Views content after unspecified module update
I'll preface this by saying, I am very new to Drupal and pretty much have no idea what I am doing. I did not develop the site I am going to reference. With that said, recently I updated a handful of modules, I couldn't say which ones (I can't remember) and now there is some weird spacing on one of our pages which was created with Views.

The page that is throwing a weird spacing issue is https://tarltontest.law.utexas.edu/about-the-library/hours

The issue is that the data range between parentheses is now on three lines, rather than inline with the title, ie Fall Semester Hours, Fall Finals Hours, etc.

I cannot figure out where the spacing is coming from. I cannot see anything in the Views settings that would cause this. IS this a template file\> CSS? I don't even know where the parentheses are coming from.

I would love any help in identifying where to possibly look to fix this.

# Answer
> The issue is that the data range between parentheses is now on three lines, rather than inline with the title, ie Fall Semester Hours, Fall Finals Hours, etc.

looks fine to me...
> 0 votes

---
Tags: views
---


# Question
Title: How to use Solr Handlers when sending requests from Drupal
I'm using Solr 4.10.2 and Drupal 7.X, I have the Apache Solr Module Framework operating and sending the requests to Solr From Drupal. Currently when we perform a search, Drupal builds the query and sends it to Solr. Solr just executes the query and returns the results without using it's internal handlers which can be configured through SolrConfig.xml.

I would like to know if there is a way to just send the searched terms (without building a query) from Drupal and let Solr use the internal handlers declared in SolrConfig.xml to handle the request, build the query and then return the data?

The reason for this is we have been working on trying to boost some results when we perform a search (we want exact match first & fuzzy search results after) by changing the "weight" of some fields.

We know that from Back Office we can use the "Bias" function to boost some fields but this is too limited for what we are trying to achieve.

We also know we can change the query sent from Drupal directly from code side by using hook\_apachesolr\_modify\_query() but we prefer changing as little code as possible and using the SolrConfig.xml /handlers which we already have configured to return the results as we want.

# Answer
> 1 votes
Ok, we figured out how to do this. In order to choose the handler that is being used by Solr while sending a request from Drupal, we have to edit `hook_apachesolr_query_alter()` and add the following code:

```
$query->addParam('qt', 'MyHandlerName');

```

We did some extra coding to allow us to change the handler directly from back office in order to be able to switch handlers without touching the code.

---
Tags: search
---


# Question
Title: How to export comment fields (or other settings) with Features?
If I export a content type that has fields specified in the **comment** of the content type the fields of the comment are not exported.

How do I export those fields that I specified in the comment?

(In my case a have a Workflow status field specified in the comment)

# Answer
I Managed to do this with the help of the **Strongarm** module.

In the variables table there are fields like:

comment\_xxxx\_xx\_\[content\_type\_name\_here\]

for example: field\_bundle\_settings\_comment\__comment\_node\_my\_content\_type comment\_default\_per\_page\_my\_content\_type ..etc

I just selected all of them. It would be better of course to work out what is stored where.

Also in Features in **field instances** I found fields like: comment-comment\_node\_my\_content\_type-comment\_body ..

In Features **field\_base** I found something called comment\_body

Exporting those seemed to be everything. (Not too convenient to hunt fields and whatnot and maybe miss something..)
> 2 votes

# Answer
user3027622 - thank you - I would like to add to your response a little, to explain how this problem can be solved using drush.

I also found that the Comment fields (in particular, the order in which the fields were displayed) were not being exported.

I did this to solve the problem.

```
# see which component types are available
drush fc

# search for components we want to export
drush fc variable | grep comment
drush fc field_instance | grep comment

# export the components to my feature
drush fe myfeature variable:field_bundle_settings_comment__comment_node_partner_video_page variable:field_bundle_settings_comment__comment_node_video_page field_instance:comment-comment_node_partner_video_page-comment_body field_instance:comment-comment_node_video_page-comment_body

```
> 0 votes

---
Tags: entities, comments, features, importing-exporting, workflows
---


title: Adding a website URL to a Profile Field

text:
# Question
Title: Adding a website URL to a Profile Field
Adding a users' website link (URL) to a field. Can somebody please clarify the best approach to this using Profile2 as I cannot seem to find any option for "URL" type in any field. Maybe I'm having a blond moment or just cannot see the wood for the trees, but to save us hours searching online, can somebody advise on the simplest and most obvious solution to users being able to enter their 'website' link (ie: to link to an external URL such as a homesite such as a bandname.com, mybusiness.com).

I am also using Field Collection but presume any created filed type will be similar in setup.

I would envisage the user being able to add such a URL into their profile detial post registration in a similar way to the user DB on drupal.org (ala "Mywebsite").

Thank you.

# Answer
> 1 votes
There's no native URL field type in Drupal 7 but the Link module provides one with lots of features

> With this module links can be added easily to any content types and profiles and include advanced validating and different ways of storing internal or external links and URLs.

Profile2 profiles are entities so adding a link field to one will be an easy task through the UI.

# Answer
> 0 votes
You can also achieve that using the URL field module. I've used this module in one of my project. You can also add Optional title field to the URL.

Image from the module page.

---

You can also achieve that without using any contributed module.

Add textarea field (instead of text filed) and set Text processing as *Filtered text* in the field settings. Make sure to select **Convert URLs into links** option in Text Formats.

That's it. The entered URL will be appeared as link at output.

---
Tags: uri
---


title: Editing the Book Template

text:
# Question
Title: Editing the Book Template
I'd like to edit the way the Book navigation is structured. I'd like to be able to edit the html output of the book.

I was looking for a way to do this with the book template but had no luck. Looking at book-navigation.tpl.php I did see that $tree contained the children of the current node. However it used like this

```
<?print $tree; ?>

```

I don't see a way to alter the html of how the tree is output.

# Answer
The theme hook you'll want is `menu_link__book_toc_123`, where `123`is the node ID of your book's outline node.
For the wrapping markup, use `menu_tree__book_toc_123`.

You can also find the ID by inspecting the navigation list:
> 1 votes

---
Tags: 7, nodes
---


title: Using mixed case shortened URLs

text:
# Question
Title: Using mixed case shortened URLs
I have a content type **Advert**, which have **image** and **URL** fields and I put it in a block to place it on the page.

All works fine EXCEPT when the advertiser provides a mixed case `Bit.ly` shortened link to their site, Drupal is converting it to lower case but `Bit.ly` is case sensitive and either does not find the link at all or it redirect to another . How can I force Drupal to retain the mixed case URL, at least for external URLs? The `Bit.ly` link is important as the advertiser uses it to track ad clicks and hence the performance of the advert on our site

# Answer
Doh, what a dummy! I missed an option in rewrite results on the image field to set output as link with no transform!

Thanks everybody.
> 0 votes

---
Tags: uri
---


# Question
Title: Need of re-indexing on search on Drupal site?
My client site has a table whose data is coming from Indexed view, sometimes updates made to the data wont reflect in the view table. **Elysia cron** is installed and up running, which should update the content when changes are made.

Then what is need of re-indexing the search index?

I could see my index only 1% indexed even though I ran the cron 2-3 times. Can anyone help in this?

Thanks in advance

# Answer
> 0 votes
Cron by default only indexes a certain number of items each run. I believe it defaults to 100 items. The number is configurable from admin/config/search/settings.

The easiest way to force a reindex of an entire site is to use drush:

```
drush -y seach-reindex
drush -y seach-index

```

This will clear the index, and then index all unindexed items. Be prepared, this can take a long time.

Sometimes, though, if you have some weird custom logic in the node load or field attach process, the search can get caught up. When cron runs, the PHP timeout would eventually be hit. When run from drush, you would see no progress running.

---
Tags: views, cron, search
---


# Question
Title: How to add an extra form action on the user login page?
I would like to add a link to the user registration page on the user login page. As I want the link to be placed right next to the **Login** button, I thought that adding an extra form action would be the easiest way to do this.

Should I add/edit some template or is there a hook for this?

# Answer
> 1 votes
Use hook\_form\_FORM\_ID\_alter() in order to modify the specific form. You can add the action or the link there. The link can be added using the #prefix,#suffix attributes of either the form or of a specific element.

Prefix example:

```
$form['#prefix'] = l(t('Link text'), 'my link');

```

Action example:

```
$form['actions']['add'] = array(
  '#type' => 'submit',
  '#value' => t('Add'),
  '#submit' => array('_my_callback_function'),
);

```

---
Tags: 7, users
---


# Question
Title: How can I replace the Forum's vocabulary 'Forums' with my existing vocabulary 'tags'?
I use a "`tags`" taxonomy for most content on my site. The "Forum" (core) module insists on using its own vocabulary ("`Forums`") and also seems to have automatically created a vocabulary for itself.

Is there a way to have the forum module use my existing "tags" vocabulary? I'd imagine forum topics tags with a tagged term to be listed in a teaser kind of preview when browsing that tags' vocabulary's matching term (alongside other content with that tag).

**Edit**: See below screenshot where I try to change the vocabulary in the forum content type field. The vocabulary choice is disabled.

# Answer
After you enable the D7 core **Forum** module, you'll also have a "**Forum topic**" content type (and a "**Forums**" vocabulary as shown via `admin/structure/taxonomy/forums`).

Using the "Manage fields" tab of this content type (located at `/admin/structure/types/manage/forum/fields`), you can see the various fields for this content type. One of its fields is the "**Forums**" field (with machine name "**taxonomy\_forums**"), with "Term Reference" as Field type.

Click the "**Term Reference**" link of the "**Forums**" field there, which brings you to `/admin/structure/types/manage/forum/fields/taxonomy_forums/field-settings`, where you can change its "Field settings".

There you will be able to change the (default) "**Forums**" vocabulary to (e.g) your existing "Tags" vocabulary (or any other vocabulary you have defined).

**Attention**: if on the "Field settings" screen the Vocabulary drop down is disabled (= you cannot select another vocabulary, as in the screenprint in the "PS" of the question), and you get an error message like "*There is data for this field in the database. The field settings can no longer be changed.*", then you'll have to think of a way to get around it somehow. A few more links that provide some more details on this (and possibly other alternatives):

Be careful when trying to get this fixed! Because things may get worse ... You might consider a possible approach like this:

1. Create a new term reference Field for the Forum topic content type, and for which you then select the desired taxonomy.
2. After that, it should be OK to "delete" the original `taxonomy_forums` (machine name) field.

However, in doing so, the new term reference Field will have a machine name starting with a prefix `field_`. But if you then try to use that field (as part of the Forum module functionality), the Forum module might not use such `field_` prefix (you might get errors about that mismatch).

An alternative approach might be to uninstall/reinstall the Forum module, and then check if after enable you can change the taxonomy term field. However, in doing so, be aware that the taxonomy term "General discussion" of the taxonomy "Forums" (used by the module) is NOT deleted as part of the uninstall of the module. So before re-install (enable), you may want to try to manually delete that term and taxonomy first. If you don't do that, then you might end up with a taxonomy term like "General discussion" multiple times.
> 1 votes

---
Tags: 7, taxonomy-terms, nodes
---


# Question
Title: How to pass a variable $ _ GET in a page?
I will wish to create a privileged space for some users.

I create a role 'Candidate'. I assigned permission 'access user profiles' has this role. I create a user that uses this role. (eg, foo)

Secondly, I create a menu (see below)

```
$items['candidate/%candidate'] = array(
  'title'            => t('My candidate space'),
  'description'      => '',
  'page callback'    => 'cel_configuration_custom_page',
  'page arguments'   => array(1),
  'access arguments' => array('access user profiles'),
  'access callback' => TRUE,
);

```

Then a linked function

```
function cel_configuration_custom_page($args){
  return 'custom';
}

```

Finally, I have emptied the cache.

When I go on the **candidate/1** page with my account **'toto'** or account **'admin'**, I have not found page.

Why?

# Answer
> 2 votes
Try the following code:

```
    $items['candidate/%user'] = array(
      'title'            => t('My candidate space'),
      'page callback'    => 'cel_configuration_custom_page',
      'page arguments'   => array(1),
      'access arguments' => array('access user profiles'),
    );

    function cel_configuration_custom_page($account){
      return 'Custom page for ' . $account->name;
    }

```

You can't use `%candidate` as an argument for user accounts. Also, if you want to restrict access by a particular permission, don't set access callback to `TRUE` as that will grant access to everyone.

# Answer
> 1 votes
Thanks for your answers.

To solve the problem I use as my variable in url% or \['candidate /%'\] and it works properly.

---
Tags: routes
---


# Question
Title: Any module for user to custom make a schedule from listed options?
I'm looking for a module which can do something pretty specific. For a conference that our organization hosts, we have many different sessions during the day. People can pick and choose which one they want to attend.

We would like to create a page which will 1) list all the sessions available and 2) allow people to "favorite" or "pick" from these sessions which will add them to a smaller list, which they can view on a separate page. Ideally this will *not* require individuals to be logged in, but rely on cookies.

Does anyone know of a module with functions like these? It could really be a view with more robust features, but I can't find an extension of Views which has these features.

# Answer
Alternatively, you can also use the Flag module in order to flag content in your view. Then, you can create another view which displays only the content you've flagged. This might be more simple.
> 0 votes

# Answer
I haven't done it persay. But, having attended many Drupal Camp's and 1 Drupal Convention I know the Conference Organization Distribution (COD) has this basic feature-set built it.

COD include the concept of Sessions, and session collections. I know that users can select tracks to register for (typically in a day-calendar view) and then a users session list appears on the users dashboard/account page.

I would recommend either downloading the COD distribution and using it directly, or viewing the install profile of COD and the included content types, Fields, Views, Rules, etc and reverse engineering the functionality you want on a smaller scale.
> 0 votes

---
Tags: 7
---


# Question
Title: Is There A Way To Remove Kickstart Demo Product Types Without Emptying Database?
Is there are a (safe) way to delete the demonstration Product Types in Commerce Kickstart 2 without the entire Drupal install?

It appears that the Commerce Kickstart 'Reset' function simply empties the entire db. (yikes).

I've read many discussions on this but they tend to go back to 2011. I was hoping there was a more current (and hopeful) answer. We want to get rid of all the 'Drinks', 'Tops', etc. but keep the Products/Types and other content we've created.

# Answer
> 1 votes
hmm my understanding was that Kickstarter kit was a "hey see what it can do once fully configured!" example of Commerce. Understanding the setup -- you could then go back and install/configure Commerce by hands to your needs.

That being said Commerce content I think is just Entities and Nodes, If you want an non-SQL way to reset a site (i've written ~34 sql Delete statements to nuke content from sites in an sql script for drupal -- it's not *that* hard you just look at `node` and `field_*` tables mostly when clearing `content` from a drupal site) I'd recommend looking at the Delete All module and the documentation found in `drush help delete-all` as a GUI means of selecting out types of content to nuke from a drupal site.

# EDIT: DrupalCamp Montreal 2014 steps to setting up Commerce ala Commerce Kickstart but Not Depending on the Kickstarter kit

Original source (broken): http://renaudjoubert.com/en/article/step-step-guide-to-installing-commerce-scratch

```
Step by step guide to installing Commerce from scratch

The following guide was used in a presentation at DrupalCamp Montreal 2014.
The presentation focused on how to install Drupal Commerce from scratch
(i.e. we won't use the Commerce Kickstart distribution).
This is an elevator guide. So get in now because we're going up!

FIRST FLOOR
https://www.drupal.org/project/commerce
Install required modules
drush dl ctools views entity rules addressfield commerce
drush en ctools views entity rules addressfield commerce -y
Installation instructions
https://www.drupal.org/node/1007434
use the provided drush commands
drush en commerce commerce_ui -y
drush en commerce_customer commerce_customer_ui -y
drush en commerce_price -y
drush en commerce_line_item commerce_line_item_ui -y
drush en commerce_order commerce_order_ui -y
drush en commerce_checkout commerce_payment commerce_product -y
drush en commerce_cart commerce_product_pricing -y
drush en commerce_product_ui -y
drush en commerce_tax_ui -y
Add a few more useful modules
drush dl admin_menu module_filter zurb-foundation-7.x-4.x-dev jquery_update -y
drush pm-disable toolbar
drush en admin_menu_toolbar module_filter jquery_update -y
Create a responsive Zurb subtheme
drush fst Your Subtheme Name your_subtheme_name 'A subtheme of ZURB Foundation.'
Set jQuery update to 1.7+ (admin/config/development/jquery_update)
Enable your new responsive subtheme (admin/appearance)

SECOND FLOOR
Quick tour of what we've got soo far
1 Product type named 'Product'
2 tax types
LOTS of hidden functionnalities
NO visible products
and NO, you don't get a store out-of-the-box
Commerce Kickstart gives you that but you won't know how to get there if you don't try from scratch
Create a new product type 'Download'
add file & image fields
Revisit 'Product', the product type installed by Commerce
add an image field
Let's create products
a physical product (Product)
a virtual product (Download)
Now what? where's the store?
Gotcha!

THIRD FLOOR
Out-of-the-box Store is for wimps! ; )
Commerce products only exist in the backstore
products are like brown boxes in a warehouse: they're only accessible to the store's employees
in order to make products accessible to customers, you need to put them on display in a nice and attractive way
how do we do that in Drupal?
we use content types, of course
Create a content type for displaying products
how does Commerce differentiate & recognize product displays from regular content types?
a product reference field!
create product displays and configure them
Alright, let's shop!
wait a minute, nothing happens when i click Add to cart!
Gotcha!

FOURTH FLOOR
In case you didn't read the fine print: some assembly is required, like Ikea, but without the KISS diagrams
Introducing Rules... doh! where's the UI ?
drush en rules_admin -y
go to admin/config/workflow/rules and add a rule that redirects to the cart
Welcome to the cart
Time to checkout wouldn't you say ?
doh!... something isn't right
where are the taxes?
Like I said, Out-of-the-box taxes are for wimps! ; )
Commerce's taxe model is simple
there are tax types; like there are product types and content types
and then there are tax rates which you create using one of the available tax types
Create GST & PST tax rates (note - these taxes are specific to the Province of Quebec in Canada where the camp was held)
Revisit the checkout
Darn, the taxes are not displayed in the expected order! (i.e. GST on this first row, PST on the second row)
How do we change the order in which taxes are displayed ?
the hard way: by overriding theme_commerce_price_formatted_components() in the theme's template.php (see https://drupal.org/node/1095576#comment-8721217)
the easy way: by creating separate tax types for GST and PST and playing with their respective weight (note that at the time of this writing, the behaviour for tax weights does not follow the convention where lighter weights float to the top; see this issue)
Are we in business yet? Not quite.

FITH FLOOR
Setting up a payment method
for simple tests, use the 'Example payment' module (provided by Commerce)
For serious tests and real sales, you can use Stripe or Paypal or whatever works for you. For the purpose of this presentation,I used Stripe.
www.stripe.com
setup an account
get the API keys (secret and publishable)
Install & configure Stripe
drush dl commerce_stripe
drush en commerce_stripe -y
add both keys to the Stripe payment method rule (admin/commerce/config/payment-methods/manage/commerce_payment_commerce_stripe)
Time for some tests
for this, we use the dummy credit cards provided by Stripe
https://stripe.com/docs/testing
When you're happy that all works like it should you can replace de test API keys by the live API keys.
Done!

```

# Answer
> 1 votes
This worked for me:

```
drush dis commerce_kickstart_product -y
drush vset commerce_kickstart_demo_store 0
drush en commerce_kickstart_lite_product -y

```

This seemed to allow one to delete the demo product types and such. Not sure if they are regenerated later or not.

---
Tags: commerce
---


# Question
Title: Switch style plugin of a view based on results
I would like to create a view, which would display it's result with style plugin *Unformatted* if there is only 1 result, but would use *Bootstrap Accordion* style plugin, if there are more of them. I tried to do it like this:

~~```
    name == 'some_view_name') {
        if (count($view->result) > 1) {
          $view->style_plugin = 'ViewsBootstrapAccordionPluginStyle';
          $view->style_plugin->plugin_name = 'views_bootstrap_accordion_plugin_style';
          $view->style_plugin->options['title_field'] = 'title';
          $view->style_plugin->definition['path'] = 'sites/all/modules/views_bootstrap/plugins/accordion';
          $view->style_plugin->definition['theme path'] = 'sites/all/modules/views_bootstrap/templates/accordion';
          $view->style_plugin->definition['file'] = 'ViewsBootstrapAccordionPluginStyle.inc';
          $view->style_plugin->definition['theme file'] = 'theme.inc';

        }
      }
    }

```
The result is this error:
`Fatal error: Call to a member function render() on a non-object in .../sites/all/modules/views/theme/theme.inc on line 49`
~~

What am I doing wrong?

EDIT: Probably almost everything. `$view->style_plugin` has to be an object, that was the reason of the error above. So I modified the code to this:

```
<?php
function my_module_views_pre_render(&$view) {
  if ($view->name == 'my_view') {
    if (count($view->result) > 1) {
      $bs_accordion_style = new ViewsBootstrapAccordionPluginStyle;
      $bs_accordion_style->plugin_name = 'views_bootstrap_accordion_plugin_style';
      $bs_accordion_style->options['title_field'] = 'title';
      $bs_accordion_style->definition['path'] = 'sites/all/modules/views_bootstrap/plugins/accordion';
      $bs_accordion_style->definition['theme path'] = 'sites/all/modules/views_bootstrap/templates/accordion';
      $bs_accordion_style->definition['file'] = 'ViewsBootstrapAccordionPluginStyle.inc';
      $bs_accordion_style->definition['theme file'] = 'theme.inc';
      $bs_accordion_style->options['grouping'] = array();
      $bs_accordion_style->row_plugin = $view->style_plugin->row_plugin;
      $bs_accordion_style->definition['theme'] = 'views_bootstrap_accordion_plugin_style';
      $bs_accordion_style->view = $view->style_plugin->view;
      $bs_accordion_style->display = $view->style_plugin->display;
      $view->style_plugin = $bs_accordion_style;
      $view->style_options['title_field'] = 'title';
    }
  }
}

```

That almost works. It results in this error (1 per view result):

`Recoverable fatal error: Object of class stdClass could not be converted to string in include() (line 21 of .../sites/all/modules/views_bootstrap/templates/accordion/views-bootstrap-accordion-plugin-style.tpl.php)`

How can I correct this?

# Answer
I have finally discovered a workaround, that may be the solution for some. I display the view using Panels. Using *visibility rule*, there is possibility to limit visibility of view based on number of results of that view. The steps could be:

1. Create a *Contextual filter* for your view for field `Content:Nid`. This should correspond to argument of your *Ctools Page* (so that path of a page is similar to `something/%nid`). You may need to add Relationship, if you want to display content, that is related to the content with `nid`.
2. Create a *Context* display for your view.
3. Create a 2 separate displays (*Content panes*) for your view - for one result and multiple results.
4. Create a new *Relationship* based on your view for your Panel (at the *Contexts* tab).
5. Add **both** your *content panes* to the panel.
6. Add *Visibility rules* to both panes. You should choose PHP-based filtering and enter something like:

`if (count($contexts['relationship_view_from_argument:name-of-your-view-ctools_context_1_1']->output['rows'])==1) {` `return TRUE;` `}`
> 0 votes

---
Tags: views
---


title: How to send an email using a field key?

text:
# Question
Title: How to send an email using a field key?
I am attempting to send an email to a field selected value using the Rules module. The user selects a faculty member and saves the node. The rule should fire off and email based on the field's key. I have the field set up as:

> john@email.com|Doe, John

I am attempting to send to the key using `[node:field-advisor-:key]` as a replacement pattern. But I think it's still trying to send to the label.

I am still very new to Drupal so my vocabulary and skills are relatively limited.

Here is the exported rule:

```
  { "rules_email_to_adviser" : {
  "LABEL" : "Email to Adviser",
  "PLUGIN" : "reaction rule",
  "OWNER" : "rules",
  "REQUIRES" : [ "rules" ],
  "ON" : { "node_insert--timeclock" : { "bundle" : "timeclock" } },
  "IF" : [
        { "user_has_role" : { "account" : [ "node:author" ], "roles" : {
        "value" : { "20" : "20" } } } },
       { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_advisor_" } }
    ],
  "DO" : [
    { "mail" : {
        "to" : "[node:field-advisor-:key]",
        "subject" : "Time Card Submitted for Review",
        "message" : "[node:author] has submitted a time card for your approval. \r\n\r\nPlease review the time card at: [node:edit-url]\r\n\r\nThank you.",
        "language" : [ "" ]
      }
    }
  ]
  }
}

```

**Notes**:

* All of the faculty members (such as "John Doe") have accounts on the site.
* If it would help (simplify things) to make the rule work, I'm OK with replacing the implementation of that `field_advisor_`-field by a more appropriate field (with similar functionality).

# Answer
> 1 votes
# Part 1: Review the definition of your field

Assuming that all of the faculty members have an account on your site (as you confirmed in one of your comments), I recommend to replace the implementation of that `field_advisor_`-field. I.e. delete that field in your `timeclock` content type, and add a more appropriate field that looks like so:

* Field Name = Anything you want, say with a machine name like `field_timeclock_reviewer`
* Field Type = Entity Reference, with *Target type* = `user` and *Number of values* = `1` (pick any of the other options to define this field as you see fit).

By using this field, you don't have to maintain the data of that field as in your example with `john@email.com|Doe, John` (instead you take advantage of the already administered userids and their corresponding eMail IDs).

**Note**: to limit the list of users that can be referenced to only those users with a specific role (like "faculty"), you should use **Views "Entity selection mode"** for your entity reference field in the Entity Reference widget. But before you can select the appropriate "View" to do so, you should create a view (with the Views module) to create a list of all users with that specific role.

# Part 2: Rule to send the eMail

After you adapted the setup of your field as described above, it is straight forward to write a rule for the Rules module to send such eMail that you're looking for.

Here is a sample of such rule (in Rules export format), which will send such eMail to the userid selected via the field `field_blog_reviewer` (= a field I added to my "Blog" content type that is defined as an entity reference to a 'user'), and this whenever a new node of content type "Blog" is saved:

```
{ "rules_notify_reviewer_about_outstanding_approval" : {
    "LABEL" : "Notify reviewer about outstanding approval",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--blog" : { "bundle" : "blog" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_blog_reviewer" } }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[node:field-blog-reviewer]",
          "subject" : "Blog Post waiting your approval",
          "message" : "[node:author] has submitted a new Blog post waiting your approval.\r\n\r\nYou can review it at: [node:edit-url].",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

If in the above exported rule you'd change "`blog`" to "`timeclock`" (before importing this rule in your environment), and after you also add that extra `user_has_role` condition (as in your question), you should be pretty close to getting it to work (with an eMail that is similar to what you wanted it to be).

---
Tags: rules, emails
---