title: get user_page and modify main content

text:
# Question
Title: get user_page and modify main content
I'm very new to drupal. I have successfully added a new menu Tab. And When I click on it, it shows a new page with the expected data.

However I would like:

1. To have a "proper page" not just the unthemed view. How can I get the user page and assign my view to its main content ?
2. Is there any way to make the menu "ajax" ?

So far I have:

```
function custom_user_page_callback()
{
  $view = views_get_view('activity_feed');
  $view->set_display('view_block_name');
  //$view->set_arguments(array($tid));
  $view->set_items_per_page(5);
  $view->pre_execute();
  $view->execute();

  // Here Instead of printing what shall I do ?
  // like:
  // $page = drupal_get_page( user );
  // $page["main_content"] =  $view->render();
  print $view->render();
}

function custom_user_menu()
{
    $items['user/%user/activity'] = array(
        'title' => 'Activity',
        'page callback' => 'custom_user_page_callback',
        'access arguments' => array('access content'),
        'type' => MENU_LOCAL_TASK,
    );
    return $items;
}

```

# Answer
> 0 votes
I get the impression you want to create pages out of components, so rather look at Panels (and Panels Ajax Tabs).

In order to use panels properly you have to learn how to use Page manager also as Panels integrates with it. The best online tutorials on that subject are from Johan Falk at Node One, Learn Page Manager! series. Tutorial 4 - 7 of that series deals specifically with Panels, but start at the beginning and work your way through it. You will also learn a lot about context which is an essential concept to master as a Drupal site builder.

---
Tags: routes, users
---


# Question
Title: Performance and javascript issue in a drupal 7 website
I have a drupal 7 website. Currently its performance is not good and takes much time to render the web pages. For performance, I checked out in YSlow and came up with some results like move all js files at bottom, compress them and images too etc.

As far as I know its drupal structure to render js first at the head and then it loads the body content. So, Is there any way to move all js files at bottom of the web page in drupal???

I tried to aggregate javascript and css files with the admin panel in drupal but that is breaking some features of the website, say for example, some jquery and ajax codes are not working. Please suggest something for these problems as how can I approach for it.

# Answer
> 1 votes
You could try advagg, but shoving cloudflare at the problem is usually easier, let them deal with the js complexity by converting it to rocketscript for you for free!

Or you could mention which modules you have, how many scripts you are attempting to load, whether they are asynchronous/deferred etc, what version of jQuery, perhaps even a link to the site itself so we can have a look?

---
Tags: javascript, performance
---


# Question
Title: 'Flags: Node flag relationship' - Search Api - Solr - Views
* Flag - 7.x-3.0-alpha4
* Search API - 7.x-1.3
* Solr search - 7.x-1.0-rc2+13-dev
* Apache Solr - 3.5

I have Flag 3.x working fine in my Solr Views. I am able to flag/unflag correctly. Flag comes with a default 'My Bookmarks' view, that shows the current user what they have flagged at the moment. I basically took that view and recreated it using Solr Views. But I am unable to find the **Flags: Node flag** relationship to only **Include only flagged content** by **Current User**. I believe I am just missing something that is already there, because Flag 3 now uses entities, and relationships are solved for the most part. If someone could shed some light on this so I don't end up writing unnecessary code, I would appreciate it.

# Answer
> 1 votes
Forgot the close this a long time ago. Anyway, I wrote a custom module for solr to index some extra data, and a views handler to do what I needed.

# Answer
> 0 votes
First, the modules Search API Solr Search and Apache Solr are independent. You only need one or the other, and the module Apache Solr Views is only necessary with Apache Solr (the module Search API implements its own Views integration).

Second, integration of flag with Search API views is still in progress in Flag 7.x-3.x, see http://drupal.org/node/1362298 and http://drupal.org/node/1315850. You won't be able to do this without using one of those patches or waiting for them to be included in a release of the Flag module, I'm afraid.

# Answer
> 0 votes
To filter content that were not flagged by a user, I added a PHP Global field under the "Filter" section in views and added the following code:

```
$flag = flag_get_flag('bookmarks');
if ( $flag->is_flagged($data->entity, $GLOBAL['user']->uid) ) {
  return FALSE;
} else {
  return TRUE;
}

```

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


# Question
Title: After insert data to table, updating data in home page drupal7
I have a insert\_data module that used to insert data to category table, and I also have a module named mysite that has a function named “function mysite\_preprocess\_panels\_pane(&$variables) “ is used to render data to panel.tbl.php.

My question is how can I call function “mysite\_preprocess\_panels\_pane(&$variables)” from mysite module.

My purpose is after inserting data to table I want to show update data in home page(panel.tbl.php). I am new to drupal I need help or suggestion. Thanks

Insert\_data module

```
function insert_data($fn,$data) {
    $reply='';
    $status =1;
    $cid = db_insert('category') // Table name no longer needs {}
    ->fields(array(
   'name' => $data['name'],
   ))->execute();

   module_load_include('module', 'mysite', 'mysite');
   function mysite_preprocess_panels_pane();
   $reply= (array('status' => $status,'category' => $cid) );
   return $reply;
}

```

Calling mysite\_preprocess\_panels\_pane() without parameter will be fine?

Mysite module

```
function mysite_preprocess_panels_pane(&$variables) {
    $query = db_select('category', 'n');
    $query->fields('n');
    $items = $query->execute()->fetchAll();

    $variables['ar'] = $items;
}

```

Panel.tbl.php

```
<div class="panel-panel panel-col-first">a
    <?php
        if (isset($variables['ar'])) {
             foreach (array_keys($variables['ar']) as $name) {
             print render($ar[$name]);
        }
     }

?></div>

```

# Answer
Instead of implementing template\_preprocess\_panels\_pane() and inserting your content there is something called ctools content types.

A ctools content type shows up in the panels interface as panes that can be added to a region.

In your case I would create a ctools content type in your module mysite.

Basically it's a block that contains rendered data that can be placed in a region of your choice.

It will be more easy to understand for other developers how the data is inserted on the front page also since it will be visible in the Panels interface.

```
/**
 * Implements of hook_ctools_plugin_directory().
 */
function MYMODULE_ctools_plugin_directory($module, $plugin){
  if ($module == 'ctools' || $module == 'panels'){
    return 'plugins/' . $plugin;
  }
}

```

Then create a folder in your module called plugins and in that folder create a folder called plugins. Place a file called MYPLUGIN.inc The file should then be placed in *mymodule/plugins/content\_types/MYPLUGIN.inc*

Place this content in your MYPLUGIN.inc

```
<?php

$plugin = array(
  'single' => TRUE,
  'title' => t('MYPLUGIN'),
  'render callback' => 'MYPLUGIN_content_type_render',
  'description' => t('Renders something.'),
  'category' => t('Custom'),
  'edit form' => 'MYPLUGIN_content_type_edit_form',
);

/**
 * Render the custom content type.
 */
function MYPLUGIN_content_type_render($subtype, $conf, $panel_args, $context) {
  $block = new stdClass();
  $block->content = 'MYDATA';
  return $block;
}

/**
 * Edit callback.
 */
function MYPLUGIN_content_type_edit_form($form, &$form_state) {
  $conf = $form_state['conf'];
  return $form;
}

/**
 * Implements hook_form_submit().
 */
function MYPLUGIN_content_type_edit_form_submit($form, &$form_state) {
  foreach (element_children($form) as $key) {
    if (!empty($form_state['values'][$key])) {
      $form_state['conf'][$key] = $form_state['values'][$key];
    }
  }
}

```

Now replace $block-\>content with the data you want to be rendered.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How do I use an external data source in a view?
I am trying to display some TV schedule information from a thirdparty json api. I need to know what is the best way to do this. I have tried various module wsclient module,json query plugin, wsclient view integration. But none of them worked and overkill.

I can write a module to do this, but I need some information. One option I was thinking off was making a new data source available to the Views module. What hooks need to implemented for this?

# Answer
> 0 votes
Check Views JSON Query.

> JSON Query is a Views 3 plugin that adds native JSON query generation. It allows you to parse JSON using Views' graphical query builder. It works much like Views XML Backend but with JSON.

---
Tags: views
---


title: Drupal behaviors with non-core jquery

text:
# Question
Title: Drupal behaviors with non-core jquery
For various reasons I am currently working on a module with a version of jQuery and jQuery UI that is not core. In other words,

```
scripts[]=js/jquery.js
scripts[]=js/jquery-ui.js

```

are declared in the `.info` file. While this gives me the correct look and feel of my module, the form callbacks I used previously with `Drupal.behaviors` are not working anymore.

My first approach was to remove the `(function($) {...})(jQuery);` enclosures in the Drupal.behaviors function, to no avail.

My question is then: Is there a way to write these callbacks using standard (non-Drupal) jQuery or do I have to refactor everything 'the drupal way?'

Here is what I have on the .module side:

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

$form['Input type'] = array(
    '#type'=>'fieldset',
    '#title'=>'Upload your image'
);

$form['Input type']['file'] = array(
    '#type' => 'managed_file',
    '#title'=> t('Upload image'),
    '#description' => t('An optional description'),
    '#upload_validators' => array(
        'file_validate_extensions' > array('gif png jpg jpeg'),
        'file_validate_size'=>array(512*512*512),
    ),
    '#upload_location'=>'public://',

);

$form['Input type']['submit'] = array(
    '#type'=>'submit',
    '#value' =>t('Submit'),
 '#ajax' => array(
            'callback'=> 'ggent_update_image_callback',
            'wrapper'=>'mywrapper'
        ),
);

return $form;
}

