# Question
Title: "Authored by" field to be automatically filled
On every creation of a node or edit of a node I need the "Authored by" field to be automatically populated with the username of anyone saving changes.

any ideas how I can do that?

Thanks.

# Answer
> 6 votes
Personally I think that a module like Rules (powerful and awesome as it is) is overkill for something relatively simple as this.

Looking at node\_form(), I see that the author is set by populating the author field with the username. I would create a custom module which implements hook\_form\_BASE\_FORM\_ID\_alter, and set the default value of the author name field to the name of the current user. That would look something like this (disclaimer: untested code!).

```
<?php

function MODULENAME_form_node_form_alter(&$form, &$form_state, $form_id) {
  // Always set the username to the current user. An empty string means anonymous.
  global $user;
  $form['author']['name']['#default_value'] = !empty($user->name) ? $user->name : '';
}

```

An advantage of this solution is that the field is populated in advance with a default value, allowing user with sufficient permissions (eg. administrators) to override the author as they always can. It would be harder to do that in a rules-based approach which only kicks in after the form has been submitted.

---

*update:*

The topic starter mentions in another answer that he ended up with the following code:

```
function module_name_form_alter(&$form, &$form_state, $form_id) {
  // Always set the username to the current user. An empty string means anonymous.
  global $user;
  if ($form_id == 'content_type_node_form') {
    $form['author']['name']['#default_value'] = $user->name;
  }
}

```

Some feedback on this code:

* Of course, the if-statement makes sense if you only need this behavior in certain cases. You could even place the `global $user;` inside the if.
* I would recommend that you keep the `!empty($user->name) ? $user->name : ''` part, instead of simply using `$user->name`. It may be an edge case, but as you can see in drupal\_anonymous\_user, the global $user object does not necessarily contain a 'name' property. If, at some point in the future, this form would become available for anonymous users, they will end up with php notices on their screen.

# Answer
> 3 votes
I'd use Rules to do this. You need to create a rule to respond to a node being updated, then add an action which sets the author value from the current user.

# Answer
> 0 votes
thanks a bunch, It worked well and I simply did this(just a few changes from what you've written)

```
function module_name_form_alter(&$form, &$form_state, $form_id) {
  // Always set the username to the current user. An empty string means anonymous.
  global $user;
  if($form_id=='content_type_node_form'){
    $form['author']['name']['#default_value'] = $user->name;
  }
}

```

# Answer
> 0 votes
If we want to implement this in any node form irrespective of Content type then we can use preg\_match.

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

global $user;
// for all type of content node forms we can use preg_match
if (preg_match('/.*_node_form/',$form_id)) {
$form['author']['name']['#default_value'] = $user->name ;
}
}

```

# Answer
> -1 votes
This should just happen when created, if Author and Date information are ticked in admin/structure/types/manage/\[your\_content\_type\], under display settings.

If you want something else, you can use the token module and use a token as default value ; again in the content type settings.

If you want it updated with every save, you have to use hook\_node\_update() in a custom module, and set `$node->uid` to current user's ID (`global $user; $user->uid`).

---
Tags: nodes
---


# Question
Title: Drupal Commerce: Prices on Variations not displayed when selecting a variation
I am using Drupal Commerce Kickstart 2.

When a user selects a value from the size drop down (variation), the price and other attributes do not update on the product display. I need to have something similar to this -\> http://demo.commerceguys.com/ck/storage-devices/commerce-guys-usb-key. You'll see that when you select a memory size for the USB product the price will change.

Is this a built in feature for Drupal Kickstart or something they built through a custom module?

I have a product variation with a product attribute of Size (a user can select which size they want). I have product details such as SKU, Price, and Package.

I also have a product display set up by default, which displays my product variations as my Add to Cart form.

In the following picture you will see that even though I have 5 oz. selected all the details displayed are for the 10 oz. variation.

I need to know how to update these details based on which variation the user selects.

Any help on this is appreciated

# Answer
This seems to work out of the box. There was a JQuery version conflict that was causing javascript errors.
> 0 votes

---
Tags: ajax, commerce
---


# Question
Title: Three level menu: How to show only the children of the current page?
A three level menu:

```
  Item 1
    Item A
        Item X
        Item Y
        Item Z
    Item B
        Item Xx
        Item Yx
        Item Zx
    Item C
        Item Xy

```

When viewing the "Item 1" node, I'd like to display the sub-menu items in the template: Item A, Item B, Item C

When viewing the "Item B" node, I'd like to display the sub-menu items in the template: Item Xx, Item Yx, Item Zx

While I would like to rely totally on the menu structure, the output will not be displayed as a traditional menu.

This code does what I need:

```
function subpages($nid=null) {

$nid = 'node/'.$nid;

$menuItems = menu_tree_page_data('main-menu');

foreach($menuItems as $key => $m) {
    if ($m['link']['in_active_trail'] && $menuItems[$key]['below'] && $m['link']['link_path']  == $nid) {
        $menu = menu_tree_output($menuItems [$key]['below']);
        } else if ($m['link']['in_active_trail'] && count($menuItems[$key]['below']) > 0) {
            foreach ($menuItems[$key]['below'] as $k => $third) {
                if ($third['below'] && $third['link']['in_active_trail']) {
                    $menu = menu_tree_output($third['below']);
                //foreach ($third['below'] as $item) {
                //  echo $item['link']['link_title'].'<br>';
                //}
            }
        }
    }
}
return $menu;

```

}

# Answer
You can do that with Menu Block module.

> It provides configurable blocks of menu trees starting with any level of any menu. And more!

You can then first create a menu block in the block configuration page. Then configure the menu block to start with the 2nd or 3rd level according to which level of the menu you want to have and set the depth to 1 so that it only lists that level and not its children.

If you want to have sub-menu items follow the current menu item, i.e. it always shows the children of the current page, you should set under the menu block configuration, **Advanced Options**, and check **Make the starting level follow the active menu item.**
> 4 votes

# Answer
You can get a menu which display the children of the active menu item, ***without having to create a block for each level***, with the Menu Block module alone. Here is how:

# How?

> This works for the 7.x-2.5 version of Menu Block, I cannot guarantee this will work for other versions. Currently, they are planning to apply this patch to 2.6, so the patch (Step 2) may not be required in the future

1. Download the Menu Block module
2. Apply this patch
3. Enable the module
4. Go to *Structure \> Blocks* and click 'Add Menu Block'
5. Configure like so:

* **Starting level**: 1st level (primary)
    * **Make the starting level follow the active menu item**: checked
    * **Starting level will be**: Children of active menu item
    * **Maximum depth**: 1
    * **Make the maximum depth relative to the starting level while following the active menu item**: checked

(To get the sibling of the active menu item, change 'Starting level will be' to 'Active menu item' instead.)

# What does the patch do?

Before the patch, in 7.x-2.5, the maximum depth option is relative to the menu root. After the patch, you have an option to "Make the maximum depth relative to the starting level while following the active menu item".
> 2 votes

---
Tags: routes, 7
---


# Question
Title: Custom form multiple file upload with different extension
I am working multi file upload functionality with different extensions(pdf,doc,png,jpg). Following code is working fine for multiple images upload. **I would like to know how this code modify for different extension like doc, pdf, png,gif etc.**

```
function mymodule_form($form, &$form_state) {
    $form['file'] = array(
        '#type' => 'file',
        '#name' => 'files[]',
        '#title' => t('Upload some photos'),
        '#attributes' => array('multiple' => 'multiple'),
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),

    );
}

form mymodule_form_validate($form, &$form_state) {
    //Save multiple files
    $num_files = count($_FILES['files']['name']);
    for ($i = 0; $i < $num_files; $i++) {
        $file = file_save_upload($i, array(
            'file_validate_is_image' => array(),
            'file_validate_extensions' => array('png gif jpg jpeg'),
        ));
        if ($file) {
            if ($file = file_move($file, 'public://images')) {
                $form_state['values']['file'][$i] = $file;
            }
            else {
                form_set_error('file', t('Failed to write the uploaded file the site\'s file folder.'));
            }
        }
        else {
            form_set_error('file', t('No file was uploaded.'));
        }
    }
}

```

# Answer
> 1 votes
You can use `'#type' => 'managed_file'` instead of  `'#type' => 'file'`

managed\_file types is powerful tools support any kind of files format with ajax upload.

example :
`$form['file'] = array(
 '#type' => 'managed_file',
 '#name' => 'files[]',
 '#title' => t('Upload some photos'),
 '#attributes' => array('multiple' => 'multiple'),
 );` you can also add upload location of files like

`'#upload_location' => 'public://myfiles/'`

for more info. https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#managed\_file

# Answer
> 0 votes
In your validation function you have added `file_validate_is_image`. This function returns an array. If the file is not an image, it will contain an error message that's why you are unable to add other extensions except images.

You have to remove it (`file_validate_is_image`) and try again.

```
'file_validate_extensions' => array('png gif jpg jpeg pdf doc'), //add different extensions whatever you would like to.

```

---
Tags: 7, files
---


# Question
Title: How do I override views-view-summary-unformatted.tpl.php inside my own theme?
I cannot override views-view-summary-unformatted.tpl.php inside my own theme. I copy the tpl from the views module directory, paste into my theme directory and modify the code. My website will not recognize the new tpl. If I make the changes directly inside the views module, then I can see my changes on my website. However, I know it is not best practice to hack a contributed module. I've tried adding "--myViewName" to the tpl file, but this doesn't help. When I look at the Theme Information in my view, I don't see views-view-summary-unformatted.tpl.php listed there. (The reason I am trying to override this tpl is that I want my alpha bar to include all letters of the alphabet even if there are no entries for a particular letter.) Can someone please help me figure out what I am doing wrong? Thanks!

# Answer
I know this is old but today I struggled with this and thought I should provide a solution.

First, you have to rename your copy of 'views-view-summary-unformatted.tpl.php' so views can discover it. It should be named **'views-view-summary-unformatted--my-view.tpl.php'**.

You then need to click the **'rescan template files'** button under the theme information in the view.
> 1 votes

---
Tags: views
---


# Question
Title: How can we retain dropdown list value, when we select the option?
I want to retain dropdown list value, so that when ever someone select the option from the dropdown list should retain that value after performing the action.

```
/*
 *implements hook_menu().
 */

function dropdown_page_menu(){
  $items = array();
  $items['page/layout/%'] = array(
    'title' => 'Select Layout',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('dropdown_page_select_form'),
    'access arguments' => array('access content'),
    );

  return $items;
}

/**
 * Implements hook_block_info().
 */
function dropdown_page_block_info() {
    $blocks = array();

    $blocks['dropdown_page_select_form'] = array(
        'info' => t('Select Layout'),
    );

    return $blocks;
}

/**
 * Implements hook_block_view().
 */