///*
// * Form callbacks
// */
function        ggent_update_image_callback($form,$form_state) {
$picture_settings = array(
    'image' => file_create_url($form['Input type']['file']['#file']->uri)
    );
    drupal_add_js(array('ggent' => $picture_settings),'setting');
    return;

```

Which should send to my .js file to be used as:

```
    if (input_type === 'image') {
        img.src = '....../standardbg.png';
        Drupal.behaviors.imgupload = {
            attach: function( context, settings ) {
                if (typeof Drupal.settings.ggent.image!=='undefined' && img.src !== Drupal.settings.ggent.image) { //typeof img.src !== 'undefined' &&
                    img.src = Drupal.settings.ggent.image;
                }
            }
        };
    }

```

But this doesn't work. The Drupal.behaviors event doesn't fire at all! Any suggestions would be greatly valued. EDIT: Updating my jQuery using the suggested module does nothing.

# Answer
To all who answered or commented, thanks.

I found that the simplest way to make this work was indeed to get rid of my versions of jQuery and go with the core, but I had to add the UI libraries one by one (although it works out which co-dependencies also must be imported for you) in the `hook_init()` function with `drupal_add_library('system','ui.button');`.

I then wrapped the entirety of my js code in one big `(function($) {...})(jQuery);` and it ran fine.
> 0 votes

# Answer
If for some reason you need multiple versions of jQuery you can use the jQuery Multi module:

(libraries module is also required) and you put the different version in the libraries directory then you wrap your JavaScript code in something like this:

```
(function($) {...})(jqxxxxx);

```

where `jqxxxxx` is the version of jQuery you are using (see the documentation of jqmulti for more info)

do not include jquery scripts like you did. JQury Multi will do it automatically for you
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: Drupal7 Get results from a form in a table
I want to show my result from the form in the table on the same page.

```
//my form
function find_tryk_filter_test_form_page($form, &$form_state)
{
$form['submit']         = array(
    '#type' => 'submit',
    '#value' => t('Find trykluft element'),
    '#ajax' => array(
        'callback' => 'find_tryk_filter_test_ajax_result_callback',
        'wrapper' => 'result-wrapper',
        'method' => 'click'
    )
);

return $form;
}

```

My page callback function

```
function find_tryk_filter_test_page()
{
  $page = drupal_render(drupal_get_form('find_tryk_filter_test_form_page'));
  $page .= filter_elementer_rows($form_state['values']['dropdown_third']);
  print_r($page);
  return $page;
}

```

The function that retrives my data and create the table

```
function filter_elementer_rows($value_dropdown_third)
{
  $header = array(
    'Navn',
    'Shoplink',
    'Brochure'
   );
  $query  = db_query(//Some sql statement...));
  $rows   = array();
  foreach ($query as $row) {
    $rows[] = array(
        $row->title,
        $row->field_shoplink_value,
        $row->uri
    );
}
  return theme('table', array(
    'header' => $header,
    'rows' => $rows
  ));
}

```

My submit function

```
function find_tryk_filter_test_page_submit($form, &$form_state)
{
   return find_tryk_filter_test_page();
}

```

My problem is that when I run this, I get absolutely nothing in the table. And the SQL does work. Do I miss anything?

# Answer
The return value from a form submit function isn't used. What you need to to is rebuild the form, and alter the original form function to display the table if it's available. For example:

```
function find_tryk_filter_test_form_page($form, &$form_state) {
  if (isset($form_state['render_table'])) {
    $form['table'] = array('#markup' => find_tryk_filter_test_page());
  }

  $form['submit'] = array(
   '#type' => 'submit',
    '#value' => t('Find trykluft element'),
    '#ajax' => array(
        'callback' => 'find_tryk_filter_test_ajax_result_callback',
        'wrapper' => 'result-wrapper',
        'method' => 'click'
    )
  );

  return $form;
}

function find_tryk_filter_test_page_submit($form, &$form_state) {
   $form_state['render_table'] = TRUE;
   $form_state['rebuild'] = TRUE;
}

```

Or you might redirect to a page that has your table on it, if that makes sense:

```
function find_tryk_filter_test_page_submit($form, &$form_state) {
   $form_state['redirect'] = 'foo/bar/path';
}

```
> 1 votes

---
Tags: forms
---


# Question
Title: Drupal behind a SSL offloading reverse proxy -- is this config correct?
We are transitioning an existing drupal installation to run as a SSL-only site behind a SSL offloading proxy. Drupal itself has no SSL and is running on port 80 on apache.

We've got what we think is a pretty successful configuration:

On the nginx end of the world it looks like:

```
server {
    listen              80;
    server_name         staging.example.com;
    return              301 https://staging.example.com$request_uri;
}

server {
    listen                  443 ssl;
    server_name             staging.example.com;
    ssl_certificate         $chained_cert_path
    ssl_certificate_key     $private_key_path;

    location / {
        proxy_pass          http://$backend_ip;
        proxy_set_header    Host $host;
        proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header    X-Forwarded-Proto $scheme;
        proxy_set_header    X-Forwarded-By $server_addr:$server_port;
        proxy_set_header    X-Real-IP $remote_addr;
        proxy_redirect      http:// https://;
    }
}

```

And in the drupal site's config we are running:

```
// reverse proxy settings and such
$conf['reverse_proxy'] = TRUE;
$conf['reverse_proxy_addresses'] = array($proxy_ip);
$base_url = 'https://staging.example.com';

```

As I said this seems to be passing all tests, but my spidey sense is saying this was too easy and there is a fugly problem waiting somewhere in some part of drupal we don't understand well enough -- manually paving $base\_url just isn't sitting right with me. Are there landmines here?

# Answer
You don't have to indicate `$base_url = 'https://staging.example.com';` , you can have something like this:

```
server {
    listen              80;
    server_name         staging.example.com;
    return              301 https://$host$request_uri;
}

server {
    listen                  443 ssl;
    server_name             staging.example.com;
    ssl_certificate         $chained_cert_path
    ssl_certificate_key     $private_key_path;

    location / {
        proxy_pass          http://$backend_ip;
        proxy_set_header    Host $host;
        proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header    X-Forwarded-Proto $scheme;
        proxy_set_header    X-Real-IP $remote_addr;
    }
}

```

and in your Drupal settings:

```
$conf['reverse_proxy'] = TRUE;
$conf['reverse_proxy_addresses'] = array($proxy_ip);

// from http://devblog.more-onion.com/using-drupal-behind-reverse-proxy
if (
  isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
  $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' &&
  !empty($conf['reverse_proxy']) &&
  in_array($_SERVER['REMOTE_ADDR'], $conf['reverse_proxy_addresses'])
) {
  $_SERVER['HTTPS'] = 'on';
  // This is hardcoded because there is no header specifying the original port.
  $_SERVER['SERVER_PORT'] = 443;
}

```
> 5 votes

---
Tags: uri, proxies
---


# Question
Title: Add menu itens in Commerce Kickstart administrative toolbar
I have worked with default Commerce Kickstart 2 toolbar menu, and I really liked. But now I installed a new module, Commerce Feeds, and I can not access it because there aren't menu entries in toolbar. Is there a way to add menu entries like the one I need in Commerce Kickstart 2 toolbar menu, or I have to back to Drupal 7 administrative toolbar?

# Answer
> 2 votes
You're able to modify the Commerce Kickstart 2 admin menu from this path: /admin/structure/menu/manage/management

It's a normal menu created during installation called "Management".

---
Tags: commerce, toolbar
---


# Question
Title: Store only a resized version of an enormous uploaded image
I have editors uploading images the size of 3.8MB. I don't want to lower the maximum size for image/file upload (it's set to be 5MB), that's because I use core Image Styles (admin/config/media/image-styles), but for a server's sake, is it possible to make them upload that enormous file but just store a resized, smaller version of it? let's say, store a reduced 800x800px version of it?

# Answer
Yes, that functionality is in Drupal core as default.

In Image field settings (your Content type -\> Manage fields) set for **Maximum image resolution** to 800x800px. Drupal will resize image size and save only resized version of it.
> 1 votes

---
Tags: media
---


title: remove node in /node?page=1

text:
# Question
Title: remove node in /node?page=1
I am using Global Redirect which automatically convert /node?page=1 to /?page=1 when click on pagination. everything working fine but i want also remove /node and just want /?page=1 when mouse hover on pagination. you can also refer my site and check its pagination.

# Answer
> 1 votes
You can use `hook_menu_alter` below code not completely correct but can get you good idea about how can you do it

```
function mymodule_menu_alter(&$items) {
 $temp= $items['node/%'] ;
$items['page?%']=$temp;
}

```

---
Tags: redirection, paging, uri, nodes
---


title: image scroll on hover

text:
# Question
Title: image scroll on hover
I'm not necessarily looking for a module for this, but I'm curious where to start to get the following functionality:

Each content entity has an unlimited amount of image fields. So if I had 5 images I want to be able to "scroll" through them on the frontpage. The scrolling functionality is that when you hover over the image, it shows different images. The frontpage is generated by a view

I'm basically making a TV show site with screenshots and I want the user to be able to preview some screenshots on the frontpage by simply hovering over the episode image.

# Answer
> 0 votes
It sounds like you want a slideshow for each content, based on that image field. There are many modules that offer that functionality, some themes, and you can always write or otherwise incorporate Javascript to handle it for you.

---
Tags: views
---


# Question
Title: How do I remove the "where" clause from a structured query object in hook_query_alter()?
Jumping off of this question, I'd like to know how to gracefully detect and remove each snippet in the WHERE clause of my query object in plain old hook\_query\_alter(), not hook\_views\_query\_alter() (as the Views query object seems structured in some entirely different way (frustrating!). The documentation vaguely suggests that this is possible by showing how you can create a reference to your query conditions that you can then manipulate, by starting with this:

```
$where =& $query->conditions();

```

... but the object(s) within are utterly confusing, and I've been struggling to remove or replace existing snippets. I've explored /includes/select.inc and /includes/query.inc but the classes therein don't seem to provide any methods for fine-tune manipulation.

# Answer
> 8 votes
That's pretty much all there is to it: in hook\_query\_alter() you only have access the query object from "outside" and, since there is no public API to remove conditions, it's kinda confusing.

However, there's some clever php hackery going on so if you call `$where =& $query->conditions();` or any of the other examples in the documentation you linked it will return a reference to that corresponding variable.

So, in the *where* example above, you gain access to `$query->where` protected class variable. If you inspect them you will see they are just basic php arrays containing all of the information and you can literally just unset something on that reference and be done.

So:

`$where =& $query->conditions();
// Remove the second condition.
unset($where[1]);`

Finally, specifically with *where* queries, you want to be mindful of the `#conjunction` and eventual more complex and/or grouping stuff.

---
Tags: 7, views, database
---


# Question
Title: Views - Conditionally rewrite title link attribute based on field empty value
I have a `Resource` content type that has a `Title`, `Link` or `File Attachment`. The first is required, the latter two are optional. The goal is for the administrator to create a new piece of content and link to either an internal (or external) page OR a PDF/Word file.

What I would like is have the `Title` be a link to either the page link or file location based on whichever is empty.

Right now, in the view, I have Title, Link and File Attachment fields exposed but hidden. The Title field has Rewrite Output enabled, but how do I set it to link to either a web page or file path based on the empty value for the field?

Inside Rewrite Output, I can add either `[file_link]` or `[file_attachment]`, but this is not conditional.

# Answer
> 5 votes
From what I understand, either the "Link" OR the "File Attachment" fields will be filled in, but never both. If that is correct the solution is pretty simple.

You need to "Exclude from view" the title field.

Then, you need to Rewrite both the File Attachment and Link fields via the "Rewrite the output of this field" and put the \[title\] (or wahtever the field name is) in the rewrite field.

Then also for each of those 2 fields, check the "Output as link" and put the link field into the link path for the link, and put the file attachment field into the link path for the file attachment.

Now you only need to open the "No Results Behavior" fieldset for each of those fields and check "Hide if Empty" and "Hide rewriting if empty".

Now either one or the other will be output with the title as a link to either the page or the file attachment depending on what you filled in on the node edit screen.

---
Tags: views, uri, database
---


# Question
Title: How may I add a tab item in an OG that shows a Content Type related to that group?
We have Drupal Commons 3 (on Drupal 7). In our groups, I'd like at add a tag near the group's title that links to a certain content types. I have a View ready to go. How might I add that view to an OG tab?

**Update and screen shots:**

So I have this view:

I had hopped to create a new tab here:

By playing with this setting:

# Answer
> 1 votes
Hope this will help you,

In Drupal 7, you can achieve this using creating a new MENU item via programmatically OR by VIEWS.

Programmatically:

* Create a menu item

```
function test_menu() {
  ....
  //menu for shows a Content Type related to that group
  $items['node/%/og-content-type'] = array(
  'title' => 'OG content type',
  'page callback' => 'get_og_content_type',
  'page arguments' => array(1),
  'access callback' => 'og_content_type_access',
  'access arguments' => array(1),
  'type' => MENU_LOCAL_TASK,
  'weight' => 5,
  );
  ...
  return $items;
}

```
* Now give access to the tab

```
function og_content_type_access($etid) {
  if (access) {//check your condition. Based on this condition the TAB will show.
    return TRUE;
  }
  else {
    return FALSE;
  }
}

```
* Now its time to embed your view

```
function get_og_content_type($etid) {//Im passing ID in case you want in views.
  $html = '';
  $html = views_embed_view('VIEWNAME', 'display_id', $etid);//embed view
  return $html;
}

```

Reference : views\_embed\_view

**Using Views**:

* Just create a new VIEW, with path as **node/%/YOUR\_PATH**, **Contextual filters** and **Permission**. Refer the images below
* Create a NEW menu TAB now
* Add Contextual filters, based on this filter the VIEWS content changes.
* Final result

To create a custom permission in VIEWS, you can use **PHP filter**.

* Go to admin \> modules and enable **PHP filter**
* Go to your VIEW \>\> **Page settings \>\> Access** and select PHP filter and add this code without **PHP TAGS**.

```
  if (arg(0) == 'node' && is_numeric(arg(1))) {
    $entity_type = 'node';
    $etid = arg(1);
    if ($group = og_get_group($entity_type, $etid)) {
      return TRUE;
    }
    else {
      return FALSE;
    }
  }

```

NOTE :

* You can create you own permission using hook\_permission and you can use that permission in VIEWS \>\> **Page settings \>\> Access**

# Answer
> 0 votes
I lack the requisite reputation points to comment (really?) but I wanted to call out Richard's remark about using the Group ID in the contextual filter rather than the Node ID.

A group is a node, yes, but I just completed this exercise and it refused to work with *Content: NID* as the contextual filter. When I changed it to *OG Membership: Group ID* I began to get the expected view results:

---
Tags: organic-groups, 7
---


# Question
Title: "Send email" action not working to send email to poster of comment
I have successfully set up email notifications on my client's blog for administrators when new comments are posted and am now trying to set it up to send a thank-you email to the poster of the comment as well. I set it up using triggers and actions as described here.

I put in `[comment:author:mail]` in the "Recipient" field on the action configuration form as suggested in the note right below that field, but it seems that it never sends the email. I initially tested it using my own email address and it worked fine, then I posted a comment as an anonymous user using two different email addresses of mine but never received an email. Why is `[comment:author:mail]` not working? I'm using other variables in the body of the email (e.g. `[comment:node:title]`) and they're working fine.

I tried using Maillog as @tenken suggested below, which verified that the problem isn't with mail delivery but rather with the email not being populated correctly:

Here's a screenshot that shows the email to the administrator is working correctly, but not the thank-you email:

# Answer
The anonymous user account doesn't have an email address to send to. You will want to use the value of the field that collects the email address instead of author:mail.
> 1 votes

# Answer
This question can be very hard to answer -- email is tricky as PHP just hands off your email to the underlying/remote mail system. I suspect nobody can tell you exactly what's wrong without in-depth examination of your setup.

But, the Mail Developer module will allow you to "try" to send and log raw emails without actually sending them, you can likely look for differences between mails that do send -- and the emails you think are not sending correctly.

> Maillog provides an easy possibility to log all Mails for debugging purposes. It's possible to prevent the mails to being sent, so there is no need for an extra mail server to test the mail functionality of other modules or the drupal core. Additionally you can immediately display the mail through the devel dpm() facility.
>
> If you like to upgrade from a previous dev release, please disable, uninstall and reinstall again. There's no upgrade procedure yet.

Also see the similar modules on the project page -- for additional tools to debug and resolve your problem.
> 1 votes

---
Tags: comments, emails, actions, rules
---


title: Honeypot in custom webforms (manual)

text:
# Question
Title: Honeypot in custom webforms (manual)
I'm making a custom form (fields are added by using `drupal_render`), but since I have Honeypot enabled for all my web forms, when I submit a form, I get the following message:

> There was a problem with your form submission. Please wait X seconds and try again.

That's because Honeypot markup isn't being included in my custom form.

I have two options:

1. Disable Honeypot for this form (not possible through module settings from Drupal administration menu). **How can I add an exception?**
2. Enable Honeypot manually (with `drupal_render`s I guess).

Honeypot docs is so poor, so I also have tried to add Honeypot markup manually in this way: `<?php print drupal_render($form['honeypot_time']); ?>
 <?php print drupal_render($form['url']); ?>`

It adds the markup actually, but it isn't fixing yet.

# Answer
> 7 votes
According to the module documentation, you can do this:

> If you want to add honeypot to your own forms, or to any form through your own module's hook\_form\_alter's, you can simply place the following function call inside your form builder function (or inside a hook\_form\_alter):

```
<?php
  honeypot_add_form_protection($form, $form_state, array('honeypot', 'time_restriction'));
?>

```

> Note that you can enable or disable either the honeypot field, or the time restriction on the form by including or not including the option in the array.
>
> You can also use Honeypot's API to modify the time delay for forms, add or remove protections for certain forms, etc.

---
Tags: 7, webforms, advertising
---


# Question
Title: How to make the "Height" of Views Slideshow Fully responsive?
I'm working on a slideshow on Drupal 7 with Views Slideshow. The only issue I have right now is to make the **Frame** "**Height**"(not the image) responsive **when resizing the browser**. I found many articles, questions and answers about how to make Views Slideshow responsive, but none of them work properly. I believe the "Frame" is causing this.

These articles I found does not really fix the height of Views Slideshow. Maybe I missing something.
\- Make views slideshow responsive - remove inline styles
\- Can't remove the height/width of the slide container

----- updated for @Patrick Ryan

I got some error from google chrome web browser after adding these js

----- updated on Aug. 20, 2014 @ 9:46am
I found the following script also fix the height. Its from drupal.org issue views Slideshow for Responsive design on #26

```
$(window).resize(function(){
  $('.views_slideshow_cycle_main').each(function(){
    var cycleMain = $(this);
    var img_width = 0,
        img_height = 0;
    var clearCSS = {width: "auto", height: "auto"};
    var cycle = cycleMain.children('.views-slideshow-cycle-main-frame');
    cycleElements = cycle.data("cycle.opts");
    cycle.css(clearCSS);
    cycleMain.find('.views-slideshow-cycle-main-frame-row').each(function(i){
      $(this).css(clearCSS);
      var tmp_img_width = $(this).width();
      var tmp_img_height = $(this).height();
      if(tmp_img_width > img_width)
        img_width = tmp_img_width;
      if(tmp_img_height > img_height)
        img_height = tmp_img_height;
      cycleElements.elements[i].cycleW = tmp_img_width;
      cycleElements.elements[i].cycleH = tmp_img_height;
      $(this).css({width: tmp_img_width, height: tmp_img_height});
    });
    cycleMain.height(img_height);
    cycle.css({width: img_width, height: img_height});
    cycle.data("cycle.opts.elements", cycleElements);
  });
});

```

# Answer
> 4 votes
I normally take care of the height with javascript. First I make sure that I am handling the width properly with CSS:

```
.views-slideshow-cycle-main-frame,
.views-slideshow-cycle-main-frame-row,
.views-slideshow-cycle-main-frame-row img {
  width: 100% !important;
}

```

Then I create a function that sets the height. This will take whatever container your slideshow is in as a parameter and find the slideshow within it.

```
/* Slideshow resize function */
Drupal.theme.prototype.slideshowResizer = function (target){
  var slideheight = 0;
  $(target + ' .views-slideshow-cycle-main-frame-row').each(function(){
    slideheight = $(this).find('.views-slideshow-cycle-main-frame-row-item').innerHeight();
    if(slideheight != 0){
      $(target + ' .views-slideshow-cycle-main-frame').css('height',slideheight+'px');
      $(target + ' .views-slideshow-cycle-main-frame-row').css('height',slideheight+'px');
      return false;
    }
  });
};

```

And finally I call the function on the window resize event:

```
Drupal.behaviors.slideshowResize = {
  attach: function (context, settings) {
    $('.your-slideshow-container', context).once('processed', function () {
      Drupal.theme('slideshowResizer', '.your-slideshow-container');
    });

    $(window).resize( function() {
      Drupal.theme('slideshowResizer', '.your-slideshow-container');
    });
  }
};

```

Also, make sure your base img tag has `height: auto;`

---
Tags: views, theming
---


# Question
Title: Creating a new Workbench view showing recently updated content and its state
This is a simplified example to show my problem.

I've added a handful of Workbench moderation states (and plenty of transitions) into my workflow system.

I need to create a new table view to display content with the following columns:

* Title
* Revision review date
* Moderation state

(I want to either add an external filter on the moderation state, or separate the states out into multiple displays).

This is what I've done:

1. Created a new view of Content revisions
2. Added a Workbench Moderation: State field using the relationship to the Content revision
3. Added sort criteria of Content revision updated date descending to show most recently updated nodes
4. Removed the 'Published' filter - as the content under review might not be published yet.

However, what I see is repeated content. After adding a filter 'current moderation' I know that to reduce the duplicates, it would be necessary to add a filter 'Workbench Moderation: Current (Yes)'. However, after adding this filter, the list doesn't show the current moderation state. Is this a bug?

# Answer
I think I figured this out, actually.

1. Create a new View which lists "Content *revisions*" (not just "Content"). "Save & continue."
2. On the View edit screen, open up the "Advanced" right-hand column, remove the "Content revision: Content" relationship from the "Relationships." This causes the View to query the `node_revision` table, but join the `node` table in the `vid` field, which isn't what we want (because `node.vid` will not always point to the latest revision). Instead, add the "Content revision: Content: The revision NID of the content revision" relationship. Even though this one is also labeled "Content revision: Content," it'll join on `node.nid` instead of `node.vid`.
3. From the Filters section, remove the "Content: Published (Yes)" filter. Replace it with a "Workbench Moderation: Current" filter, set to Yes. Don't relate it to the new relationship we just made ("Do not use a relationship").
4. When adding entity fields, use the "Content (historical data)" ones instead of just the "Content" ones.

This approach seems to be working for my needs so far.

EDIT: In retrospect, I wasn't quite having the same problem as you were after all, since it doesn't sound like you were wanting to show only one revision per node. But I'll leave my answer up in case someone else eventually finds it useful.
> 3 votes

---
Tags: views, workflows, workbench
---


# Question
Title: Get Users by roles for organic groups drupal7
I have following system roles set up for users

1. content publisher
2. content approver

All my users divided in to 5 organic groups.

I didn't set up any roles for organic groups.I am trying to get content approvers for particular group for approval process.

I tried using this function **og\_get\_users\_by\_roles**.

But the above function uses the organic group roles not system roles.

I am confused now should i setup same roles for organic groups.Please give some direction.

# Answer
> 1 votes
Try this if it works for you.call this function with user\_role id and group id as parameter.

```
    function get_users_on_role_and_group_basis($rid, $gid) {
      $users = entity_load('user');
      foreach($users as $user) {
         if(is_array($user->og_user_node)) {
           if (array_key_exists($rid, $user->roles)) {
             foreach($user->og_user_node['und'] as $key=>$values) {
               if(in_array($gid,$values)) {
                 $get_user[] = $user;
                }
            }
          }
        }
      } if(isset($get_user)) {
          return $get_user;
        }else {
        return 0;
      }
    }

```

# Answer
> 1 votes
If you would like to get a list of organic group users by their roles, there's no core og function to do that. And it doesn't seem like that's what you're after.

However, for those who have found this thread while searching for a way to get organic group users by roles, one can install the module og\_extras for this function:

```
/**
 * Get all the users with certain roles in a group.
 *
 * @param $gid
 *   The group unique ID.
 * @param $roles
 *   Array with the role IDs to query.
 */
og_extras_get_users_by_roles($gid, $rids = array())
snip->

```

# Answer
> 0 votes
This is clearly the wrong function to use to get system roles and I don't know of any functions that would take care of this query. You should query the og\_ tables or possibly rethink your role system and use OG roles.

# Answer
> 0 votes
It is clearly you are confused. OG managed his roles and permission separately from the roles and permission of Drupal.

This is done in the configuration tab in the admin under the OG area(user permission or something like this). This is managed this way so each group bundle can mange their permission different from other groups bundles(you can also grant to each group the option to override the permission individually).

I describe two scenarios and from here you can help us direct you to how this should be done:

1. You rely on the system roles and then the roles of OG will not take place.
2. You rely on the permissions and roles of OG and you don't pay attention to the wide roles. This will mean that you need to create roles under the OG.

If you decide to use 2 then some you'll need to get the users from the groups(the information is done with the entity `og_membership` which manage the entities that belong to groups) Then you can get the users roles with the function `og_get_user_roles()`

---
Tags: organic-groups, users
---


# Question
Title: Drupal rendered page for directory root, followed by static pages?
I have a directory that I want to load through the Drupal system, which of course is fine with clean URLS:

> /my-dynamic-page/

However at this directory I then want to serve static pages

> /my-dynamic-page/static1

When I add a folder for /my-dynamic-page/ to the server, this now bypasses the Drupal system. While the static pages now work, when you try and load /my-dynamic-page you get a Forbidden error. This is because the Drupal system has been bypassed (there is a physical folder now) so the system looks for an index file.

How do I overcome this?

# Answer
> 1 votes
Add your own .htaccess file under the my-dynamic-page and my-dynamic-page/static1 with only this in it:

```
DirectoryIndex index.html index.htm

```

# Answer
> 0 votes
Thanks to J.Reynolds whose answer pointed me in the right direction to use DirectoryIndex.

In the dynamic directory I created a .htaccess with the following:

```
DirectoryIndex index.php /index.php

```

So it looks for a local index.php first, if not then goes to the root PHP index file.

---
Tags: uri, .htaccess
---


# Question
Title: Why does the autocomplete return incomplete words?
I am working on an autocomplete feature based on the Search API Autocomplete module. Basically I almost copied the functions I needed from this module for my use case. I set up a Solr index, and I am trying to query it, so it returns back relevant suggestions.

The problem is that the words returned are not always the words I am expecting. For example, if I enter *Pu*, the module should return *Publication* because this word is present in some nodes; it returns *Public*, which is not even present anywhere. From where does this mysterious word come? I don't know if the problem is with Solr index or Search API module, since they are twice involved in the module.

They are a lot of errors. Here are some examples of the issue.

* *studi* instead of *studies*
* *strategi* instead of *strategies*
* *describ* instead of *describe*

# Answer
> 0 votes
Actually the issue was related with stemming algorithms as Clive mentioned first. By removing this line in fieldType name="text" in schema.xml file, autocomplete was repaired:

```
<filter class="solr.SnowballPorterFilterFactory" language="English" protected="protwords.txt"/>

```

So, after I disabled stemming everything was good with autocomplete feature (either contrib module and my custom one), but unfortunately there was a new problem with standard queries (using Search API and views module); those were no more working. Then I managed to solve all issues my changing the analyzer of fieldType name="text" to this one.

```
<!-- An unstemmed text field - good if one does not know the language of the field -->

<fieldType name="text_und" class="solr.TextField" positionIncrementGap="100">
  <analyzer type="index">
    <tokenizer class="solr.WhitespaceTokenizerFactory"/>
    <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" enablePositionIncrements="true" />
    <filter class="solr.WordDelimiterFilterFactory"
            protected="protwords.txt"
            generateWordParts="1"
            generateNumberParts="1"
            catenateWords="1"
            catenateNumbers="1"
            catenateAll="0"
            splitOnCaseChange="0"/>
    <filter class="solr.LengthFilterFactory" min="2" max="100" />
    <filter class="solr.LowerCaseFilterFactory"/>
  </analyzer>
  <analyzer type="query">
    <tokenizer class="solr.WhitespaceTokenizerFactory"/>
    <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
    <filter class="solr.StopFilterFactory"
            ignoreCase="true"
            words="stopwords.txt"
            enablePositionIncrements="true"
            />
    <filter class="solr.WordDelimiterFilterFactory"
            protected="protwords.txt"
            generateWordParts="1"
            generateNumberParts="1"
            catenateWords="0"
            catenateNumbers="0"
            catenateAll="0"
            splitOnCaseChange="0"/>
    <filter class="solr.LengthFilterFactory" min="2" max="100" />
    <filter class="solr.LowerCaseFilterFactory"/>
  </analyzer>
</fieldType>

```

With this definition for my text fields, everything works perfectly. Even accented characters are correctly returned, so it fits exactly my use case, as system is indexing english and french publications.

Thanks

---
Tags: search, ajax
---


title: Issue implementing Ajax in form

text:
# Question
Title: Issue implementing Ajax in form
I created a basic page which has a basic form and implements ajax, or attempts to do so. My issue is that it doesn't seem to be functioning as it should. What might be Ajax, only works after I press enter in the textfield, which submits the data and refreshs the page, although I don't think it's ajax at work, rather the form functioning normally, I changed the #event to blur and the #keypress to false but everything is still entirely the same. Ultimately ajax isn't working, if anyone can clear this up that'd be grand.

```
<?php
/**
 * @file
 *  Creates form page which implements ajax
 */

/**
 * Implements hook_menu();
 */
function formajax_menu() {
    $items['formexample'] = array(
      'title' => 'Form Ajax Example',
      'description' => 'This is a page generated via hook menu
                        which displays a form with ajax support',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('formajax_form'),
      'access callback' => TRUE,
    );
    return $items;
 }

function formajax_form($form, &$form_state) {
  // create a fieldSet
  $form = array();
  $form['data'] = array(
      '#type' => 'fieldset',
      '#title' => t('Form Ajax Example'),
    );
 // Create textfield
    $form['data']['textinput'] = array(
      '#title' => t('Name'),
        '#description' => t('Your Name Here'),
        '#type' => 'textfield',
      // add ajax property with callback and wrapper
      '#ajax' => array(
          '#callback' => 'formajax_callback',
          '#wrapper' =>  'replace_this',
          '#effect'  => 'fade',
          '#event' => 'blur',
          '#keypress' => FALSE,
        ),
    );
    // create item dependant on textfield
    $ajax = (!empty($form_state['values']['textinput']))
             ? $form_state['values']['textinput'] : 'John';
    $form['data']['ajax_response'] = array(
      '#type' => 'item',
      '#title' => t('Ajax Response'),
      '#markup' => t('Your Name is' . $ajax),
      // prefix item with div id of wrapper
      '#prefix' => '<div id="replace_this">',
      '#suffix' => '</div>',
    );
    return $form;
 }
// create callback which will return data
function formajax_callback($form, &$form_state) {
    return $form['data']['ajax_response'];
}

```

# Answer
> 0 votes
Take the #'s off the nested #ajax values. IE

```
  '#ajax' => array(
      'callback' => 'formajax_callback',
      'wrapper' =>  'replace_this',
      'effect'  => 'fade',
      'event' => 'blur',
      'keypress' => FALSE,
    ),

```

---
Tags: forms, ajax, routes
---


# Question
Title: Using breadcrumbs with multiple menus for one link
In my website I have 2 menus; the *Main Menu* and the *Header Menu* that I use for *quick links*.

I have 1 page that is linked in both menu.

When I'm on that page, the breadcrumb (and other menu-related blocks) use the hierarchy of the *quick-link* menu.

In my node the menu configured is the *Main Menu* and I added the link manually to the *Header Menu*.

Is there any way to give a *weight* to different modules?

Thanks!

# Answer
> 1 votes
Multiple Node Menu might do the trick:

> This module modifies the "Menu settings" in standard node editing form to allow managing multiple menu links to a node. The Drupal standard behavior is to only care about a single menu link for anode, all other menu links must be added through menu administration.

# Answer
> 0 votes
Menu Trail by Path *should* help:

> Menu Trail By Path sets the active-trail on menu items according to the current url.

Just in case, I always use Path Breadcrumbs as well. If you're comfortable with Page Manager, then the UI is really simple. If not, then it shouldn't take you long to figure it out :)

> This module is a solution for all problems with the breadcrumbs on your site!
>
> Path breadcrumbs module helps you to create breadcrumbs for any page with any selection rules and load any entity from the URL!

Although if you just want to change the weights of the module in the `system` table, then the following documentation is the place to look: How to update a module's weight

# Answer
> 0 votes
In Crumbs you have one plugin key per menu, which you can prioritize.

E.g. you might have `menu.hierarchy.main-menu` and `menu.hierarchy.header-menu`. Go to admin/structure/crumbs to move them up and down.

Note: You can also use the `menu.hierarchy.*` wildcard.

Crumbs, once enabled, will handle all the breadcrumbs on your site. Usually this is a good thing, but you should evaluate.

---
Tags: routes, breadcrumbs
---


# Question
Title: overriding template file of display suite layout applies on other pages
I created a display suite layout "tow column stacked" in manage user section, then I want to override that template, and make a new one in my theme templates folder, the ds module suggest for me :

> * ds-2col-stacked--user.tpl.php
> * ds-2col-stacked--user-user.tpl.php

so I created `ds-2col-stacked--user-user.tpl.php` in my templates folder, but this template is overriding as well the registration page!

how can override with the correct name, to apply this new template only for user edit account page `("/user/%/edit")` ?

Thanks in advance.

# Answer
> 2 votes
You can use hook theme suggestion in your template file. It gives you the right way of naming you tpl file.

```
function THEME_preprocess_node(&$variables) {
  print_r($variables['theme_hook_suggestions']);

}

function THEME_preprocess_page(&$variables, $hook) {
  print_r($variables['theme_hook_suggestions']);

}

```

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


title: Set conditonal default value of a field

text:
# Question
Title: Set conditonal default value of a field
I have a custom form with a field...

```
function mh_integration_connect_form($form, &$form_state) {
  $form['#method'] = 'get';
  $params = drupal_get_query_parameters();
  $form['cat'] = array(
    '#type' => 'select',
    '#title' => t('Categories'),
    '#options' => $categories,
    '#default_value' => $params['cat'],
  );
}

```

as $param is not set before the form is submitted, so it show error for "Notice: Undefined index: cat". I am wondering if we can set this default\_value conditionally,

```
if(isset($params['cat'])) {
    '#default_value' => $params['cat'],
}

```

# Answer
You simply want to remove this error and conditionally use the default value.

For this, you can also do one more thing in addition to this code

```
function mh_integration_connect_form($form, &$form_state) {
  $form['#method'] = 'get';
  $params = drupal_get_query_parameters();
  $form['cat'] = array(
    '#type' => 'select',
    '#title' => t('Categories'),
    '#options' => $categories,
    '#default_value' => isset($params['cat']) ? $params['cat'] : '',
  );
}

```

Hope it works for you! Thanks.
> 0 votes

# Answer
Here is how you can do it:

```
  $params = drupal_get_query_parameters();
  $form['cat'] = array(
    '#type' => 'select',
    '#title' => t('Categories'),
    '#options' => $categories,
  );

  if(isset($params['cat'])) {
    $form['cat']['#default_value'] = $params['cat'];
  }

```
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Possible to use PDO inside a custom module in Drupal 6?
I'm about to build some new functionality on an old Drupal 6 site which will be upgraded to D7 or D8 within a year or so. This new module is heavy on the SQL and I'm building many complex SQL queries. I'd love to use PDO with named parameters to make the code readable.

Is it possible for me to initialize my own PDO connection to MySQL inside the module or will this break the rest of the Drupal environment somehow?

# Answer
You definitely could (Drupal is just a a PHP application, nothing special in that respect). But you'd lose support for stuff like table prefixing.

If you're looking to use PDO, and stay within the bounds of normal Drupal practices, you should install the DBTNG module:

> This is a backport of the Drupal 7 PDO database compatibility layer for use with Drupal 6 modules.
>
> ...
>
> This module does not override the existing database functionality but makes the new compatibility layer available under a series of functions identical to their Drupal 7 counterparts named dbtng\_ instead of db\_. For example with this module, use dbtng\_set\_active instead of db\_set\_active, with the exception of the following functions that funciton identically to their Drupal 7 conterparts: db\_insert, db\_merge, db\_update, db\_delete, db\_truncate, db\_select, db\_transaction, db\_close, db\_condition, db\_xor, db\_and, db\_or, db\_next\_id, and db\_like.

That should let you write code that won't need to be changed for Drupal 7 and 8 (unless table/field names change of course).
> 2 votes

---
Tags: 6, database
---


# Question
Title: Form API ajax calls reload attached JS using behaviors
I have leaflet map attached to my form, this is the container div I used:

```
$form['general']['map'] = array(
  '#markup' => '<div class="map-wrapper" id="ngmap"></div>',
);

```

Everything works fine and map's being loaded. I also added an image upload functionality in bottom of my form like this:

```
$form['detailed']['img'] = array(
  '#type' => 'managed_file',
  '#upload_location' => 'public://map-images/',
  '#required' => TRUE,
  '#title' => 'Image',
  '#default_value' => $complain['image'],

);

```

When I click on ajax upload button after selecting the image file, it throws an error and nothings happen:

> Uncaught Error: Map container is already initialized.

Seems like uploading file is forcing leaflet.js to reload map container. My guess is ajax is reloading and rendering the whole form all over again.

How's that possible and what's the easiest fix for this? Thank you.

Edit: How I added initializing function, look like this attached js is being recalled everytime I click on upload image ajax button:

```
(function($, Drupal) {

  // Custom functions and variables can go here
  Drupal.behaviors.moduleName = {
    attach:function() {
      map = new L.Map('ngmap', {center: new L.LatLng(37.472, 57.327), zoom: 13});
      googleLayer = new L.Google('HYBRID');
      map.addLayer(googleLayer);
    }
  };
}(jQuery, Drupal));

```

# Answer
Drupal calls every declared behaviors when an AJAX call is performed. This is done to apply the declared behaviors to new loaded content via AJAX.

When a behavior is applied to an element a class is used to mark that element as behavior processed, so next behavior call ignore this element. The recommended way to do this is using the jQuery Once, included in Drupal 7. See the behaviors section of this page.

In your case you should use something like this:

```
(function($) {

  // Custom functions and variables can go here
  Drupal.behaviors.moduleName = {
    attach:function(context, settings) {
      $('#ngmap', context).once('leaflet', function () {
        map = new L.Map('ngmap', {center: new L.LatLng(37.472, 57.327), zoom: 13});
        googleLayer = new L.Google('HYBRID');
        map.addLayer(googleLayer);
      });
    }
  };
}(jQuery));

```

Once will add a 'leaflet-processed' class to the #ngmap element, so next time the behavior is called the initialized map is ignored.

Imagine you have several maps in the same page, and imagine you can load more by using AJAX calls. The above code, with some modifications, allows you to initialize every new loaded map after the AJAX call.

So, your fix works but is not the right way to do it (in general inline code is discouraged), I recommend you to use the #attached and Once approach.
> 2 votes

# Answer
I initialized Map in an external js file and attached it to form using \['#attached'\] property of Form API.

What I didn't know and the problem was that every time an ajax call happens Drupal recalls all attached js files, so it re-init leaflet map and throws that error (since it's already been init).