function dropdown_page_block_view($delta = '') {
    $block = array();

    switch ($delta) {
        case 'dropdown_page_select_form':
            $block['subject'] = t('Select Layout');
            $block['content'] = drupal_get_form('dropdown_page_select_form');
            break;
    }

    return $block;
}

function dropdown_page_select_form($form, &$form_state){
  $options = array(
    'select' => t('Select'),
    'layout_1' => t('Layout 1'),
    'layout_2' => t('Layout 2'),
    'layout_3' => t('Layout 3'),
    );

  $form['choice'] = array(
    '#type' => 'select',
    '#options' => $options,
    '#title' => t('Select your layout'),
    '#default_value' => $form_state['choice']['type']
    );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value'=> t('Go'),
    );
  return $form;
}

function dropdown_page_select_form_submit($form, &$form_state){

switch ($form_state['values']['choice']){
  case layout_1 : {

    //echo 'hi';die;
    drupal_goto("layout_1".$options);
    break;

  }
  case layout_2 : {
    //echo 'no';die;
    drupal_goto("layout_2".$options);
    break;
  }
  case layout_3 : {
    drupal_goto("layout_3".$options);
    break;
  }
  default: {
    print 'Select it!';
  }
}

  drupal_set_message(t('Your layout %input', array('%input' => $form_state['value']['choice'])));
}

```

# Answer
Try following code. I think you need this value to be retained through all pages while navigating.

```
function dropdown_page_select_form($form, &$form_state) {
    $options = array(
        'select' => t('Select'),
        'layout_1' => t('Layout 1'),
        'layout_2' => t('Layout 2'),
        'layout_3' => t('Layout 3'),
    );

    $form['choice'] = array(
        '#type' => 'select',
        '#options' => $options,
        '#title' => t('Select your layout'),
        '#default_value' => isset($_SESSION['selected_layout']) ? $_SESSION['selected_layout'] : 'select'
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Go'),
    );
    return $form;
}

function dropdown_page_select_form_submit($form, &$form_state) {
    $_SESSION['selected_layout'] = $form_state['values']['choice'];
    drupal_set_message(t('Your layout %input', array('%input' => $form_state['value']['choice'])));
    switch ($form_state['values']['choice']) {
        case 'layout_1' : {

                //echo 'hi';die;
                drupal_goto("layout_1" . $options);
                break;
            }
        case 'layout_2' : {
                //echo 'no';die;
                drupal_goto("layout_2" . $options);
                break;
            }
        case 'layout_3' : {
                drupal_goto("layout_3" . $options);
                break;
            }
        default: {
                print 'Select it!';
            }
    }
}

```
> 0 votes

# Answer
You can set the default values as follows,

`$form['choice'] = array(
 '#type' => 'select',
 '#options' => $options,
 '#title' => t('Select your layout'),
 '#default_value' => variable_get('choice', $form_state['choice']['type']
)
);`

provided you get the submitted values in the variable $form\_state\['choice'\]\['type'\] post submit action. And the variable name should match the form field name "choice"

Hope this works for you!
> 0 votes

---
Tags: forms
---


# Question
Title: how to use function arg() in drupal to call .tpl files?
I have 3 .tpl files, how can i call these tpl files by using function arg(). actually i want to show 3 different .tpl files to user when he request from a dropdown options.

The detail description is i want to create a page which render list of nodes in a page but i like to give option to user that weather he wants all the node in single column layout or 2 column layout or 3 column layout. For these layout i'm creating 3 different .tpl files so now i want to call them on the request of dropdown list.

# Answer
Considering that you want tpl for page, continuing to the answer https://drupal.stackexchange.com/a/149899/39999, you can create layout files as follow:

In `template.php` add following function and replace with your theme name:

```
function <THEME>_preprocess_page(&$vars){
    if(isset($_SESSION['selected_layout']) && !empty($_SESSION['selected_layout']) && $_SESSION['selected_layout'] != 'select'){
        $vars['theme_hook_suggestions'][] = 'page__'.$_SESSION['selected_layout']; //setting a new page template
    }
}