attached syntax (see Form API):

```
$form['#attached']['js'] = array(
  drupal_get_path('module', 'mymodule') . '/mymodule.js',
);

```

My quickfix for now was moving init code to inline using drupal\_add\_js() function, so it gets called only once. Hope this could help others too.
> 1 votes

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


title: views grouping by field type in a row

text:
# Question
Title: views grouping by field type in a row
Here is what i get in views:

(first-row)
node1title
node1body

(second-row)
node2title
node2body

---

and this is what i want:

(first-row)
node1title
node2title

(node2-row)
node1body
node2body

is it possible to get it in a single view?

# Answer
one possible answer is to add views php module add php code in for titles and then for body.
> 0 votes

---
Tags: views
---


# Question
Title: Content Access for not showing specific Content types on Add Content page
I am new in Drupal. I have one simple query.

I am trying to create one Editor role for one website. Editor would be able to create, update and delete one specific content type "Documents".

I have given permission using ACCESS CONTROL and also I have checked in Permission page. It only has permission to add "Documents Content Type" but still when I login as an Editor and try to create new "Document Content", it shows all the content types. I want to hide other content types for Editor.

So basically it should show only "Document Content Type" for a user.

**P.S. This is bit different question. So don't make it as duplicate question Pls.**

# Answer
check your permission tab once again
> 0 votes