```

Then create following template files:

1. page--layout-1.tpl.php
2. page--layout-2.tpl.php
3. page--layout-3.tpl.php
> 0 votes

# Answer
If I understand it correctly you are looking for a way to render .tpl.php files on certain paths, this article explains how to do it.

In the article they define only one path and show you how to make sure a .tpl.php is rendered. You can easily adjust the code to make it work with 3 different paths and 3 different tpl.php files.

Hope this helps!
> 0 votes

---
Tags: 7
---


# Question
Title: Hook the language switcher and change the URLs it redirects to in Drupal 7
I have a multilanguage site in Drupal 7.

The language negotiation is based on URL. I have got translated content, so when I visit **www.example.com/this-is-a-news** in *English*, I can change to *Spanish* using the **language switcher** and go to **www.example.com/esta-es-una-noticia**, which is the URL of the translated node. However, I have some URLs which are dynamic, i.e., they are built in-the-fly, for example: www.example.com/this-is-a-news/on-the-fly-parameter...

As the part of the URL */on-the-fly-parameter* is completely dynamic and can change, and because the translation is a non-Drupal table in the database which is updated independently, I want to hook the language switcher and add the translations of all of these URLs dynamically. How can I achieve this?

# Answer
> 1 votes
I have discovered how to do it.

```
function MYTEMPLATE_language_switch_links_alter(array &$links, $type, $path) {

 $extract_parameters_URL = explode("/", $_SERVER['REQUEST_URI']);

 $code_altered_url = process_URL_extracts($extract_parameters_URL);

 foreach ($links as $langcode => $link) {

    $links[$langcode]['href'] = $code_altered_url ;

 } // foreach

```

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


# Question
Title: Drupal Ubercart to Commerce Migration: any solution for uc_file (file downloads)?
I've recently upgraded a Drupal site from 6 to 7, and now want to migrate from Ubercart to Drupal commerce. The Ubercart upgrade has been completed already just in case.

Ubercart has a module called uc\_file that allows files to be assigned to products.

The module has three tables: 1. uc\_files: contains the file id (fid) and the name of the file 2. uc\_file\_products: contains fid, feature product id (fpid), something called pfid, and some other fields for the description, etc. 3. uc\_file\_users: contains fid, uid, fpid, fuid (?), and other fields.

Has anyone migrated these tables, and if so, what approach did you take? The most important data I need to migrate is the actual line item purchases, so the users will be able to access their purchased downloads.

I have commerce\_migrate\_ubercart installed, but it doesn't appear to handle the Ubercart File Downloads, which is the entire store.

# Answer
> 0 votes
Well as it turns out, no code was needed.

In case anyone runs into this issue, here's what you need to do:

1. Download the dev version of commerce\_migrate\_ubercart and apply the payment patch if it hasn't already been applied.
2. Disable all Ubercart modules
3. Carefully follow the instructions in the README.txt file. You'll want to migrate every available table starting with products, and working your way to payments (transactions). Save the database early and often along the way.
4. Download/configure commerce\_file and commerce\_license.
5. Be sure you are able to go end-to-end with your cart and download privileged files in your user/uid/my\_files tab.
6. Download/enable commerce\_vbo\_views and views\_bulk\_operations
7. Edit the rule "Activates licenses of an order", and add the event "After updating an existing commerce order".
8. Go to your Store's order list page, select the desired order states that have completed orders, then select all rows in the table, then click modify order values, and just set the exact same state as selected before. What we're after here is to force a re-save of the order to trigger our rule.
9. You should now be able to view a user and click the "Files" tab to see their downloads assuming permissions are correctly set and the migration worked.
10. Edit the rule again to remove the added event and you're done.

Easy peasy :)

---
Tags: 7, commerce, ubercart, migrations
---


# Question
Title: Is there module that allows linking or embedding attachments or images from other nodes?
I need a module that allows me to link or embed attachments and images from other nodes, using a filter syntax like \[moduletag:node-id:filename\], \[moduletag:node-id:attachment\_index\], \[moduletag:node-id:image\_index\].

It will be especially helpful on nodes which exist for attaching images to, so that I can reference individual images on that node if needed.

# Answer
> 2 votes
I recommend to use the **Media** module (https://www.drupal.org/project/media)...

**Alternative 1:**

I have no experience with this module, but **FileField Sources** (https://www.drupal.org/project/filefield\_sources) could solve your problem, including:

* Re-use files by an auto-complete textfield
* Attach server-side files uploaded via FTP
* Transfer files from a remote server (cURL required)
* Paste a file directly from the clipboard (Drupal 7 only)
* Select existing files through the IMCE file browser

**Alternative 2**

Another possibility is described here: https://drupal.stackexchange.com/a/53971/36708

---
Tags: nodes, navigation
---


# Question
Title: Problems with accessing private files uploaded via file field in a webform
I have a webform with a file field configured to private files. When I'm logged in as a superuser (uid=1) and trying to download the file, I get access denied.

I was trying to debug this, and this is what I noticed.

All private files served by the `file_download()` function that is called in the system.module. This function validates if the file exists and request the file headers using `file_download_headers()` function that triggers `hook_file_download()`.

In the `webform_file_download()` function the module determines whether the file was a webform upload and grant or deny file access based on access to the submission. It validates access permission by calling `webform_submission_access()`. When I run dpm($account) in this function, I get an anonymous user when I'm trying to access the private file. When I browse recent log messages I have the entry below:

```
access denied   06/02/2015 - 11:23  system/files/webform/cv-uploads/cv.pdf  Anonymous

```

When I change the URL to file that doesn't exist, I get this:

```
page not found  06/02/2015 - 11:26  system/files/webform/cv-uploads/cv.FDP  admin

```

As you can see for some reasons when the module is trying to get access to the file that does exist, I get *access denied* and the user is anonymous. When the file doesn't exist, I get *page not found* and the user is a logged in user.

Any ideas why this happens?

**UPDATE**

I've added the following code to my index.php but I still get anonymous user when I'm trying to access the file.

```
define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

+ global $user;
+ watchdog('user', '<pre>'. print_r($user, TRUE) . '</pre>');

menu_execute_active_handler();

```

I've copied over the whole site including database and files to my local machine, and I'm not experiencing this issue. There's should be some settings that does this on the live site.

**UPDATE 2**

I've noticed that on the live site we have a list of disabled functions that I'm not aware of. Maybe it will help somehow.

```
disable_functions = apache_child_terminate, apache_setenv, define_syslog_variables, escapeshellarg, escapeshellcmd, eval, exec, fp, fput, ftp_connect, ftp_exec, ftp_get, ftp_login, ftp_nb_fput, ftp_put, ftp_raw, ftp_rawlist, highlight_file, ini_alter, ini_get_all, ini_restore, inject_code, mysql_pconnect, passthru, php_uname, phpAds_remoteInfo, phpAds_XmlRpc, phpAds_xmlrpcDecode, phpAds_xmlrpcEncode, popen, posix_getpwuid, posix_kill, posix_mkfifo, posix_setpgid, posix_setsid, posix_setuid, posix_setuid, posix_uname, proc_close, proc_get_status, proc_nice, proc_open, proc_terminate, shell_exec, system, xmlrpc_entity_decode, parse_ini_file,show_source,shell_exec

```

# Answer
> 0 votes
The problem was caused by the Varnish on the server. Below is the settings for Varnish.

```
# Always cache the following file types for all users. This list of extensions
# appears twice, once here and again in vcl_fetch so make sure you edit both
# and keep them equal.

if (req.url ~ "(?i)\.(pdf|asc|dat|txt|doc|xls|ppt|tgz|csv|png|gif|jpeg|jpg|ico|swf|css|js)(\?.*)?$") {
  unset req.http.Cookie;
}

```

# Answer
> 1 votes
If you are using private file system every module can prevent you from downloading a file. It comes from file\_download\_header function:

```
function file_download_headers($uri) {
  // Let other modules provide headers and control access to the file.
  // module_invoke_all() uses array_merge_recursive() which merges header
  // values into a new array. To avoid that and allow modules to override
  // headers instead, use array_merge() to merge the returned arrays.
  $headers = array();
  foreach (module_implements('file_download') as $module) {
    $function = $module . '_file_download';
    $result = $function($uri);
    if ($result == -1) {
      // Throw away the headers received so far.
      $headers = array();
      break;
    }
    if (isset($result) && is_array($result)) {
      $headers = array_merge($headers, $result);
    }
  }
  return $headers;
}

```

So basically you should discover which implementation of hook\_file\_download returns -1. You can do that by printing (or writing into watchdog) value of `$function` variable inside `if ($result == -1) {` statement (so you will know that this function is responsible for giving -1 result).

However, there is also other case when you'll get access\_denied() - if none implementation of hook\_file\_download will return file headers.

So try to figure out **which** function (=\> module) prevents you from downloading file, then debug that function and try to deduct **why**.

---
Tags: webforms, files
---


# Question
Title: Does entity_save() trigger the update event?
Not quite sure if calling entity\_save() from code will trigger the update event or not.

So, does it?

# Answer
Assuming you're asking whether or not `entity_save()` invokes `hook_entity_update()`: no, it doesn't.

The controller class (or save callback function) for an entity type may well invoke it (for example `node_save()` does), but you can't rely on it for an entity type without checking the code first.
> 2 votes

---
Tags: 7, entities
---


title: cmis configuration alfresco cloud

text:
# Question
Title: cmis configuration alfresco cloud
I'd like to use the Alfresco Cloud ECM with my Drupal instance. I created an alfresco site. I installed and activated the CMIS module. Here is my configuration script:

```
$conf['cmis_repositories'] = array(
    'default' => array(
      'label' => 'cmis.alfresco.com',
      'user' => 'my_alfreso_cloud_username@example.de',
      'password' => 'my_alfreso_cloud_password',
      'url' => 'https://cmis.alfresco.com/cmisatom'
    ),
  );

```

I only find these lines to configure the module. Then I added a CMIS field to my content type. When I add a new node then there is an error:

> Notice: Undefined index: `cmis_field_rootFolderPath` in `cmis_field_field_widget_form()` (line 123 of D:\Inetpub\SK1913\sites\all\modules\cmis\cmis\_field\cmis\_field.module).

I cannot find any other configuration forms (beside the root path setting).

What am I doing wrong? Does this module work with the alfreso cloud solution? I don't want to install alfreson on my server until I know how to use it, or even **if** I use it...

# Answer
> 0 votes
I think there is one more configuration in setting.php for content type mapping with its fields.

In this example i have mapped article content type with cmis type.

```
$conf['cmis_sync_map'] = array(
 'article' => array(
     'enabled' => TRUE,
     'cmis_sync_cron_enabled' => TRUE,
     'cmis_folderPath' => '/Sites/New/Article',
     'full_sync_next_cron' => TRUE,
     'cmis_sync_nodeapi_enabled' => TRUE,
     'subfolders' => TRUE,
     'cmis_type' => 'alf:article',
     'content_field' => 'body',
   ),
);

$conf['cmis_sync_map']['article']['fields'] = array(
  array('drupal' => 'title', 'cmis' => 'cmis:name', 'drupal to cmis' => TRUE, 'cmis to drupal' => TRUE),
  array('drupal' => 'body', 'cmis' => 'cm:content', 'drupal to cmis' => TRUE, 'cmis to drupal' => TRUE),
  array('drupal' => 'field_object_id', 'cmis' => 'cmis:objectId', 'drupal to cmis' => TRUE, 'cmis to drupal' => TRUE),
);

```

I hope it will works for you.

---
Tags: 7
---


# Question
Title: Pass positional arguments to drush via drushrc.php?
drush allows you to pass default arguments in a drushrc.php-file like:

```
    $command_specific['command'] = array(
      'argument' => 'value',
      …
    );

```

This seems only to work for named options. Is there a way to also pass positional arguments via drushrc.php (like the installation-profile for drush site-install)?

I tried to use `$command_specific['site-install'][0] = 'profile';` but that didn't work.

# Answer
> 3 votes
Alas, there is no command-specific argument feature in Drush. You can't even use a pre-command hook to fill in the arguments, as Drush will check for required arguments before calling any command hooks.

Another option would be to define a shell alias, and define your argument there:

```
$options['shell-aliases']['myis'] = 'site-install xyzzy';

```

Then you can use this as `drush myis [other options]`, and your profile name will be inserted.

# Answer
> 0 votes
This shell alias works for me. This means that you can define a shell alias that sets default parameters (and options if you want) for an existing command:

```
$options['shell-aliases']['site-install'] = '--yes site-install xyzzy';

```

Developers would simply need to run `drush site-install`.

---
Tags: drush
---


title: Count Search Results

text:
# Question
Title: Count Search Results
I am trying to create a block to put on the search results page that has a list of the content types in the search results and the number of results for that content type.

Does anyone know how this can be achieved, if it can be?

So far I've tried hooking into `_preprocess_search_results` but that only works with the current page of the results.

Thanks for any help with this.

# Answer
Why aren't you using facets?

That's how blocks which list search results grouped according to a certain criteria are called and it's a built-in feature of Search API.

All you need to do is get Facet API, enable the integration module search\_api\_facetapi, enable the type field, set it up as a facet and enable the block.

That block then doesn't just list the content types, you can also click on it and the results are automatically limited to that type.
> 3 votes

# Answer
EDIT: Grrr. Never mind. I mispoke. It is per page :( But it was a fun exercise at least.

search works by running each of the results through search-result.tpl.php and then aggregating them in search-results.tpl.php, which then pages them out to you. So, in theory at least, you could put some intelligence inside search-result.tpl.php that counts node types and squirrels this information away somewhere to be displayed in a block on the search results page. (Obviously, copy these tpls, don't edit the ones in modules/search :)

For example, in Drupal 6 at least, if you created this function:

```
function _mymodule_search_count($op='display',$type=null) {
  static $counts=array();

  if ($op=='display') {
    return $counts;
  } else {
    if ($type) {
      $counts[$type]++;
    }
  }
}

```

and stuffed this in the top of search-result.tpl.php:

```
_mymodule_search_count('count',$info_split['type']);

```

and then this at the top of search-results.tpl.php:

```
$count=_mymodule_search_count('display');
drupal_set_message('<pre>' . print_r($count,true) . '</pre>');

```

you would see what I mean. It's up to you to put all of this in a block, but that's pretty simple :)
> 0 votes

# Answer
1. Add a preprocess hook
2. Copy search-results.tpl.php into your theme directory. You'll find the original in modules/search. Leave that intact and make a copy.
3. Print the result code in the template. Edit your copy of search-results.tpl.php to print the search result count wherever you want. I put mine right below the "Search results" header tag.

`<?php print $search_totals; ?>`

The preporocess hook is as follows:

```
function YOURTHEME_preprocess_search_results(&$vars) {

// search.module shows 10 items per page (this isn't customizable)

 $itemsPerPage = 10;

  // Determine which page is being viewed

  // If $_REQUEST['page'] is not set, we are on page 1

  $currentPage = isset($_REQUEST['page']) ? $_REQUEST['page']+1 : 1;

  // Get the total number of results from the global pager

 $total = isset($GLOBALS['pager_total_items'][0]) ? $GLOBALS['pager_total_items'][0] : 0;

  // Determine which results are being shown ("Showing results x through y")

 $start = $itemsPerPage * $currentPage - ($itemsPerPage - 1);

   // If on the last page, only go up to $total, not the total that COULD be

  // shown on the page. This prevents things like "Displaying 11-20 of 17".

  //$end = (($itemsPerPage * $currentPage) >= $total) ? $total : ($itemsPerPage * $currentPage);

  $end = $itemsPerPage * $currentPage;

 if ($end > $total){
    $end = $total;
  }

  // If there is more than one page of results:

if ($total > $itemsPerPage) {

    $vars['search_totals'] = t('Displaying !start - !end of !total results', array(
      '!start' => $start,
      '!end' => $end,
      '!total' => $total,
    ));
  }

else {
// Only one page of results, so make it simpler
 $vars['search_totals'] = t('Displaying !total !results_label', array(
      '!total' => $total,
      // Be smart about labels: show "result" for one, "results" for multiple
      '!results_label' => format_plural($total, 'result', 'results'),
    ));
  }

}

```
> 0 votes

---
Tags: 7, hooks, search
---


title: Use Optional Arguments in a Panels Path

text:
# Question
Title: Use Optional Arguments in a Panels Path
I am porting an existing custom form that takes optional arguments from the URL to preload some fields. I can not use the `?q=` method because I must maintain backwards compatibility. For example, both of these URLs are valid:

```
shop/barn
shop/barn/small/white/red/double/tin

```

The problem I am running into is how to setup this with Page Manager to accept an optional argument. If I set up my url to be:

```
shop/barn/%settings

```

and map %settings to a string, I can get it load the optional arguments! But ... `shop/barn` does not work. The only way I've figured out to resolve this so far is to create two pages with the exact same panel setup. I would really like to condense this down to one.

I have a feeling the answer lies in something to do with making a custom ctools arguments plugin as the author posted for Panel Pages and Taxonomy Term Arguments. I have tried modifying line 48 in the `simplecontext_arg.inc` in the `ctools_plugin_example` module with the following to accomplish this:

```
if (empty($arg)) {
  $arg[0] = '123';
  return ctools_context_create('simplecontext', $arg);
}

```

Unfortunately, this displays a blank panel when I visit `ctools_plugin_example` unlike visiting `ctools_plugin_example\123`.

This is being implemented on a Drupal Commerce site, so in a perfect world I would also like my panel pages to override the node/%node path with the optional argument so that I can more easily and consistently change the path of my product displays in the future instead of having to manually maintain a bunch of URLs.

I am also open to suggesting something other than Panel Pages, such as overriding the `node--barn.tpl.php` files.

# Answer
My final solution was to create a Page Panel with the following path:

```
shop/%product/!optionalArgs

```

`%` indicates a required argument, `!` indicates an optional argument

In order to grab all of the "arguments" or URL path after the `product` (ex: barn), go to `Settings » Arguments`, select `Settings` for `optionalArgs`, and make sure `Get all arguments after this one` is checked. Click `Finish`.

In order to use this with a Clean URL, the panel path needs to be some derivative of the Clean URL because panels does not have access to it. For more details, see `merlinofchaos`'s explanation in the following Panels Issue: Panels, Pathauto and Arguments

> Let's say I have a url. It can be any URL, but for this example it's "node/12".
>
> Let's say I have an alias and it's generated by pathauto, and it's something like video/type/12/this-is-the-title-of-the-video and it's aliased to "node/12"
>
> If I visit http://example.com/video/type/12/this-is-the-title-of-the-video then what Drupal thinks the URL was was, in fact, 'node/12'. Panels never has a chance to do anything with video/type/12/foo because that URL doesn't really exist.
>
> The reason, then, that adding some other piece to the URL makes it work is that aliases don't accept arguments. They must be exact. So the problem, in that case, is the alias itself is actually taking the page away from where you want it to go.
> 7 votes

# Answer
I ran into a similar scenario. I've seen a lot of questions, answers, and articles that recommend various methods of passing hierarchical or nested URL patterns into views arguments or contextual filters, but they were all too generic or didn't work for my situation, which I feel is a very common one.

I'm working with Drupal Commerce products and hierarchical taxonomy terms and I wanted URL structures like this:

**Taxonomy:**
`store/parent-category`
`store/parent-category/child-category`
`store/parent-category/child-category/grandchild-category`

**Product Display:**
`store/parent-category/child-category/grandchild-category/product-title`

In PathAuto I defined the following patterns:

**Product Display paths:**
`store/[node:field-product-display-category:parents:join-path]/[node:field-product-display-category:name]/[node:title]`

**Product Taxonomy paths:**
`store/[term:parents:join-path]/[term:name]`

The `field-product-display-category` mentioned in the token above is coming from a Term Reference field on my Product Display content type.

So a default taxonomy page would have the path `store/parent-category/child-category/grandchild-category`. Each one of those nested taxonomy pages needed to show all the products referenced by child terms. So `store/parent-category` would need to show all products belonging to `child-category` and `grandchild-category`.

I also needed the taxonomy names in the URL instead of the taxonomy term IDs. I created a view page with a `Content: Has taxonomy term ID (with depth)` contextual filter because I might have any number of possible nested taxonomies and I wanted the parent taxonomy to show all results for the child taxonomies.

I tried to use the contextual filter validation method of converting the term name in the url into its corresponding term id and replace spaces with dashes, but my category names have special characters like `/`, `&`, `+`, and `-`, which meant decoding the url didn't always match the original term name.

To get around this I created a custom views contextual filter validator, which could correctly parse the term name out of the url and figure out the corresponding term id by querying the `url_alias` table. After querying a particular path once, the result is cached for better performance.

To create the custom contextual filter validator I followed this example: http://www.joetsuihk.com/en/en/custom\_views\_argument\_validator\_views\_plugin\_argument\_validate

**The info file:**

```
name = Example Module
package = "Example"
description = Example Module custom views argument validator
core = 7.x

files[] = plugins/example_module_plugin_argument_validate_url.inc

```

**The module:**

```
/**
 * @file example_module/example_module.module
 * Implement hook_views_api - load up the custom views include files
 */
function example_module_views_api() {
  return array(
    'api' => 3.0,
    'path' => drupal_get_path('module', 'example_module'),
  );
}

```

**The views include file:**

```
/**
 * @file example_module/example_module.views.inc
 * Defines a custom contextual filter validator
 */
function example_module_views_plugins() {
  return array(
    'argument validator' => array(
      'taxonomy_url_alias' => array(
        'title' => t('Taxonomy URL Alias'),
        'handler' => 'example_module_plugin_argument_validate_url',
        'path' => drupal_get_path('module', 'example_module') . '/plugins',
      ),
    ),
  );
}

```

**The contextual filter handler:**

```
/**
 * @file example_module/plugins/example_module_plugin_argument_validate_url.inc
 * Contains the taxonomy url alias contextual filter validation plugin.
 */

/**
 * Validate whether an argument (contextual filter) is a valid
 * @ingroup views_argument_validate_plugins
 */
class example_module_plugin_argument_validate_url extends views_plugin_argument_validate {

  private $intAddUnixTime = 604800;
  private $error = FALSE;

  function validate_argument($argument) {
    $view = &$this->view;
    $handler = &$this->argument;

    if (!empty($view->args)) {
      //reconstruct the url from the views argument array
      $strPath = implode("/", $view->args);

      //get the taxonomy term id based on the url, not the term name
      $objAlias = $this->getTermId($strPath);

      //split the url_alias's source column up into an array.
      //the source column contains the term id at the end of a path like 'taxonomy/term/123'.
      $arrTermData = explode("/", $objAlias->source);
      $tid = end($arrTermData);
      $term = taxonomy_term_load($tid);

      //manually assign the term id to be the view's argument
      $handler->argument = $term->tid;
      return true;
    }
    else {
      return false;
    }
  }

  /**
   * Get the taxonomy term id from either the url_alias table or from persistent cache
   * @param string $strPath like 'parent-category/child-category/grandchild-category'
   * @return object containing the result of the url_alias table or persistent cache lookup
   */
  private function getTermId($strPath) {
    $objReturn = NULL;
    //attempt to get the taxonomy term id from cached url_alias table result object
    $objReturn = $this->getCache($strPath);

    //if cache is not set, do a select query
    if ($objReturn == NULL) {
      try {
        if(!$this->error) {
          $objReturn = $this->_dbSelect($strPath);
          //cache the response
          $this->setCache($strPath, $objReturn);
        }
        else {
          //log some error because $this->error was true
        }
      }
      catch (Exception $ex) {
        $this->error = TRUE;
        //log an exception
      }
    }

    return $objReturn;
  }

  /**
   * Run a query to look up the taxonomy term id based on the url alias path
   * @param string $strPath url alias like 'parent-category/child-category/grandchild-category'
   * @return object results of the query
   */
  private function _dbSelect($strPath) {
    $result = NULL;
    try {
      //The alias stored in the url_alias table is going to be prepended with 'store/' because of my pathauto taxonomy pattern
      $result = db_select("url_alias", "ua")
        ->fields('ua', array('pid','source','alias'))
        ->condition('alias', 'store/'.$strPath, '=')
        ->condition('source', 'taxonomy/term%', 'LIKE')
        ->range(0,1)
        ->execute()
        ->fetchObject();
    }
    catch(Exception $ex) {
      //log an exception
    }

    //$result is an object like:
    //$result->pid //'12345'
    //$result->source //'taxonomy/term/123'
    //$result->alias //'store/parent-category/child-category/grandchild-category'
    //$result->uid //1
    return $result;
  }

   /**
   * Get an object from cache
   * @param  string $strPath used as part of the cache id
   * 'cache_taxonomy_url_alias' is a custom cache bin
   * @return object data from the persistent cache
   */
  private function getCache($strPath) {
    $objCache = cache_get('example_module_plugin_argument_validate_url' . '::' . 'store/'.$strPath, 'cache_taxonomy_url_alias');
    if (isset($objCache->data)) {
      return $objCache->data;
    }
    else {
      return NULL;
    }
  }

  /**
   * Store an object in cache
   * @param  string $strPath used as part of the cache id
   * @param  object $objData contains the url alias table results
   * @return void
   */
  private function setCache($strPath, $objData) {
    cache_set('example_module_plugin_argument_validate_url' . '::' . 'store/'.$strPath, $objData, 'cache_taxonomy_url_alias', time() + $this->intAddUnixTime);
  }
}

```

After that I selected my custom contextual filter validator:

The next issue I ran into was that my views path was the same as my taxonomy pattern. I visited `store/parent-category/child-category` and expected the view to handle the display, but instead it went to the default taxonomy page. Worst of all, it didn't display any products as belonging to the `child-category` because the products actually belong to the `grandchild-category` taxonomy nested underneath it. I was seeing the 'There is currently no content classified with this term' message.

To overcome this, I just gave my view a different path like `store-view/%`.

This still doesn't satisfy my needs because I really need the view to be displayed with other blocks on a panel. To solve this I created a content pane display type on the view to be embedded in a panel page.

I set up the pane settings to use the panel path:

And to use the first panel argument as the view's argument data source:

Then for the content pane's contextual filter validation, I selected the custom *Taxonomy URL Alias* validator:

Then tell it to link to the other view's *Categories Page* display that I created earlier, which is also using the *Taxonomy URL Alias* validator:

Then I created a panel page with a different path to contain the views content pane I just created:

I configured the argument to be a String instead of a Taxonomy Term ID

In the argument settings, select *Get all arguments after this one* because I needed to send the whole path `parent-category/child-category/grandchild-category` into the view content pane, not just the first argument `parent-category`:

That's it, now navigating to 'panel-page/parent-category/child-category' looks up the term id for 'child-category' and displays all the products belonging to the 'child-category' and 'grandchild category', since the contextual filter is configured for a term id (with depth).
> 1 votes

---
Tags: commerce, chaos-tool-suite
---


# Question
Title: How to apply Panels layouts for CiviCRM pages
For CiviCRM pages Events and Contributions that has paths of e.g.

```
www.site.com/civicrm/contribute/transact?reset=1&id=1
www.site.com/civicrm/event/register?id=23&reset=1

```

And so on.

Problem is that you need to copy paste custom .php files and folders in themes dir for each form to apply custom styling, e.g. have right side and left side columns and display custom content. E.g. left side column texts and infos, descriptions and right side column contains the registration form/payments.

I can't figure out how to do that without copying multiple folders for each form and editing it each time to match the page ID.

I'm looking at the Panels and it doesn't have CiviCRM content as nodes content type to be applied and filtered out in the panels variant and etc.

Or not possible?

# Answer
> 0 votes
Might also be worth your while taking a look at the CiviCRM Entity module (https://www.drupal.org/project/civicrm\_entity). Not straightforward to use but might get you at least some of the way. I think Webform and webform\_civicrm modules might be the way to go for standard contributions.

# Answer
> 1 votes
Most CiviCRM forms can be accessed with the Webform CiviCRM Integration module: https://www.drupal.org/project/webform\_civicrm

Though the integration currently only handles on-site payment methods for contribution forms.

You can build a webform using fields from the CiviCRM form and then use panels to arrange the page, or use Webform Layout module (https://www.drupal.org/project/webform\_layout) to arrange the form elements

---
Tags: 7, theming, panels, display-suite, civicrm
---


title: user/logout access denied v7.34

text:
# Question
Title: user/logout access denied v7.34
Admin or normal user can not logout using `www.myswebsite.com/user/logout`

*An access denied* page is displayed and the user is still logged.

using `?q=user/logout` works.

It is not a rewrite problem, all other url are ok.

I have cleared the cache and deleted the cookies, tried on FF, IE & Chrome.

Any idea to investigate ?

# Answer
> 0 votes
I have found the root cause. The Geocaching. I am in Australia and the server is in France. The missing of /user/logout into the apache log warns me. I have tested with a french proxy and everything is ok.

My provider offers Geocaching, the page looks to be cached.

I have purge the geocache and /user/logout works!!

The first hit of a 403 for /user/logout triggers the same problem. This is easy to understand, when user/logout is success, the answer is a 302, nothing is added into the cache whereas a 403 is permanent so it is stored.

This explains why ?q=user/logout works, it is a query no caching is done.

**To summarize deactivate the geocaching.**

# Answer
> 0 votes
Try different way

1. This works for me if I substitute the logged-in username for 'user', like this:

http://my\_site/my\_user/logout

ie:

http://example.com/jdoe/logout

2. this might be problem with not enabling clean url in your site go to

http://example.com/admin/config/search/clean-urls

enable clean url and check if its working

3. as you mentioned use http://example.com/user/logout will logout the current user section

Further readings: logout problem - https://www.drupal.org/node/1572984

enabling clean url - https://www.drupal.org/node/1572984

access denied + logout - https://www.drupal.org/node/2192401

---
Tags: users, uri
---


# Question
Title: Rebuild permissions needed after installation from profile
Once solved this issue: How to define settings from an install profile

I would like to skip the Error Message I get on first load of the application:

```
Message d'erreur
Les permissions d'accès au contenu doivent être reconstruites. Reconstruire les permissions.

```

To do so, I've created a task to perform the function node\_access\_rebuild(FALSE);

```
function genius_install_tasks(&$install_state) {
  $tasks['genius_settings'] = array(
      'display' => FALSE,
      'type' => 'batch',
      'run' => INSTALL_TASK_RUN_IF_NOT_COMPLETED,
  );

  $tasks['link_taxonomy_menu'] = array(
      'display' => FALSE,
      'type' => 'batch',
      'run' => INSTALL_TASK_RUN_IF_NOT_COMPLETED,
  );

  $tasks['rebuild_permissions'] = array(
      'display' => FALSE,
      'type' => 'batch',
      'run' => INSTALL_TASK_RUN_IF_NOT_COMPLETED,
  );

  return $tasks;

}

```

But it seems to don't be enough.In fact, I set a message that I can't see, so I think this task maybe is not being perform.

```
function rebuild_permissions() {
    // Rebuild permissions
    node_access_rebuild(FALSE);
    // This message is set at the end of the node_access_rebuild
    // Keep here to ensure this task has been made
    drupal_set_message(t('Content permissions have been rebuilt.'));

}

```

I am going to try to change the type of the task to normal. **EDIT: This change doesn't solve the problem**

Mindwhile, appreciate reader, do you have any advice to do the rebuild permissions at the end of the installation correctly?

Thanks for the reading.

# Answer
Finally it seems as it is done from the hook\_install.
> 0 votes

---
Tags: installation-profiles
---


# Question
Title: Where are templates from hook_theme stored in the database
I have a module, called "bundles", there I created a file "attached\_email.tpl.php" and a hook\_theme:

```
function bundles_theme($existing, $type, $theme, $path)
{
    $path = drupal_get_path('module', 'bundles');

    return array(
        'attached_email' => array(
            'template' => 'attached_email',
            'path' => $path,
            ),
        );
}

```

I have 2 databases for this website: lwt (default) and lwt\_test (for test data). I have written the template, cleared caches and imported test data into lwt\_test DB. But the template is unavailable there. When I call:

```
theme('attached_email', $data);

```

From lwt database, it gives the output. But when I switch to lwt\_test:

```
db_set_active('lwt_test');

```

nothing is given. I can only conclude, that there is some piece of data, stored in lwt database, missing in lwt\_test database. And that's why Drupal doesn't see my new template.

**Update**

When I use this code:

```
print theme('attached_email');
db_set_active('lwt_test');
send_attached_emails($bundle_id, $users);
db_set_active();

```

It gives the correct result (probably the template is cached after the 1-st call).

# Answer
> 2 votes
Normally, `db_set_active()` is used to query external data. I have never heard about it being used to switch between two full Drupal databases from within the same active codebase / website.

I suspect one or two things is happening: you are having cache problems and/or you are having registry problems.

When you clear caches via the UI or drush, the full registry gets rebuilt, which includes theme functions and their template files. That information will get stored in whatever database is active at the time.

If you switch databases, the cache and registry will be pulled from the newly active database. In addition, any new cache entries will be written to the new database.

So, I think your problem is that the wrong cache and/or the wrong registry is being queried when you use the Drupal API and you are getting stale data.

The proper way to accomplish this is to set up a dev/staging/live environment, where code goes forward from dev -\> staging -\> live, and databases go backwards from live -\> staging -\> dev. There are lots of articles on the net, and a few questions here, about how to do this.

---
Tags: theming, database
---


# Question
Title: Search keyword with selectable exposed filters
I'm trying to make a search view with one textfields and two checkbox filters (body, tags). The search text would only search the selected fields and would show results as summaries.

I've tried combined fields filters in Views, but the filters selected are all enabled. Is there was a way to toggle the filters via checkbox?

# Answer
I think this is the module that you are looking for....

Better Exposed Filters

> The Better Exposed Filters module replaces the Views' default single- or multi-select boxes with radio buttons or checkboxes, respectively. Description fields and Select All/None links can be added to exposed filters to make for a better user experience.
>
> Views Filters is a powerful tool to refine the results returned by a given view. When you expose a filter, you allow the user to interact with the view making it easy to build a customized, advanced search. For example, exposing the node type field as a filter lets your site visitor limit their search queries to just blog entries. Better Exposed Filters gives you greater control over the rendering of exposed filters.
>
> Why use this module? Because it provides a better user experience than the default option. Try telling a client that they should click on an option, then scroll to the next option and ctrl+click on it. Don't just click 'cause you'll lose your first selection. Oh, and ctrl+click again to unselect an option... Yeah, not user friendly.
> 0 votes

---
Tags: 7, views, forms
---


# Question
Title: local language variables to use in code for queries(NOT GLOBAL LANGUAGE)
I'm building a site in multiple languages (Italian and English) and I would like to ask you to intervene on the code to add selections 'if' to my queries to the user's local language. At first I place conditions using as a reference global $ language but I understand that it is wrong as it does for the whole site and not a single user. I saw on the internet that you can use sessions but how do they do? I would also switch to change languages. I have no idea how to do. I went in configurations -\> REGIONAL AND LANGUAGE -\> languages -\> detection and selection .. here that I have to give exactly? How should I do help me please!

# Answer
> 1 votes
If the user is logged in, you can the global `$user` variable. The language object is then `$user->language`. For an anonymous user, you can use a session variable or a cookie. There's a module to use cookies: Language Cookie

To use a session variable: On the "Detection and Selection" configuration page, set "Session" as the first detection method. To set up the variable, click the "Configure" link on that page. You should see

Then you just need links to set the user's language. Something like

`http://yoursite.com/?language=en` and `http://yoursite.com/it?language=it` at the top of the page.

---
Tags: i18n-l10n
---


# Question
Title: How to have search results from a views defined block display on page?
I have created a custom search block with Views 3 in Drupal 7. I would like the results of that search be displayed in a page (like the default drupal search block) and not in the block itself (which seems to be the default behaviour for views). How do I accomplish this? I think I am missing a setting somewhere but can't find it.

# Answer
This is from a project I worked on a while ago. It uses Search Api and has a full search page at product-search/% (a Search Api view). After the redirect in the block's form submit, it places the search term into the search box text field for the search page. It's not a direct answer to your question as you will have to adapt the code if you want to use it.

```
function MODULE_block_info() {
  $blocks = array();
  $blocks['product_search'] = array(
    'info' => 'Search Products',
    'cache' => DRUPAL_CACHE_GLOBAL,
  );
  return $blocks;
}

function MODULE_block_view($delta) {
  $block =  array();
  switch($delta) {
    case 'product_search':
      $block['subject'] = t('Search Products');
      $block['content'] = drupal_get_form('MODULE_search_products_form');
      break;
  }
  return $block;
}

function MODULE_search_products_form($form, &$form_state) {
  $form['search'] = array(
    '#type' => 'textfield',
    '#title' => t('Terms to search for'),
    '#size' => 28,
    '#maxlength' => 128,
    '#required' => TRUE,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Search'));

  return $form;
}

function MODULE_search_products_form_submit($form, &$form_state) {
  drupal_goto('product-search/' . $form_state['values']['search']);
}

function MODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'views_exposed_form':
      if ($form_state['view']->name=='product_search_api_view' && $form_state['view']->current_display=='page') {
        // get the view argument if defined
        if (isset($form_state['view']->args[0])) {
          // Set form filter input value to term tid
          if (!isset($form_state['input']['search_api_views_fulltext']))
            $form_state['input']['search_api_views_fulltext'] = $form_state['view']->args[0];
        }
      }
      break;
  }
}

```
> 0 votes

---
Tags: 7, views, search
---


# Question
Title: Which module should I use to visualize my Google Analytics Data using the Google Charts engine?
I would like to import Google Analytics data of my site into my site, so that I can visualize them with the (interactive) Google Charts API.

Which module(s) should I use for this?

# Answer
> 3 votes
Seems to me that Google Analytics Reports is the solution for this, no? Those "reports" do include charts also (not just tabular data).

If you rather want to create some charts yourself, consider the Comparison of Charting Modules as a possible place to do start from, to find the module that best fits your needs. Possible alternatives that might work for this specific question are the Chart module, or the Charts module, though there are other alternatives in that comparison that might be a better fit for this case.

The **license** that comes with the related charting library (engine) in each of these modules, should be considered also. It is one of the (important?) selection criteria for deciding on the module to go for. 'Possible privacy concerns' or 'Yes or no support for saving charts in PDFs' is another typical item to consider.

Disclosure: I'm the author of the comparison and modules Chart and Charts,
I hope this does not violate the site's policy on self-promotion.

# Answer
> 2 votes
I think I found this solution on those 3 articles: http://blog.amazeelabs.com/en/create-ultimate-google-analytics-dashboard-drupal-part-1 http://blog.amazeelabs.com/en/create-ultimate-google-analytics-dashboard-drupal-part-2 http://blog.amazeelabs.com/en/comment/257249

i hope this helps someone.

---
Tags: 7, google-analytics, charts
---


title: Tab Tamer - Hiding tabs based on Roles

text:
# Question
Title: Tab Tamer - Hiding tabs based on Roles
Tab Tamer Module only does but so much. I want to hide a tab for anonymous users and have it active for other admin users. This just turns it off completely. Any ideas?

# Answer
> 1 votes
I added this code. Not sure if it does the trick. I need to set a hide based on permissions correct?

```
/**
 * Implementation of hook_menu_alter().
 * Remember to clear the menu cache after adding/editing this function.
 */
function MODULENAME_menu_alter(&$items) {
  // Removing certain local navigation tabs that are either undesired or need to be custom relocated.

  // Set these tabs to MENU_CALLBACK, so they still register the path, but just don't show the tab:
  $items['node/%node/track']['type'] = MENU_CALLBACK;
  $items['user/%user/track']['type'] = MENU_CALLBACK;
  $items['search/user/%menu_tail']['type'] = MENU_CALLBACK;

  // Fully unset these tabs and their paths, don't want them at all. This breaks the path as well:
  unset($items['user/%user/example']);
}

```

# Answer
> 0 votes
If the tab is on a path, then use `hook_menu_alter` to adjust the permissions via `access_callback`. Hide the tab for anonymous, then call into the access callback that was originally set for all other users.

Otherwise do it at the theming layer (but your path is still available which is not good).

Tab Tamer uses hook\_menu\_alter to set the `type` of the menu to `MENU_CALLBACK`, which just hides it. You can easily expand on that by doing that conditionally on User Role. If you implement your own module make sure it is called after Tab Tamer.

This litte bit of code in Tab Tamer does the hiding:

```
if ($val['action'] == 'hidden') {
   $items[$val['tabtamer_original_path']]['type'] = MENU_CALLBACK;
}

```

You need to change it to something like this:

```
if ($val['action'] == 'hidden' && user_is_anonymous()) {
   $items[$val['tabtamer_original_path']]['type'] = MENU_CALLBACK;
}

```

---
Tags: routes
---


title: How can I modify the 'has_js' cookie?

text:
# Question
Title: How can I modify the 'has_js' cookie?
I am trying to modify the 'has\_js' cookie that is set by Drupal. I need to modify this cookie so it becomes both Http-only and secure in response to a site security review.

I attempted to add the following to the html.tpl.php file so the cookie would be modified before any output was rendered:

```
setcookie('has_js',null,null,null,null,true,true);
setrawcookie('has_js',null,null,null,null,true,true);

```

This gave me 2 has\_js cookies, one with the desired modifications and one without.

I next attempted to grab the value from the original has\_js cookie and then destroy it and replace it:

```
if(isset($_COOKIE['has_js']))
{
  $has = $_COOKIE['has_js']; //save cookie's value (i.e., '1')
  unset($_COOKIE['has_js']);
  setcookie('has_js','',time()-3600); //destroy old cookie
  setcookie('has_js',$has,null,null,null,true,true);
  setrawcookie('has_js',$has,null,null,null,true,true);
}
else
{
  print_r("Not set");
}

```

This demonstrates (by the output I get) that at the start of html.tpl.php, the cookie isn't set -- which might explain why there are 2 cookies (perhaps I was creating a has\_js cookie at one point in time and after that Drupal creates its own). Confusingly, if I simply do

```
print_r($_COOKIE);

```

at the same place in the file, 'has\_js' cookie does show up with an assigned value of 1.

So my question is:

How can I find out when Drupal is setting this 'has\_js' cookie and how can I add these attributes to it?

# Answer
I am answering this formally so other people can see one possible solution that will work if they have this same question, but the answer is actually found in the comment by @thumbson above: in order to modify the cookie, I did indeed find success in creating a custom js file that ran when every page loads.
> 0 votes

---
Tags: cookies
---


# Question
Title: What all is required to completely uninstall Webform?
After disabling and uninstalling Webform, I noticed that it appears to still be active. Existing Webform content are all still there and accessible. Apparently this is intended behavior.

I can delete the content and content type, but I'm worried there might be other items or residue that is not as apparent. **What all do I need to do in order to completely remove all Webform stuff from the site?**

# Answer
Like I said you need to uninstall it from `/modules` UI and then delete its folder from `/site/all/modules`.

If you take a look at webform module source code, in `webform.install` under `function webform_uninstall()` you will find this code:

```
foreach (node_type_get_names() as $type => $name) {
    variable_del('webform_node_' . $type);
}

```

as you can see it deletes every node which has webform type. for more details of what is going to be deleted after uninstalling the module, check the `function webform_install()` and `function webform_uninstall()` functions in the mentioned file.
> 1 votes

---
Tags: 7, webforms, installation
---


title: Add extra fields to a node display

text:
# Question
Title: Add extra fields to a node display
I want to add extra fields when a node is displayed, the data of this fields are fetched from an external db.

I'm uncertain if I've to use the `hook_node_view_alter` function or `hook_node_view`.

# Answer
> 1 votes
I don't understand if the extra fields to add are in the node form or into the page(display of node). If it's the first thing I think you can use hook\_form\_alter to add the extra fields and in the second case you can use hook\_preprocess\_node to add the variables to 'send' to the front-end of site.

# Answer
> 0 votes
You could use hook\_preprocess\_node and add variables that you could use in a node template.

---
Tags: 7, nodes
---


title: HTML img code does not work?

text:
# Question
Title: HTML img code does not work?
I'm using Drupal7 with CK editör.

When I add html code for an image (`<img src="..."`) I can see it on the editing page; but when I save it, I can't see anything on the page.

How can I solv it?

# Answer
Check your text formats (Admin \> Configuration \> Content Authoring \> Text formats) and make sure the one you're selecting for your node isn't filtering out the img tag.
> 1 votes

---
Tags: media, wysiwyg, theming
---


# Question
Title: Sending Auto-filled Email from Content Type Profiles
I have 'resource' content types. There are hundreds. I want each profile to contain an individualized link to a 'feedback form', or some mechanism to report an error with the profile, by email...to our staff. These items are coming from the DB, obviously. So something like the following:

Resource Name Type Description \[LINK to submit problem about this profile\] more details here

When the user clicks the link (in my imagination) they would either be able to send an email to someone on our staff with details auto-filled about the resource they are complaining about, OR, it takes them to a feedback form of some type with details auto-filled about the resource they are complaining about. Either way it auto-fills form fields and allows the sending of email.

Anyone know of a good module or technique for handling this?

# Answer
> 1 votes
I use Webform for this kind of thing, as long as the values being passed to the form aren't too extensive.

On the Resource page template, create links to the webform, with field values in the the URL.

Webform 4 can then use tokens to place those values from the URL into fields.

You can then use Webform Rules to send an email.

The same thing can be accomplished with Entity Form, Entity Reference, Prepopulate, and Rules.

---
Tags: forms, nodes, emails
---


# Question
Title: What is the syntax for setting 404 fast paths on all Drupal pages in D7 > 7.9
D7.9 introduced 404 fast paths which don't fully bootstrap drupal on 404's for certain file types if it's enabled, thus saving some bandwidth / computation. More info is available here: http://drupal.org/node/1296384

By default this excludes only certain file types such as .jpg, .txt., etc., looks like this:

```
$conf['404_fast_paths_exclude'] = '/\/(?:styles)\//';
$conf['404_fast_paths'] = '/\.(?:txt|png|gif|jpeg|css|js|ico|swf|flv|cgi|bat|pl|dll|exe|asp)$/i';

```

I want to use this for all paths. Are there any repercussions to that?

I tried changing it to

```
$conf['404_fast_paths'] = '/*$/i';

```

However, this returns a warning:

> Warning: preg\_match() Compilation failed: nothing to repeat at offset 0 in drupal\_fast\_404() (line 2484 of /cms/main/includes/bootstrap.inc).

So what should the syntax look like up there to both work and not generate a warning?

Alternatively, if there isn't a solution to this specific question, is there a way I can speed up 404's for all Drupal pages, would it better to use the Fast 404 contributed module for instance?

# Answer
You used `"/*$/i"` as regular expression, but there is nothing before the asterisk; in other words, you are not saying what can be repeated zero or more times. Valid regular expressions expressions such as `"/.*/i"`, `"/[a-zA-Z]*/i"`, `"/(foo|bar)*/i"`.

drupal\_fast\_404() is called by drupal\_deliver\_html\_page() when the result of menu\_execute\_active\_handler() is `MENU_NOT_FOUND`, which means Drupal is asked to look for a path without any menu callback associated. `drupal_fast_404()` first checks that `$_GET['q']` doesn't match the regular expression contained in the "404\_fast\_paths\_exclude" Drupal variable; if it doesn't match that regular expression, then it checks `$_GET['q']` matches the regular expression contained in the "404\_fast\_paths" Drupal variable. The default value for that variable is `'/\.(?:txt|png|gif|jpe?g|css|js|ico|swf|flv|cgi|bat|pl|dll|exe|asp)$/i'` which means the fast 404 page is returned when the request is for a file with the following extensions:

* .txt
* .png, .gif, .jpg, .jpeg
* .css, .js
* .ico, .swf, .flv
* .cgi, .bat, .pl, .dll, .exe, .asp

If you want the fast 404 pages be used in any case, I would not touch the value of the "404\_fast\_paths\_exclude" Drupal variable, and change the content of the "404\_fast\_paths" Drupal variable to `'/.*/i'`, which would match any path that causes a 404 error, excluding the ones containing "styles."
> 5 votes

# Answer
To exclude additional paths, this seems to work:

```
$conf['404_fast_paths_exclude'] = '/\/(?:styles)\/|robots\.txt|(?:another-dir)\//';

```

where 'another-dir' can be the child of a longer path (as is styles).
> 2 votes

---
Tags: performance
---


# Question
Title: How to attach a view display switch to a view?
I am wondering how I can attach a switch/ link from one view display to another view display within the same view. I can only think of messing around in the template files and hardcoding this navigation.

What is the best solution/ is there a better solution for that?

Update: both displays shall have a own url this for caching and possibility to link to a specific display.

```
myview/(default: display-table)
myview/display-table
myview/display-list

```

# Answer
> -1 votes
I actually found a good solution for this problem using the built-in menu system, providing menu links to these view pages and attaching the menu to the view using context module.

This works even better with Icon API

# Answer
> 3 votes
### Display Suite

A possible solution to this is probably utilizing display suite.

You could trigger a link using display suite & display suite extras to open different view mode. The drawback to this is that the user would have to load a different page.

### Quicktabs

Another solution would be to load the two views as blocks and use quicktabs to display the two views in that tab format you require. The drawback to this solution is that you have two views loaded.

### Views Header

At the top of your views, just add a header anchor to your other views page. This solution is best if you just have one view where this output is being displayed. Otherwise, it would be difficult to maintain duplicate views.

# Answer
> 3 votes
There is the View modes module which does exactly what you need. However there is only a development version available.

If you prefer to avoid installing modules for small tweaks like this, you might want to create a simple switch in the views header.

You can do that either by adding a text area to the header of the view (notice this will require the PHP text filter to work properly), alternatively you can implement `hook_views_pre_view` to attach a header dynamically (-\> better option).

For the link to retain page and filter values you will have to use the `l()` function along with `drupal_get_query_parameters()`.

Take a look at the blog post I wrote for more details.

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


title: Fivestar Field Not Showing

text:
# Question
Title: Fivestar Field Not Showing
I've enabled Fivestar and added it to the comments field and made sure its in the comment display as well.

I've allowed anonymous and other users the ability to use Fivestar in Permissions. I've changed comments permissions so users can leave them and see their own.

I've created a new content piece and flushed caches to check if it only provides the field on NEW items.

In firebug on FF it says the rating field is in there but for some reason it's not showing up on the screen. Here's the code from Firebug:

```
<div id="edit-field-rating" class="field-type-fivestar field-name-field-rating field-widget-exposed form-wrapper"></div>

```

Any idea what might be going on here or ways to fix it?

# Answer
it'll will work if you change the Widget type on the Comment Fields tab to "Stars (rated while editing)". Give it a try.
> 2 votes

---
Tags: nodes, rating
---


# Question
Title: In Views, how to allow users to toggle between a grid and list?
I have a view that returns a 4 column grid view. The client wants to be able to toggle between grid results and teaser results by clicking on an icon.

Does Views handle this naturally? Do I need to utilize AJAX?

# Answer
This Views mode module should be able to do this, however it is still in development version. Make sure to test it out on a development site before using it on a production site

> A Drupal Views display plugin which provides alternate display modes that can be switched to for a single View. This allows exposed filter parameters or contextual filters to be kept active while switching display mode.
> 1 votes

# Answer
If you want to do something like this,

then you can use QuickTabs Module

So, here user can switch from TAB-ONE to TAB-TWO .. so on ..

To implement this, first you have to create View-Blocks and then you have to create Quick Tabs by using QuickTabs Module

Here is one Video Tutorial to create QuickTabs.
> 2 votes

# Answer
You can also create two views, one displays as a list and the other display as a grid. Each has its own url. As an example: View a list and a grid of music artist: 1 list view of artists, display as list, url=/music/artist&display=list 2 grid view of artists, displays as grid, url=/music/artist&display=grid

on both pages, create a header, Global: text area: and enter something like:

```
<a href="/music/artists&display=list" title="Show as list"><i class="fa fa-list"></i></a>  <a href="/music/artists&display=grid" title="Show as grid"><i class="fa fa-th"></i></a>

```

PS i use fontawesome for icons.

This way you can have two pages, same content present in its own way, using a switch on top of both pages. Easy!
> 1 votes

# Answer
Studio Orange's answer is a good lightweight solution, though I'd like to add a couple of points to improve upon it (cannot post comments yet).

To make the view retain filters and page number while switching displays, you need some PHP and as using the PHP filter in the text area of the view is not too good of a practice, it's preferable to attach a header programmatically by implementing hook\_views\_pre\_view().

For the link to retain page and filter values you will have to use the l() function along with drupal\_get\_query\_parameters().

Take a look at the blog post I wrote for more details.
> 1 votes

---
Tags: 7, views
---


# Question
Title: Custom ckeditor.styles.js file with WYSIWYG module
I am trying to customize the "Font style" dropdown in CKeditor through the WYSIWYG module, but I see no way to specify a path for ckeditor.styles.js in the wysiwyg module's profile editor.

Refer to this post for futher information - it says there should be a way to specify a location for that file.

# Answer
These are 2 ways (there are certainly more) to add custom ckeditor stylesets using the drupal wyswiwyg module.

1. Using the contributed module Ckeditor Styles
2. Using hook\_wysiwyg\_editor\_settings\_alter as follows:

(code "inspired" by ckeditor\_styles module)

In a custom module add the hook\_wysiwyg\_editor\_settings\_alter implementation:

```
/**
 * Implements hook_wysiwyg_editor_settings_alter().
 *
 * @param type $settings
 * @param type $context
 */
function MYCUSTOMMODULE_wysiwyg_editor_settings_alter(&$settings, $context) {
  // We only add the settings to ckeditor wysiwyg profiles.
  if ($context['profile']->editor == 'ckeditor') {
    $format = $context['profile']->format;
    $path = drupal_get_path('module', 'MYCUSTOMMODULE') . '/js';
    $settings['stylesSet'] = "mycustomstyleset:/$path/ckeditor_styles.js";
  }
}

```

and add a file named ckeditor\_styles.js in a sub directory js of the custom module:

```
CKEDITOR.stylesSet.add('mycustomstyleset',
  [
    { name : 'Red', element : 'span', styles : {'color' : 'red' } },
    { name : 'CSS Style', element : 'span', attributes: { 'class' : 'my_style' } },
    { name : 'Marker: Yellow', element : 'span', styles : { 'background-color' : 'Yellow' } },
    { name : 'Heading 4' , element : 'h4' },
    { name : 'Blue Button', element : 'div', attributes : { 'class' : 'blue-button' } },
  ]);

```
> 5 votes

# Answer
I do this for my Drupal sites all the time! @marblegravy's answer is a first step, but you may also want to do things like add a corresponding css rules to your CKEditor, so that when your editor is applying one of your custom styles, the editor actually applies them and the editor can preview the changes, without having to save!

I recently wrote a very detailed blog post about all the moving parts here: http://drupalwoo.com/content/how-customize-ckeditor-drupal-7-site

What I cover in the tutorial is

1. How to customize the toolbar
2. Creating the custom ckeditor.styles.js file. Here's a sample:

```
 CKEDITOR.addStylesSet( 'drupal',
 [
 /* Block Styles */
 { name : 'Heading 2'        , element : 'h2' },
 { name : 'Heading 3'        , element : 'h3' },
 { name : 'Heading 4'        , element : 'h4' },
 { name : 'Paragraph'        , element : 'p' },
 { name : 'Blue Image Button',
 element : 'div',
 attributes : {
 'class' : 'blue-image-button' }
 },

 /* Inline Styles */
 { name : 'Inline Quotation'    , element : 'q' },
  ...

```
3. Configuring your CKEditor so it knows where to find this custom styles file
4. Implementing the corresponding css to these styles, and letting CKEditor know about these too!

5. How to use the setup as an editor!

Hope it's helpful! Let us know if you get this working!
> 4 votes

# Answer
I just wrote a tiny custom module. I'm using the Wysiwyg module (rather than the CKEditor module). This then enables styles from ckeditor.styles.js in my theme to be loaded.

```
/**
 * Implements hook_wysiwyg_editor_settings_alter().
 */
function MYMODULE_wysiwyg_editor_settings_alter(&$settings, $context) {
  if ($context['profile']->editor == 'ckeditor') {
    $path = drupal_get_path('theme', 'THEMENAME');
    $settings['stylesSet'] = "drupal:/$path/ckeditor.styles.js";
  }
}

```
> 3 votes

# Answer
You can define styles in the WYSIWYG profile settings (admin/config/content/wysiwyg, edit the desired profile).

"CSS" tab \> "CSS classes"

> Optionally define CSS classes for the "Font style" dropdown list.
>
> Enter one class on each line in the format: \[label\]=\[element\].\[class\]. Example: Title=h1.title
>
> If left blank, CSS classes are automatically imported from loaded stylesheet(s). Uses the stylesSet setting internally.
> 0 votes

# Answer
Just put your overridden **ckeditor.styles.js** file in the root of your theme, then go to **/admin/config/content/ckeditor/edit/**, then for each of your profiles, **edit** them and open up the **css** fieldset, find the **Predefined Styles** field and choose **Use theme ckeditor.styles.js**.

From the **Predefined Style*\*s field help:

> Define the location of the ckeditor.styles.js file. It is used by the Style drop-down list available in the default toolbar. Copy the sites/all/modules/contrib/ckeditor/ckeditor.styles.js file into your theme directory (themes/seven/ckeditor.styles.js) and adjust it to your needs.
> -1 votes

---
Tags: theming, wysiwyg
---


title: Wysiwyg Permissions for Anonymous Users

text:
# Question
Title: Wysiwyg Permissions for Anonymous Users
I've installed WYSIWYG for my site editors, but it's also showing up in the comments field box. I don't want my anonymous users to be able to leave comments with the WYSIWYG (but I do want them to comment, with restrictions of course).

I tried looking in People \> Permissions and found nothing. I looked through the settings also in Config \> WYSIWYG and finally Modules \> WYSIWYG.

Anyone know of a way to edit the WYSIWYG permissions?

# Answer
> 1 votes
Sage, edit the content type, go on the COMMENTS FIELDS tab, then click on edit on comment\_body. Make sure you set 'Text processing' to PLAIN TEXT

---
Tags: wysiwyg
---


# Question
Title: Drupal8 site status - "unsupported release" / "not supported" is this deliberate?
Is this a deliberate message as drupal8 is not yet the latest production release?

The reason for raising this question is that it was unexpected in my opinion to see this. I would not have expected to see messages about unsupported / not supported - after all, Drupal 8 is being very actively developed, so to my mind it IS supported. Maybe it depends on the point of view - i.e. for production, then no, not yet. Please advise, thanks!

(see screenshot below)

Tried searching issue list for drupal 8 on drupal.org a few times but blank screen - perhaps volume of issues and peak time may be causing the results to not be displayed. Haven't raised this as an issue because it may be something I've not done right in the setup.

Wondering if it might be related to this problem (which appears to be just a warning, though):

`$ drush up
The external command could not be executed due to an application error.`

(Discussed here: Error when updating modules with Drush )

My system setup

* Running on a puphpet.com configured VM, Ubuntu 12.04 LTS 64bit
* `PHP 5.5.12-2+deb.sury.org~precise+1 (cli) (built: May 12 2014 13:46:35)`
* `mysql Ver 14.14 Distrib 5.5.37, for debian-linux-gnu (x86_64) using readline 6.2`
* `Drush Version : 7.0-dev`

Obtained drupal8 doing the following:

`$ git clone --branch 8.x http://git.drupal.org/project/drupal.git drupal8.localvm
Cloning into 'drupal8.localvm'...`

and then

`$ git pull
Already up-to-date.`

# Answer
> 0 votes
That was probably a warning in Alpha. We're now at Beta 7, and it's now yellow instead of red: There are currently 55 critical issues remaining: https://www.drupal.org/project/issues/drupal?priorities=400&version=8.x Which still gives a nice trend line toward 0, and release candidates: https://plot.ly/~xjm/37/remaining-critical-issues-during-the-drupal-8-beta/

---
Tags: 8, status-messages
---


# Question
Title: How to disable Ctools modal form from running on mobile devices?
I am using Drupal 7 Totem distro (a responsive site). My problem is that the pop-up modal form works fine on large screens but doesn't respond well on mobile devices/smartphones.

How do I disable the modal form from runnning on mobile devices?

# Answer
You can hack wonders with a little "@mediaquery" and "!important". I used this little bit with "modal\_forms", not sure if the #id is the same.

```
@media (max-width: 580px) {
    #modalContent {
      position: fixed !important;
      top: 12% !important;
      bottom: 12% !important;
      right: 4% !important;
      left: 4% !important;
    }
    div.ctools-modal-content {
      width: 100% !important;
      margin: 0 auto;
    }
    div.ctools-modal-content .modal-content {
      width: 100% !important;
    }
}

```
> 2 votes

# Answer
Next code will disable **ctools popup** appearing, and restore going to URL of link behaviour (tested for Modal forms (with ctools)), so for mobiles, instead of opening modal, it will open URL of link:

```
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
  $('a.ctools-use-modal-processed', context).unbind('click');
}

```
> 2 votes

---
Tags: 7, javascript
---


# Question
Title: Detaching Drupal Behaviors of another module
I'm using this module External Link module which adds "ext" as a class to any anchor tag matching the regex defined via the admin UI provided by the module. I then bind a click event to trigger colorbox for anchor tags with the "ext" tag. Now my issue is, any anchor tags added to the colorbox container are also being added a class "ext".

I understand that this has to do with Drupal.behaviors attach method implemented in the contrib module, but how do I "detach" this behaviors from my custom js file? Specifically for the links within the modal container.

# Answer
we faced the same issue here we are using lightbox module what we did is we dint used any extra module in common we wrote a Behaviour to add a external class and added condition to when colorbox is added remove external class

Define your base URL in any module in it

"Drupal.settings.baseUrl"

```
/* external links*/
 Drupal.behaviors.external_link = {
    attach: function (context, settings) {
      $("body .view-content a").once(function() {
                    var anchorlink = '';
                    anchorlink = jQuery(this).attr('href');
                    if(anchorlink != "#" && !$(this).hasClass('lightbox-processed'))
                    {
                        if(!(anchorlink.lastIndexOf('http') == -1) && anchorlink.lastIndexOf(Drupal.settings.baseUrl) == -1 && !jQuery(this).hasClass("external"))
                        {
                            if($(this).parent().hasClass('lightbox-processed')){
                                    jQuery(this).removeClass("external");
                            }else{
                                    jQuery(this).addClass("external");
                                    var targ = "_blank";
                                    jQuery(this).attr("target", targ);

                            }
                        Drupal.attachBehaviors();
                        }
                    }
      });
   }
  };

```

instead of lightbox-processed replace your class hope this will help you :)
> 1 votes

---
Tags: javascript, navigation
---


# Question
Title: Submitting Data / Updating Data into Webform programmatically
I have an existing WebForm in which I want to submit information through a Custom Page. Any idea how I can do that?

Also, there is another page where I want to update couple of fields in the WebForm through sid (submission ID) in a custom page.

Any Idea how to achieve that?

# Answer
> 2 votes
You can do this by adding following code in your custom module

```
  // Submit a webform
  module_load_include('inc', 'webform', 'webform.module');
  module_load_include('inc', 'webform', 'includes/webform.submissions');
  // Load node by webform id
  $node = new stdClass();
  $node = node_load($webform_nid);
  // Get next serial number
  $serial = _webform_submission_serial_next_value($webform_nid);

      $data = array(
        1 => array('Guest user'),
        2 => array('guest@example.com'),
        3 => array('Final testing of webform'),
      );

  $submission = (object) array(
    'nid' =>$webform_nid,
    'uid' => 0,
    'submitted' => REQUEST_TIME,
    'remote_addr' => ip_address(),
    'is_draft' => FALSE,
    'serial' => $serial,
    'data' => $data,
  );

  $sid = webform_submission_insert($node, $submission);

```

---
Tags: webforms
---


# Question
Title: All added links open as target, how to prevent it?
In my Drupal based website, all links that I added from CKeditor open as (target="\_blank"

```
Link example: (<a href="node/add/name">Name</a>)
After adding, example from html source: (<a target="_blank" rel="nofollow" href="node/add/name">Name</a>)

```

As you see, the 'target="\_blank" rel="nofollow"' added automatically.

How can I solve this problem?

# Answer
> 0 votes
In CKeditor when adding a link it will ask

click -\> **hyperlink** button -\>in **Target** set it as  will resolve your issue.

or if you have installed **external** module means disable it.

---
Tags: navigation, wysiwyg
---


# Question
Title: How to specify Google Chart API options for altering generated charts when using the views integration?
I have a series of pie charts being displayed through Views and the Views Dataviz module. I've also experimented with other chart modules that use the (interactive) Google Charts charting engine.

When these charts are generated through their integration with the Views module, I wonder how I can alter the chart output by using the options in the Google Chart API (options such as colour, legend, font size, etc).

I've looked in the code of individual charting modules, but I'm not sure where I can customize the output of the charts.

# Answer
# Finding an appropriate charting module

To create charts in Drupal, consider the Comparison of Charting Modules as a possible place to start from, to find the module that best fits your needs. That comparison does include the modules mentioned here, but quite AbitMORE charting modules ...

Possible alternatives that should solve this specific question, are the Chart module, or the Charts module (confusing names, I didn't invent them). Though there are other alternatives in that comparison that might be a better fit for this specific case.

# Selection criteria

The **license** that comes with the related charting library (engine) in each of these modules, should be considered also (open source or not, license fee, etc). It is one of the (important?) selection criteria for deciding on the module to go for.

Some other typical items to consider are:

* Possible privacy concerns.
* Yes or no support for saving charts in PDFs (usually supported by PHP based libraries, and not supported by JS based libraries).
* Flash based libraries should be avoided if charts are to be displayed on mobile devices.
* Some libraries (like the Google flavors ...) require a working internet connection (not always available in local DEV environments ...).

# Available options specific to the Charts module

The Charts module is possibly one of those "other charting modules" that you experimented with. For the Charts module, the currently closest answer (solution?) you can find is described in issue #2209467. And the closest solution to get this to work, is as described in comment #4 (which also includes an interesting patch). Be aware of the current status of that issue, i.e.:

* the patch only works for Highcharts (as charting engine), the Google Charts counterpart of it is still missing (and prereq for adding this feature to the Charts module).
* it is related to the Charts API (which is different from the Views integration). So after the Charts API feature gets delivered, some more (minor?) work is needed to also make it available within the Views integration of the Charts module.

So only considering the Charts module as an alternative, and applying the suggested patch is not sufficient. But at least it should help somehow to understand what the missing pieces are. And maybe inspire somebody to submit 1 (or more) additional patch(es) to make it complete?

**Disclosure**: I'm the author of the comparison and charting modules mentioned above, I hope this does not violate the site's policy on self-promotion.
> 3 votes

---
Tags: views, charts
---


# Question
Title: How to display 1 full article and the a summary of others
Hi I'm new to Drupal and I'm trying to find a way to display on my home page the full version of the latest article and a list of other articles as teasers. The teasers could be either listed under the full article or in a block in the sidebar. Is this possible? Currently I can only list articles as teasers.

# Answer
> 0 votes
You can create two views block.

Create a views block for latest article like this way

```
  under Format, select content (full content) in show filed.
  select update date field in filter criteria.
  In Advanced Options,  under Pager ' Display a specified number of items' as 1

```

Create another views block for other article like this way

```
  under Format, select content (teaser) in show filed.
  select update date field in filter criteria.
  In Advanced Options,  under Pager 'your choice' and set offset value as 1

```

Now display the blocks where you want.

# Answer
> 1 votes
Install Views, then enable the disabled view called `Front page`.

To get two different view modes for the nodes, you could add an attachment display to the view that shows a single latest article in full view mode and add it to the view at the top. Then you would set the page display (the original view) to display teasers, starting at an offset of 1.

It could also be accomplished with Display Suite.

---
Tags: theming
---


# Question
Title: Which module to use for tracking pages browsed by users?
My requirement are:

* most viewed pages
* most 404
* most 403
* most referring pages
* most visitors

In addition provides charts and HTML table view for those data.

Could someone give me any advice?

# Answer
The best tracking out there is google analytics and its not a module. You simply add the javascript provided by google to every page in your site and access all the info and much much more on google's analytic dashboard.

To add the javascript provided by google to your site other check the drupal module Google Analytics or add it yourself through a template file or drupal's add js function
> 3 votes

# Answer
I use statcounter and it tells me exact path of users.
> 2 votes

# Answer
You can enable the core Drupal statistics module and use views for configuring more detailed reporting

Your best option however, will be to use an analytics tool if you want to have charts and such like. You can try using google analytics, piwik analytics or open web analytics.
> 1 votes

# Answer
Yet another option might be to consider the Visitors module, of which I recently became the new maintainer.
> 1 votes

---
Tags: 7, charts
---


# Question
Title: How to use Oracle as a remote/local database for Drupal 7?
Can anyone offer any advice about the viability of using Oracle(commercial) as a remote/local database for Drupal 7?

I need to determine if this will work and convince my employer without incurring huge costs in testing.

# Answer
> 9 votes
There is a stable Oracle database driver in Contrib: http://drupal.org/project/oracle

However, if you want to use Oracle for your main Drupal database, you will need to test each contrib module that you are planning to use for Oracle compatibility. Many still have MySQL specific SQL, even though the situation has improved a lot thanks to the new database abstraction layer.

Using the Oracle driver to access data from a secondary database for imports and so on should work fine, though.

# Answer
> 1 votes
Another option to consider might be the Forena module, which is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports. Oracle is one of the supported DBMSs ...

---
Tags: 7, database
---


title: Select field label for a value

text:
# Question
Title: Select field label for a value
is there a way to get the label of a value from a select field? I mean that if my select field has options like:

key1|label1 Key2|label2

how can I get label1 in my node--\*.tpl.php?

Thanks.

# Answer
> 1 votes
You can use list\_allowed\_values().

```
$field = field_info_field('field_name');
$allowed_values = list_allowed_values($field);

```

For reference field\_info\_field()

---
Tags: entities
---