---
Tags: nodes, users
---


title: Views results diplay modes

text:
# Question
Title: Views results diplay modes
I have a view with its filters exposed. when someone searches for any content results are shown perfectly in list view . now wat i want is a link showing grid view of the same result. more apecific i want a result to be in 2 modes 1) list view and another one is the grid view.

# Answer
> 1 votes
You can do this by creating two different display of same view. If your current view display is page at path like `/view/list-view` then create another page display of same view with path like `/view/grid-view`. Then Configure that display as Grid view under views `Format` settings. You can use that path to create link to that view later anywhere you want.

---
Tags: views
---


# Question
Title: how to separate taxonomy hierarchy in pathauto with slashes
Pathauto seems to have a different way of aliasing taxonomy hierarchy.

From Taxonomy Menu:

1. Classifieds \> Cars \> Aston Martin \> DB9 Coupe
2. Classifieds \> Jobs \> Accounting

What I want is something like this for the url:

* classifieds/jobs/accounting (not accounting-jobs-classifieds)

(Note that Pathautho generates this with dashes in reverse order as well.)

In Pathauto, I'm using this pattern: `Default path pattern` (applies to all vocabularies with blank patterns below)

`[term:parents-all]`

Confused.

# Answer
With the Token module enabled, you can set a pattern like this:

```
[term:vocabulary]/[term:parent:parent:name]/[term:parent:name]/[term:name]

```

Make this pattern as long as you want. Your paths will then become:

```
vocabulary
vocabulary/category1
vocabulary/category1/subcategory1
vocabulary/category1/subcategory2
vocabulary/category1/subcategory2/subsubcategory1

```

and so on...
> 10 votes

# Answer
There is a clever way to do this by using **join:/**

In my case, I used:

`[node:field-taxonomy-skolski:parents:join:/]`

where `field-taxonomy-skolski` is the field for choosing the term from the taxonomy tree. Forward slashes will be stripped, though there is a setting under

**Administration » Configuration » Search and metadata » URL aliases » URL aliases** \- settings

at the bottom of the page for **PUNCTUATION drop-down**. Set to slash (/) "no action" instead of "remove".
> 16 votes

# Answer
This one works for me on Drupal 7.15 with Token 7.x-1.3 and Pathauto 7.x-1.2:

> \[term:parents:join:/\]/\[term:name\]

As brunops stated in the second answer, join:%separator% does the magic. It replaces the default dash with %separator%.

A big thanks to brunops!
> 6 votes

# Answer
The keys to getting this to work is:

* install and enable the Entity API, Entity Tokens, Path Auto and Taxonomy modules.
* create a field on your content type and set Field Type to Term Reference and name it something like 'field-content-category' (machine name)
* Set the Number of Values, aka, 'Maximum number of values users can enter for this field' to 1 (very important if you want to use the joined-path tokens which automatically adds a / between the path elements).
* set the URL patterns (admin/config/search/path/patterns) to something like '\[node:field-content-category:parents:join-path\]/\[node:field\_content\_category\]/\[node:title\]'
> 3 votes

# Answer
Well I would recommend using something smart like:

\[term:parent:terms:reversed:join:?\]

But I cant for the life of me get it working neither. So instead I recommend the following but you can only go as deep as the hierarchy allows (can be seen in replacement patterns). If you add terms deeper in the hierarchy you will have to update the pattern also.

\[term:parents-all:3\]/\[term:parents-all:2\]/\[term:parents-all:1\]
> 0 votes

---
Tags: 7, taxonomy-terms, routes, path-aliases
---


# Question
Title: Taxonomy breadcrumb on taxonony block in views (by contextual filters)
I have set up a block that shows up on the relevant pages that shows up other nodes with the same taxonomy terms (by means of contextual filters that take the argument from a given page).

Can I add a breadcrumb to the header of this block view? I have Crumbs installed.

Example Case:
This is a commerce site, and all the products are tagged by 2 vocabularies: "category" and "collection". Items that share a category tag are "internally similar" (say, all the apples), while "collection" tage are whose that the seller wants to present as similar (say, an apple and a specialized apple knife).
At the bottom of the product page are two blocks (views, contextual filters that take term argument from page) that display products that share both respective taxonomy terms with the main product on the page, and I want *those* to have a "taxonomy breadcrumb": not only a title with the (linked) tag name, but also its parents (s).
I have actually achieved that functionality by adding a views attachment to the block views.

# Answer
> 1 votes
I think this could be done with Crumbs programmatically, but this might be overkill. It would also be fragile, because it would depend on Crumbs functionality that is not really part of the public API, so could change in future versions of Crumbs.
Also consider that you don't really need the full breadcrumb, just the taxonomy trail.

Instead, you could write a custom Views header plugin. Unfortunately it is a bit hard to find documentation on that.

Or, you could alter the views header with one of the views hooks.

Or you could use the theme layer to override the views theme output for this specific view.

Or override the block template for the specific block. I think this one is actually the easiest for a starter, and for this specific situation. You can get the taxonomy term from the node, and you get the node with menu\_get\_object().

Have a look at https://api.drupal.org/api/drupal/modules%21taxonomy%21taxonomy.pages.inc/function/taxonomy\_term\_page/7 to see how the taxonomy page calculates a breadcrumb based on the taxonomy hierarchy.

(I am mentioning more than one solution here, because other readers might have slightly different requirements.)

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


title: users adding images

text:
# Question
Title: users adding images
I am wondering what the best option would be for adding images to Drupal 7.

I am running a new social media site for cats and their catlover humans at http://aimable.ghookermls.info/. My authenticated users want to add images, including animated gifs, easily. I don't want the images to be too large, which would either mess up the display, take too long to load, take up too much disk space, or some combination thereof. I also don't want the images to interfere with other aspects of the site.

Here's what I have tried, and why it is not working optimally:

**Image with Article.** Only one image allowed per article, and Statuses (fbsmp) do not allow that to work properly.

**Statuses / Facebook-style micropublisher.** Images are compressed rather than resized; resizing cuts off the right edge; and the fbsmp module is interfering with images in articles.

**IMCE.** Works with CKEditor for most users; for others, they cannot upload. When I browse their files as administrator, I get the following error:

* Directory u(%n) is not accessible.
* Unable to get a working directory for the file browser!
* Notice: Undefined index: perm in include() (line 14 of /home/.../public\_html/.../sites/all/modules/imce/tpl/imce-file-list.tpl.php).

Also, some images are too wide and spill over into the right sidebar.

**Drupal Wall.** I tested it, giving only administrators permission to create posts. Authenticated users could post and comment on nodes, and anonymous users could view posts. Also, «Image Style: \_none» appeared below the image when viewing the node with the image.

# Answer
> 0 votes
If you're using CKeditor, you could try the Auto Resize plugin.

> This Plugin provides a small image processor. You can limit the size of images directly on the client without upload images on your server. Big images will be resized automatically on paste.

This would prevent you from ever having the larger images uploaded to the server in the first place by doing the resize automatically in the editor before the node is saved.

# Answer
> 0 votes
you could try one of the following:

In either case, you can set file size limits, and use an image style to style it further on Manage Display

---
Tags: users, media
---


title: Multilevel filter

text:
# Question
Title: Multilevel filter
I would like to make a form where users can choose categories to get to a node. For example they choose a magazines category (science, drupal, mechanics ....) and then publication year and then publication months.

Is it possible to do this with Views or Views Dynamic Fields but allow users to choose let's say Drupal category in magazines and then get a list of publication years available for this category only?

# Answer
> 0 votes
See this long discussion on a similar situation - there are a number of options available depending on your specific needs, including the module Views Dependant Filter. Here is an excerpt from the project page of this module:

> Allows the presence of exposed filters on a view to be controlled by values in another exposed filter. Dependent filters are hidden when not relevant, and their values are not considered when the exposed form is submitted.

The module is compatible with both the Views basic and the Better Exposed Filters form plugins.

---
Tags: views
---


# Question
Title: How can classes be removed from panel panes?
Is there a way to remove the default 'panel-pane' classes, without creating hundreds of templates for different entities, and while still keeping the option of adding custom classes to panes?

# Answer
> 1 votes
By admin panel. When you edit a panel page, click on a cog of the pane that does not need styles. Check styles. Choose no styles. There few options. I do not remember exactly how it is called. It exists there. Check it ...

---
Tags: theming, panels
---


title: Register entity type as a group

text:
# Question
Title: Register entity type as a group
Is it possible to programmatically register a custom entity type as an Organic Groups group? I know I can add a group field to the entity type using the UI, but I would like to register the entity type as a group in the module code. Users should be able to add such an entity and then these entities should automatically be a group and the checkbox should be hidden from the administration form.

Of course I could 'check' the checkbox and hide it by altering $form and $form\_state, but I feel it is a better practice to register it as group in the entity type definition, if possible at all.

# Answer
To register content type grammatically you can by code and by the module - features. But I do not see a reason why you need to create it problematically.
> 0 votes

---
Tags: organic-groups
---


title: Theme webform using custom module

text:
# Question
Title: Theme webform using custom module
I know I could easily theme a webform using the webform-form.tpl template.

However, I want to do this on the module level where the tpl is located inside the custom module folder or coded directly into the .module file?

I tried looking in to these hooks and nothing seems appropriate for my need: http://drupalcontrib.org/api/drupal/contributions!webform!webform.api.php/group/webform\_hooks/7

# Answer
> 0 votes
I guess you can put near the file your\_module.module. Also your can put it into a nested folder. Keep attention: webform-form.tpl.php and that template engine is invoked at the last moment. It overloads all module templates.

---
Tags: hooks, webforms
---


# Question
Title: Customizing form for product attributes and features?
I'm trying to create a crowdfunding site using Ubercart. However, Ubercart has recently shown a certain lack of flexibility when it comes to how it interacts with my custom content types.

I feel that the content type "research project" should not have an SKU that should be set by the project creator, and there is currently no way to set the project goals if one is merely a user and not an admin, as the project goals and deadlines are features, not attributes.

The problem, for me, is that I cannot figure out how I am to change the way in which attributes and features can be changed by privileged users, and I am not sure how to automatically set an attribute (e.g. programmatically creating IDs to put in the SKU field).

Thanks in advance. :-)

# Answer
I am not an expert as I am going through a learning curve with Drupal myself, however, I do have database experience and started using Ubercart myself.

As to your question on auto-created SKU, I think as a learner you are complicating things, unless you are looking into a huge and fast growing database for which you want to create auto SKU, which serves for Stock Keeping Unit. There is a modul Commerce AutoSKU.

As a method to setting up your "research project" implementer 'Role', you can create a form (e.g. Project Form), allowing the enduser to Name (Title) the project, but ID to that project can be in incremental order assigned by the table (project\_id, auto\_increment). You can allow access to that specific form to the persons implementing the research projects.

As to making use of Ubercart's default system and its capability to advanced features such as customizing methods, I find there is quite the flexibility as to adjusting your own custom forms and assigning fields with the 'Hook System'. It is a steep learning curve, I found.

I have been following the following videos. The presenter is quite fast, but I found his instructions helped me to understand my capability. It is a youtube video series consisting of 10 videos (15-20 mins long each).

Creating an E-commerce Site Using Ubercart

Sorry that I cannot help you further, but I hope I am able to get you one step closer to your project.
> 0 votes

---
Tags: 7, ubercart
---


# Question
Title: Is there a module that would allow me to reorganize the way fields are displayed for a content type form?
When I create a particular content type, Drupal generates a form for me with all the appropriate data entry fields.

However, the form is not particularly attractive: all the fields are displayed one below the other, but in some cases I would like to be able to display fields side by side, for example.

Does anyone know of a module which would allow me to take control of the way fields for data entry are displayed? I am thinking of something like Display Suite, but for forms.

# Answer
The best way to do that is using Display Suite module.

> Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files.
> 1 votes

# Answer
you can either use css to override the default behaviour, or adjust the css prior to rendering via hook\_form\_alter(), but simple css is the far simpler approach.
> 0 votes

---
Tags: forms
---


title: Rate widget in panels not working

text:
# Question
Title: Rate widget in panels not working
I'm using the votingapi and rate modules but I have some issues with those modules and panels.

I'm using panels to render the node view. I added content using node \> Rate widget. Everything looks fine viewing the node, even if I use the rate widget in the node.

The problem comes when I refresh the page. The rating is not anymore in the widget. That's weird because the value of the rating is stored in the votingapi\_vote table, even if I show the widget using views it displays the correct rating, but not with panels.

What I'm doing wrong? Thanks!

# Answer
> 0 votes
I just found the answer. The problem occurs when the option "Use source translation" is checked in the Rate configuration section. Here is a patch to solve the problem source translation option on untranslated nodes causes 0 votes display

---
Tags: panels, rating
---


title: How to add edit button in content type?

text:
# Question
Title: How to add edit button in content type?
I am new to drupal and I was adding a button for editing the data from database. but when I am adding edit button using add content type then this error message is showing to me.Please help me to guide how to add buttons and relate them to database.

# Answer
> 1 votes
You actually need to add the edit button in a node. well, first you need to get the node ID, create `template.php` and add this function :

```
function YOUR-THEME_preprocess_node(&$variables)
{
    if (isset($variables['node']))
    {
         $variables['id'] = $variables['node']->nid;
    }
}

```

in this way the node id will be saved in the `$id` variable inside the node template file. if you want to use the default `node.tpl.php` copy this file from `modules/system/node.tpl.php`. now add this code where ever you want in the new copied `node.tpl.php`

```
<?php
    global $base_url;
?>
<a href="<?php print $base_url;?>/node/<?php print $id;?>/edit">Edit the Content! </a>

```

if you suggest any theme hook (theme the node page) no difference does it make, use the above code, the link always will be

```
"<?php print $base_url;?>/node/<?php print $id;?>/edit"

```

Good luck

---
Tags: views, 7
---


# Question
Title: Send e-mail after entityform submission using field from referncing node
I have a content type called contact page and several entity forms. The content type contact page has two fields on it one entityreference field that is used to reference an entityform and the other a text field used to store an e-mail address.

If the user selects an entity form then when the contact page is rendered so is the referenced entityform. When a user submits and entityform I would like to send an email to the email address supplied on the contact page.

I've been looking at rules but I am struggling to find out where I can load fields from the referencing entity so that I can use the email address on the contact page once an entityform is submitted.

# Answer
> 0 votes
First you have to add a condition "this entity has the field". Then you will be able to access this field in the selector in other condition.

---
Tags: rules, entities
---


title: Create a simple quiz

text:
# Question
Title: Create a simple quiz
I have a *videos* content type and I want users, who have watched this video, to answer some questions related to each single video.

How can I create a quiz for each single video node?
I tried the webform module and create a video block but there is a problem. The video will be shown in all forms and I can't insert video for next question. Please help me.

# Answer
> 1 votes
You can always try the Quiz module. I have some experience with it and it mighty suffice for your needs.

Or you can always create your own form with the well-documented FormAPI. You can define your own validation- and submithandlers. Very, véry cool features.
What you can do is create a custom block, and fill it up with your own form.

Depending on your experience level (and time), you can one of above options...
Good luck!

---
Tags: webforms
---


title: changing unicode characters in a module

text:
# Question
Title: changing unicode characters in a module
There are hundreds of records in a database that are in `windows-1256` charset, I want to read these data and convert them to `utf8` then insert them in a new table, to read these data I need to change the MySQL unicode to `latin1` and convert the data to `utf8`. from this link I successfully did this. Now I need to insert these data into database and their charset must be `utf8`, the problem is `$database` variable in `settings.php` have this configuration

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'DB_NAME',
      'username' => 'PASSWORD',
      'password' => 'PASSWORD',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
      'collation' => 'latin1_general_ci',
      'pdo' => array(
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES latin1",
      )
    ),
  ),
);

```

and in `database/mysql/database.inc` line 57 changed to this:

```
if (!empty($connection_options['collation'])) {
  $this->exec('SET NAMES latin1 COLLATE ' . $connection_options['collation']);
}

```

so because of this new database configuration, insertion the converted records (to `utf8`) doesn't provide the desire result (because MySQL is `latin1` now), I need to reset the database configuration to its origin just before inserting the data. how do I can do this?

---

UPDATE:

the only solution I have found so far, is to create another database in `utf8` and using external connection move the data into there !!!

# Answer
> 1 votes
1) run query `ALTER DATABASE DB_NAME DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci` on your data base

2) change line

> 'collation' =\> 'latin1\_general\_ci'

in settings.php to

> 'collation' =\> 'utf8\_general\_ci'

and line

> PDO::MYSQL\_ATTR\_INIT\_COMMAND =\> "SET NAMES latin1"

to

> PDO::MYSQL\_ATTR\_INIT\_COMMAND =\> "SET NAMES utf8"

---
Tags: database, installation, configuration
---


# Question
Title: Drupal load form with ajax callback in Bootstrap modal
I need to load a form into a 'bootstrap modal dialog' which will submit data via ajax callback to callback function.

The form display properly when the modal dialog is launched:

```
<a data-toggle='modal' href='?q=document/share' data-target='#Modalshare' class='ModalTrigger'>
 <div class='' style='float:right;'><span class=''><span title='' class='glyphicon glyphicon-share-alt'></span></span></div>
<a/>

```

The menu 'document/share call the function 'modal\_share()' that display the modal content

```
<div>...
content
...<div>

```

Within this function modal\_share(), a form is called for render:

```
function modal_share($fid) {

$f = drupal_get_form('modal_share_form',$fid);
....
....
echo <div> .... ".drupal_render($f) .".....</div>

}

```

So far so good and the modal is correctly output with the form 'modal\_share\_form' as per below structure:

```
function modal_share_form($form,&$form_state,$fid) {
form['share_list'] = array(
  '#type' => 'select',
  '#multiple' => TRUE,
  '#options' => $option ,
  '#title' => t(""),
  '#description' => "",
  '#required' => false,
  '#default_value' => $default

);

$form['share'] = array (
        '#type' => 'button',
        '#value' => "<span class='glyphicon glyphicon-share-alt'></span><span id=''> ".t('record')."</span>",
        '#ajax' => array(
          'callback' => "modal_share_form_submit",
          'wrapper' => 'shareMessage',
          'effect' => 'fade',
          'method'=>'html'
        ),

        '#id' => 'modalsharebutton',
);
return $form;
}

```

Now the problem is the the #ajax function in the button is not rendered by drupal as it should.

the html rendering is:

```
<button id="modalsharebutton" class="btn btn-primary form-submit" type="button" value="<span class='glyphicon glyphicon-share-alt'></span><span id=''>record</span>" name="op">

```

without the "ajax-processed" class attached

The thing is that if I load the form on a main page ajax function is rendered properly.

So my conclusion is that when building the form for modal, it is not going through the proper ajax build process...

But I can't see the solution.

Thanks for help.

# Answer
I solved this issue differently by adding '#attribute' with event...

```
$form['share'] = array(
        '#type' => 'button',
        '#value' => "<span class='glyphicon glyphicon-share-alt'></span><span id=''> " . t('Record') . "</span>",
        '#ajax' => array(
          'callback' => "modal_share_form_submit",
          'wrapper' => 'shareMessage',
          'effect' => 'fade',
          'method' => 'html'
        ),

        '#id' => 'modalsharebutton',
        '#attributes' => array('onclick' => "share_submit($fid);"),

);

```

Thank you.
> 1 votes

# Answer
For me seems like parsed html is quite broken.

Button markup should be something similar to record Drupal input type button will not work as expected. You could try markup. Maybe it will work out. I would use input type submit and then style it as needed.
> -1 votes

---
Tags: forms, ajax, javascript
---


# Question
Title: How to show a view with 2 columns on the front page?
I need in the front page on my website to show a view with two columns : the left column will show the two latest content from a category, and the same for the right column.

How can I achieve this?

# Answer
There are many ways to do this:

1. Create a block for each of your views, then add the blocks to the content area and select to show on front only (all done via block UI), and set it side by side via CSS.
2. Create a content type for the front page. Then create a new instance of that content type. Run it through panels and choose two column layout, then add views of your liking to the left and right panel.
3. Create a content type for the front page. Manage the display of this content type via Display Suite and use two column layout. Add a dynamic field for each of the left and right columns, and set the dynamic field to display a view of your liking.
4. Implement hook\_menu\_alter for the front page in a custom module. Return the output of 2 views\_embed\_view() calls wrapped in HTML for the columns, or in a render array that will suit your layout.
5. Create a content type for the front page or use an existing type.
Then create a new instance of that content type. Note the path of
this content (node/ID). In configuration - site information, set it as the front page. Edit this content type's body element, and using the PHP filter embed the views with calls to views\_embed\_view().

Methods 2 and 3 are in my opinion preferable, with method 5 the least preferable method. Method 1 is perhaps the easiest.
> 1 votes

---
Tags: 7, views
---


title: Customisable Tabbed Content

text:
# Question
Title: Customisable Tabbed Content
Hi guys i'm trying to create a restaurant menu like below:

I've created a 'Venues' content type, in which it contain the usual Title, Description, Image and another Taxonomy field for Category (Type of Restaurant).

At the bottom i'd like a tabbed menu like the image above. Just not sure how I can go about creating it. Ideally i'd like:

* Let the user create up to 4 or 5 tabs
* Each tab to have a title (Which is displayed in the section and on the tabs)
* Each tab to have X amount of items (Name, Description Price)

Not sure if there's a module that helps with this or if I should use Views somehow or what fields I should add to the content type. Totally baffled.

In my static HTML prototype, I used jQuery UI to build the tabs, will I need to use that again here or again, is there a module that can help with that?

Thanks for your help :)

# Answer
You can see the jQuery Tabs Field module for this.

> jQuery Tabs Field module allows you to create jQuery Tabs field. Using this you can add upto 7 tabs with tab title and tab body in a node. After saving node, the module will display all these 7 tabs as jQuery tabs.
> 0 votes

---
Tags: nodes, javascript
---


# Question
Title: right sidebar doesn't shrink in zen responsive theme
I have a Zen 7.x.5.x Responsive subtheme with Right sidebar...

I know, I am new with all this responsiveness staff; but - I think the right sidebar doesn't shrink when I resize my browser....it just moves inside, staying about the same size....or may be I don't understand something....

so, I have made up my content area - it consists now from 2 blocks floating left and right; I put them width proportionally to content area : 67% and 33% - they resize, when I resize browser....but sidebar looks too big and not shrinking; even it seems to be set in percents from page's 1200px.....

# Answer
Inspect the right sidebar element in your browser. Then select

```
<section class="region region-sidebar-second column sidebar">

```

in the DOM and it should give you the width as a percentage. This is proof that the sidebar is responsive. Now drag the browser window smaller and observe the media query changing at breakpoints and the percentage should also change. At mobile breakpoint the sidebars should be 100%.

Now look in your sub theme's sass/layouts folder for the file \_responsive.scss

You will see snippets like this

```
$zen-column-count: 3;
...

#content {
          @include zen-grid-item(2, 1);
        }

        /* Span 1 column, starting in 3rd column from left. */
        .region-sidebar-second {
          @include zen-grid-item(1, 3);
        }

```

This is where the sidebar width is set in relation to the content area. In the above case it is 1 column wide starting at column 3. As there are a total of 3 columns it is 1/3 the total width.

You can change it here if you have compass set up and working and properly watching the folder for changes.
> 0 votes

---
Tags: theming
---


# Question
Title: Drupal 7: How may I customize the user profile? And how do I add to it profile2 fields?
The profile under user/n will only show the profile picture and the username.

I´m using an Omega subtheme. I´ve copied and pasted the default user-profile.tpl.php file, deleted everything and added these two lines, hoping that one of them would work:

```
print drupal_render(field_view_field('profile2', $profile['main'], 'field_nombrecompleto1'));
print $field_profile_nombre_completo['value'];

```

The second line refers to the original core profile field, and the first one refers to the imported field (I´ve imported using the migrate module in D6, before I´ve upgraded to D7).

None of the fields gets printed out. I´ve added this at the top of the template:

```
print "<pre>";
$vars = get_defined_vars();
print_r($vars);
print "</pre>";

```

And nothing happend. So I´ve added that code to the top of my page.tpl file, and it appeared the whole list of variables. At the very top it prints:

```
[template_file] => sites/all/themes/liga/templates/page.tpl.php

```

And at some points it actually recognizes the (core profile) field:

```
    [content] => Array
                                (
                                    [content] => Array
                                        (
                                            [system_main] => Array
                                                (
                                                    [field_profile_nombre_completo] => Array
                                                        (
                                                            [#theme] => field
                                                            [#weight] => 0
                                                            [#title] => Apellido y Nombres
                                                            [#access] => 1
                                                            [#label_display] => hidden
                                                            [#view_mode] => full
                                                            [#language] => und
                                                            [#field_name] => field_profile_nombre_completo
                                                            [#field_type] => text
...

```

I´ve then deleted everything at my user-profile template and printed just XXXXXX and it didn´t printed out. It stills print the profile image and the username.

**Now I have two issues here: How to customize the profile template (user-profile.tpl.php) because it´s not recognizing the file inside my theme folder, and how to print profile2 fields information inside the user profile.**

Hope anyone can give me some insight or clue. THANKS!!!

Rosamunda

# Answer
I don´t know if I should respond to my own question, because after two days not only I didn´t received any answer (which isn´t bad in itself, because nobody "has" to answer), but I´ve received a minus one point, without ANY explanation at all, wich I think is rude.

Anyway, as I´ve found by myself the problem, and other people maybe has the same issue, and as a good citizen, I shall say that the it was the "Display Suite" module.

**That module, wich is installed in more than 45.400 sites, was the only reason my Drupal installation didn´t recognized the user-profile.tpl.php file.**

I´m going to read more carefully DS readme, tutorials ans screencasts out there because it´s a more complex module than I thought it was. But people should know that it does that (at least right out of the box, in a D7 installation with some core profile fields, Profile2 installed, and without any tweaks in the default configuration).

Cheers.

Rosamunda
> 10 votes

# Answer
you should copy core user\_profile.tpl.php file to sites/all/theme/template. now its work perfectly. and you want to print profil2 field then you can find in $user\_profile array. $user\_profile array print all the data that are related to users.
> 2 votes

---
Tags: 7, theming, users
---


title: Search additional user fields?

text:
# Question
Title: Search additional user fields?
When using the search form, by default Drupal searches Content nodes, and there's a toggle to search Users (`search/node` vs. `search/user`). But the `search/user` appears to only search the default fields for the User nodes (username and email). I've added additional fields (Admin \> Config \> People \> Manage Fields) to User nodes, but those don't get searched. How can I make the default `search/user` find users by those additional fields?

# Answer
> 1 votes
As far as I know, the easiest way to do this is with views. You can set up a user view with exposed filters for any user field that you need to search. If you want to get a link to your your view on the search page form then, a form alter in a custom module would do it. Obviously make sure your view has a page with a proper path setup. search/your\_view etc will work.

Here is a quick example of adding a custom markup field to the search form in **drupal 7**.

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

 if ($form_id == 'search_form') {

   $form['usercustomsearchlink'] = array(
  '#type' => 'markup',
  '#markup' => '<a href="http://YOURSITE.com/search/YOURVIEWNAME">Search User Fields</a> ',
  '#weight' => 1,
   );

   }
}

```

That should put a link underneath the search box on the form (after a cache clear). However, I havent been able to figure out how to make it appear only on search/user pages yet so, that link will appear on all search forms.

# Answer
> 0 votes
I recommend to use Search by Page module. You can search user fields by adding which roles are to be added to index and which role is to be used when doing the indexing. The results are added to the default search page by adding another search tab in addition to "Content" (nodes) and "Users".

This module also has an *API* to help add other things to index. But making user fields searchable can be done with configuration alone via included sub-module.

**Search by Page:**

> This module is an enhancement to the core Drupal search module, which adds a new tab to the core Search page or can also be used in stand-alone mode. The differences between Search by Page and the existing tabs in the core Search module lie in what is indexed for searching and how it is indexed:
>
> * Search by Page indexes the content of your pages as rendered by your theme (Search indexes the default rendering you would have from an unmodified theme).
> * Search by Page allows you to omit content from indexing (such as "database table" node types that should never be viewed as stand-alone content).
> * Search by Page allows you to index non-Node pages, including user profiles, file attachments, and Views.
> * Search by Page is language-aware, so it only shows you results in the current language.
> * Search by Page has multiple search "environments", so you can have different search pages/blocks to search different things.
>
> Search by Page does not know what the pages of your site are, so it doesn't index anything by itself. **You will need to enable and configure at least one sub-module that lets you add paths to the search index, in order for this module to do anything.**

---
Tags: 7, users, search
---


title: Debugging custom database queries

text:
# Question
Title: Debugging custom database queries
Is there a convenient way to ask a particular database object to print its query?

Every now and then, I write a DBTNG db\_op() in a module, and far to often, I don't quite get the queries right.

I know that devel can output the query log, but that's *all* queries, which, in this type of situation, is a problem more often than not.

I want to do

```
$result = db_select('node', 'n')->fields('n')->execute();
dpm($result->queryWithParameters);
dpm($result->finalQuery);

```

# Answer
There is a `dpq()` function in the devel module which seems to fulfill this need.

> Print a SQL string from a DBTNG Query object. Includes quoted arguments.
> 13 votes

# Answer
I know this is an old question but hopefully this answer might be useful to other people: basically Drupal core has its own DatabaseLog class. You could use it in cases where you don't have Devel module available (like maybe production debugging of slow queries?):

```
Database::startLog('my_custom_key');
// do some SQL operations here...
// print the queries
print_r(Database::getLog('my_custom_key'));

```
> 2 votes

---
Tags: database
---


# Question
Title: Best way to create outbound link with node field content
I am looking for the best way to create a button that I attach to each node's page that directs to an outside site. The url of the button will information that is in one of the node's fields. I know this should be easy, but I am still new at drupal....

Thanks in advance

//btw, it's drupal 7.

# Answer
There are many ways to do it, depending on the field type you are using. The easiest is with the Link or Url field type (link is better as url field is lightweight). You can just set the display formatter correctly, and style it in CSS as a button. If it is in a text field, then you have to output the field in anchor tags setting it as the href attribute value. You can do it in a preprocess node template function in your theme's template file where you rewrite or replace the field value to be an anchor or if you are more of a site builder than a coder then you should look at Display Suite module and use the code field option.

Another easy option is to override the node.tpl.php file for your node type (use the proper override in the naming) and in the template file output the link using the url() function. Depending on the order of your fields you might have to then also hide the field if the content variable is rendered before you need the anchor.

My personal preference is to use Display Suite as it is such a versatile module.
> 1 votes

# Answer
I would use the Link module https://www.drupal.org/project/link

If the text displayed on the button is always the same, you may want to change the default value displayed in the field settings for that content type. If you need the link to look more like a button use CSS.

Happy Drupaling :)
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Is there incremental deployment module for Drupal 7?
I can find Deploy module for Drupal 7 that achieves full deployment. Also, I can find Incremental Deploy module for Drupal 6. Is there incremental deployment module for Drupal 7? or even work around that achieves incremental deployment for Drupal 7?

# Answer
> 0 votes
There is no Drupal 7 version of Incremental Deploy. In fact, the Drupal 6 version is no longer supported.

You have several options to duplicate the functionality. The closest match is probably Data Export Import - https://www.drupal.org/project/data\_export\_import

Other options are the Migrate module - https://www.drupal.org/project/migrate or migrate\_d2d - https://www.drupal.org/project/migrate\_d2d

Modules for migrating specific content types are also available. For example, for taxonomies, Taxonomy CSV import/export - https://www.drupal.org/project/taxonomy\_csv

# Answer
> 0 votes
Deployment module for Drupal 7 can be combined with Rules to create setup similar to Incremental Deploy. See https://www.drupal.org/node/1406136 for more info about that (you'll neeed to scroll down a bit).

---
Tags: 7, deployment
---