# Question
Title: Why is the Devel block displaying the Performance, Execute PHP and Switch User blocks?
My Devel block is displaying the Performance, Switch Users and Execute PHP blocks as well in the sidebar, making it very unsightly and bloated as well.

I can't see what I could have done to cause that and wonder if it is due to some interaction with some third-party module.

What could have caused that?

EDIT: I hve added the code for the block to low. There seems to a lot of `admin-pane-xxxx` classes and IDs there, and I suspect it has something to do with Admin menu. I have also checked devel on other installations, and they don't display this behaviour. I have asked a related question regarding how to locate where code for a particular block is being generated.

```
<div class="block block-admin contextual-links-region collapsiblock-processed admin-processed" id="block-admin-devel">

    <h2 class="title collapsiblock"><a role="link" href="#">Devel</a></h2>
  <div class="contextual-links-wrapper contextual-links-processed"><a href="#" class="contextual-links-trigger">Configure</a><ul class="contextual-links"><li class="block-configure first last"><a href="/admin/structure/block/manage/admin/devel/configure?destination=admin/structure/block">Configure block</a></li>
</ul></div>
  <div class="content">
    <form accept-charset="UTF-8" id="admin-block-devel-form" method="post" action="/admin/structure/block"><div><div class="admin-panes clearfix  processed">

          <div class="admin-pane admin-pane-active admin-pane-performance">
        <h2 class="admin-pane-title"><a class="admin-pane-active active" href="/admin/structure/block#admin-pane-performance">Performance</a></h2>
        <div class="admin-pane-content clearfix"><div class="item-list"><ul><li class="dev-timer first"><div class="dev-info"></div></li>
<li class="dev-memory-usage last"><div class="dev-info"></div></li>
</ul></div></div>
      </div>
                <div class="admin-pane  admin-pane-switch_user">
        <h2 class="admin-pane-title"><a class=" active" href="/admin/structure/block#admin-pane-switch_user">Switch user</a></h2>
        <div class="admin-pane-content clearfix"><ul class="links clearfix"><li class="1 first"><a title="This user can switch back." href="/devel/switch/admin?destination=admin/structure/block&token=D1XQMmu5YkZ3s5fmg1HjPNbpJEWdfz9BkeIjQPjFqDg"><strong><em class="placeholder">admin</em></strong></a></li>
<li class="3"><a title="Caution: this user will be unable to switch back." href="/devel/switch/seetop?destination=admin/structure/block&token=4zXMi8I2marB9l1FMwGzbC9845NRnmLqEFe_7pC4HGE">seetop</a></li>
<li class="2 last"><a title="Caution: this user will be unable to switch back." href="/devel/switch/c3pio?destination=admin/structure/block&token=FPTt2bcUUJr8YYRwD4mcoliAWNijuZ79sqZaFoz3Hgs">c3pio</a></li>
</ul><div class="form-item form-type-textfield form-item-username" role="application">
 <input type="text" class="form-text form-autocomplete" maxlength="60" size="16" value="" name="username" id="edit-username" autocomplete="OFF" aria-autocomplete="list"><input type="hidden" class="autocomplete autocomplete-processed" disabled="disabled" value="https://cc5.rca2.net/user/autocomplete" id="edit-username-autocomplete">
<div class="description">Enter username</div>
<span aria-live="assertive" class="element-invisible" id="edit-username-autocomplete-aria-live"></span></div>
<input type="submit" class="form-submit" value="Switch" name="op" id="edit-submit--3"></div>
      </div>
                <div class="admin-pane  admin-pane-execute">
        <h2 class="admin-pane-title"><a class=" active" href="/admin/structure/block#admin-pane-execute">Execute PHP</a></h2>
        <div class="admin-pane-content clearfix"><div class="form-item form-type-textarea form-item-code">
  <label for="edit-code">PHP code to execute </label>
 <div class="form-textarea-wrapper resizable textarea-processed resizable-textarea"><textarea class="form-textarea" rows="20" cols="60" name="code" id="edit-code"></textarea><div class="grippie"></div></div>
<div class="description">Enter some code. Do not use <code><?php ?></code> tags.</div>
</div>
<input type="submit" class="form-submit" value="Execute" name="op" id="edit-op"></div>
      </div>
                <div class="admin-pane  admin-pane-menu">
        <h2 class="admin-pane-title"><a class=" active" href="/admin/structure/block#admin-pane-menu">Other tools</a></h2>
        <div class="admin-pane-content clearfix"><ul class="menu"><ul class="menu"><li class="first leaf"><a title="Helper functions, pages, and blocks to assist Drupal developers. The devel blocks can be managed via the block administration page." href="/devel/settings">Devel settings</a></li>
<li class="leaf"><a title="Clear the CSS cache and all database cache tables which store page, node, theme and variable caches." href="/devel/cache/clear?destination=admin/structure/block">Empty cache</a></li>
<li class="leaf"><a title="View entity information across the whole site." href="/devel/entity/info">Entity info</a></li>
<li class="leaf"><a title="Execute some PHP code" href="/devel/php">Execute PHP Code</a></li>
<li class="leaf"><a title="View fields information across the whole site." href="/devel/field/info">Field info</a></li>
<li class="leaf"><a title="View a list of currently defined user functions with documentation links." href="/devel/reference">Function reference</a></li>
<li class="leaf"><a title="View the active form/render elements for this site." href="/devel/elements">Hook_elements()</a></li>
<li class="leaf"><a title="Details about a given menu item." href="/devel/menu/item?path=admin/structure/block">Menu item</a></li>
<li class="leaf"><a title="View your server's PHP configuration" href="/devel/phpinfo">PHPinfo()</a></li>
<li class="leaf"><a title="Rebuild menu based on hook_menu() and revert any custom changes. All menu items return to their default settings." href="/devel/menu/reset?destination=admin/structure/block">Rebuild menus</a></li>
<li class="leaf"><a title="Run hook_uninstall() and then hook_install() for a given module." href="/devel/reinstall?destination=admin/structure/block">Reinstall modules</a></li>
<li class="leaf"><a href="/devel/run-cron">Run cron</a></li>
<li class="leaf"><a title="List the contents of $_SESSION." href="/devel/session">Session viewer</a></li>
<li class="leaf"><a title="View a list of available theme functions across the whole site." href="/devel/theme/registry">Theme registry</a></li>
<li class="last leaf"><a title="Edit and delete site variables." href="/devel/variable?destination=admin/structure/block">Variable editor</a></li>
</ul></ul></div>
      </div>

  </div>
<input type="hidden" value="form-9uJFBQ4hH879iRN_QBUrp46oNTDoops6Xvd5qoDSHkw" name="form_build_id">
<input type="hidden" value="hAmptoPteO_NNJXwFsRyruXJkKuh5LEmMFGxvtEqAkQ" name="form_token">
<input type="hidden" value="admin_block_devel_form" name="form_id">
</div></form>  </div>
</div>

```

# Answer
It turns out that the Admin module adds an additional `enhanced` block that combines those blocks into one, which is called `Devel` and I was activating it instead of using the Devel modules own blocks
> 0 votes

# Answer
Go to Structure \>\> Blocks and disable those blocks from your sidebar region
> 0 votes

---
Tags: 7, debugging, blocks
---


# Question
Title: How to display node's taxonomy child items in node using views for multiple parents
I have a vocabulary with child terms

* term
* -child\_term
* -child\_term\_1
* -child\_term\_2
* -term\_1
* -child\_term
* -child\_term\_1
* -child\_term\_2

Nodes have multiple parent terms assigned.

The goal is to display all parent and child terms in the exact node using views field.

I tried to implement it using taxonomy tree view with contextual filter (taxonomy term ID from the URL), but it displays only child terms for the first (one) parent item of the node.

Even view's "Preview with contextual filters" does not understand multiple contextual filter values with a "/"

How can I do this?

# Answer
The goal was to display child items for multiple taxonomy terms of the node in a node's field using views.

Solution:

---

1. Create content type with:

1. Taxonomy term field (multiple values) - it's for parent items
    2. Views field - it's for displaying child items for ALL parents
2. Make standard taxonomy tree view with ajacency model (search google)

1. Add a contextual filter with parent term ID
        1. Provide default value
        2. Taxonomy term ID from the URL
        3. filter to items that share any term
        4. When the filter value IS available or a default is provided
            1. Specify validation criteria - taxonomy term ID
            2. Filter value type - Ternm IDs separated by , or +
3. Edit view field of previously created content type

1. Select the view created as a default value for this field
    2. From placeholder list select \[node:field\_bla\_bla\] (that's taxonomy parent field in the node) as an argument passed to default value

---
> 1 votes

---
Tags: views, entities, taxonomy-terms
---


# Question
Title: Links in view - wrong language selection
Ok, I'm not sure where should I go with this problem, so forgive me if this is not the exactly best place for it.

I've created multilanguage site, of course, got many problems, but solved them all - so far. Now, when I launched german version of a site, I realized there's a problem. I have a content type of X, made a view to display a page containing table with all the X content types. Just usual listing. The link to it is in the menu, displaying only for german language. So far all in that version worked fine, but now I see there's a problem.

Content X - link for adding it is on german version only and while adding it, it works fine. But when I'm on my view page, when I click on any title of content X type (which is a link of course) I'm getting redirected to default site language. And it should stay on german version. I can't think of any ideas, so: what is wrong? How can I fix it?

# Answer
> 0 votes
I found the solution here after one day struggling with same issue:

* goto: Home » Administration » Configuration » Regional and language » Languages.
* select the 'DETECTION AND SELECTION' tab.
* Un-check all except 'URL' and 'default'. Keep 'URL' on top of 'default'

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


# Question
Title: Get the taxonomy term field in Views 3 override title
Is it possible to get a taxonomy term field in the title of a view, using the override title in the contextual filters? I know I can get taxonomy fields using relationships, but is there an argument or something similar that I can use in the override title?

I am asking for Drupal 7.

# Answer
I just recently solved this problem by hiding display of the default title in views, adding the field "content all: taxonomy term" in views. Then on the "header" section of views add "global:text area" and select the text format "php code". check "use replacement patterns from the first row". You can click on "replacement patterns" to view all of your tokens. In the text area box paste the code: `<h1>[term_node_tid]</h1>` Your term name should replace the default title.

Hope this helps.
> 2 votes

# Answer
I was able to solve a very similar issue in which I needed to override the view title with a field from the first result.

I used `hook_views_pre_render()` to accomplish this in drupal 7.

```
function tag_views_pre_render(&$view) {
  if( $view->name == 'flex' ){
    if ( count($view->result) ){
      $view->build_info['title'] = $view->result[0]->node_title;
    }
  }
}

```
> 4 votes

# Answer
the only solution I found (thanks to FatGuyLaughing: http://drupal.org/node/365418#comment-4284154) was the following:

```
function MYMODULE_views_pre_build(&$view) {
  if ($view->name == 'view_machine_name') {
    if (is_numeric(arg(1)) && arg(1) > 0) {
      $term = taxonomy_term_load(arg(1));
      if ($term) {
        $view->display['default']->handler->options['title'] .= ' - ' . $term->name;
      }
    }
  }
}

```
> 2 votes

# Answer
If you use contextual filter "Content: Has taxonomy term ID (with depth)" and title overriding, just set "%1" and the title (aka name) of the term is set as title of the view.

Note that this doens´t work with Filter by Field "Content: Vocab XYZ (field\_vocab\_xyz)". In this case the term ID is set as title.
> 0 votes

---
Tags: 7, views, taxonomy-terms
---


# Question
Title: Show exposed filter entry with match number
I want to have some view filter like this one for example.

I want a list of option \[a select..\] with the number of results they provide.

Can I do this in some way?

# Answer
It can be achieved with the help of hook\_form\_alter().

You just need to override the `$form['type']['#options']`

**Example**

An exposed filter with content types and the number of nodes attached to each select option.

```
/**
 * Implements hook_form_alter
 */
function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch($form['#id']) {
    case 'views-exposed-form-[YOUR-VIEW-NAME]-page':
      foreach ($form['type']['#options'] as $option => $name) {
        if ($option != 'All') {
          $query = "SELECT COUNT(*) amount FROM {node} n "."WHERE n.type = :type AND n.status=1";
          $result = db_query($query, array(':type' => $option))->fetch();
          $name.= ' (' . $result->amount . ')';
          $form['type']['#options'][$option] = $name;
        }
      }
    break;
  }
}

```

If you don't want to run the query every time when the filter is being displayed, then you need to create a variable with these numbers. The query might be then performed only once, during your module installation, and the variable would be updated only when the node will be created, updated or deleted.

**An example with the custom variable**

Custom function to create or update our custom variable.

```
function update_node_numbers() {
  $node_numbers = array();
  $node_types = node_type_get_types();
  foreach ($node_types as $type => $object) {
    $query = "SELECT COUNT(*) amount FROM {node} n "."WHERE n.type = :type AND n.status=1";
    $result = db_query($query, array(':type' => $object->type))->fetch();
    $node_numbers[$object->type] = $result->amount;
  }
  // set variable
  variable_set('node_numbers', $node_numbers);
}

```

The function should be fired only during administrative tasks (install module, create, update or delete node)

```
/**
 * Implements hook_install.
 */
function YOURMODULE_install() {
  update_node_numbers();
}

/**
 * Implements hook_uninstall.
 */
function YOURMODULE_uninstall() {
  variable_del('node_numbers');
}

/**
 * Implements hook_node_insert.
 */
function YOURMODULE_node_insert($node) {
  update_node_numbers();
}

/**
 * Implements hook_node_update.
 */
function YOURMODULE_node_update($node) {
  update_node_numbers();
}

/**
 * Implements hook_node_delete.
 */
function YOURMODULE_node_delete($node) {
  update_node_numbers();
}

```

Now we can alter the form with the help of our custom variable, without using any query.

```
/**
 * Implements hook_form_alter.
 */
function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch($form['#id']) {
    case 'views-exposed-form-[YOUR-VIEW-NAME]-[DISPLAY-ID]':
      $node_numbers = variable_get('node_numbers');
      foreach ($form['type']['#options'] as $option => $name) {
        if ($option != 'All') {
          // some options may have been just created.
          if (!isset($node_numbers[$option])) {
            $node_numbers[$option] = 0;
          }
          $name.= ' (' . $node_numbers[$option] . ')';
          $form['type']['#options'][$option] = $name;
        }
      }
    break;
  }
}

```
> 1 votes

# Answer
It depends on your usecase.

* Count queries always have heavy impact on performance. But in this usecase it seems to be the right direction.
* If you want to speed this one up, cache the view and its results. But only if the results do not change all the time.
* If you have the actual options of each category in an array, you can make a count(); of that array.
* Create a custom variable (a better table field in db), where the count is always updated when anything changes. And then just query that field with a JOIN. Bad: you have to tell views about your new field (hook\_views\_data).
> 0 votes

---
Tags: views
---


# Question
Title: Undoing Content Changes Made with Admin Panel
I administer an existing site, and accidentally changed some of the formatting on our homepage. In the past, I have been able to press "back" on my browser to undo changes, but for some reason it's not working this time. Does anyone know of a way I can "undo" changes I made to the website under the admin panel?

# Answer
> 2 votes
Your ability to undo changes depends on what you changed and how your site was set up. Some components of Drupal can be reverted, like if you have revisions enabled on your nodes. A more advanced set-up may have "Features" which allow you to revert all sorts of things. It really depends.

For most changes you make in the admin panel, you need to find the setting you adjusted and change it back to its original value. It would help if you described your issue in more detail, like what settings were being adjusted and what version of Drupal you were using.

---
Tags: 6, users
---


# Question
Title: Store the values of a views exposed filter Form
I have build a form using the Form API that adds a checkbox to every row in my custom view (the view page can be found here: http://goo.gl/Pg6Ja7). I want this form to store the values even after I change the exposed filter of the view or change the view page.

I was thinking to create a new submit button that will store the values on the current page, but I don't know how to do that, I googled the whole day. Or maybe some JavaScript ?

I added the View form with a handler, here is the simple code I wrote for it:

```
/**
   * @file
   *
   * A Views' field handler for adding a checkbox.
   *
   */
class files_download_links_mail_field_handler_checkbox  extends views_handler_field {
  function construct() {
    parent::construct();
    $this->additional_fields['nid'] = 'nid';
    //$this->additional_fields['field_file_download_link'] = 'field_file_download_link';

  }

  function query() {
    $this->ensure_my_table();
    $this->add_additional_fields();
  }

  function render($values) {
    // Render a Views form item placeholder.
    // This causes Views to wrap the View in a form.
    // Render a Views form item placeholder.
    return '<!--form-item-' . $this->options['id'] . '--' . $this->view->row_index . '-->';
  }

  function views_form(&$form, &$form_state) {
    // Create a container for our replacements
    $form[$this->options['id']] = array(
      '#type' => 'container',
      '#tree' => TRUE,
    );
    // Iterate over the result and add our new field to the form.
    foreach($this->view->result as $row_index => $row) {
      // Add a checkbox field to the form.
      $form[$this->options['id']][$row_index] = array(
        '#type' => 'checkbox',
      );
    }
  }

   /**
   * Form submit method.
   */
  function views_form_submit($form, &$form_state) {
    // Determine which nodes were selected.
    $selected_items = array();
    // Iterate over the view result.
    foreach($this->view->result as $row_index => $row) {
      if ($form_state['values'][$this->options['id']][$row_index] == 1) {
        $selected_items[$row->{$this->aliases['nid']}] = $form_state['values'][$this->options['id']][$row_index];
      }
    }
    // Grab the nodes
    $nodes = node_load_multiple(array_keys($selected_items));
    dpm($nodes);
  }
}
?>

```

Thanks!

# Answer
> 0 votes
This seems like the perfect scenario for a custom module in my opinion. I know it's possible to get this working based on some light research I did (specifically this web page).

Your solution is using a custom module anyway, best to create the form and hooks and sql in the custom module and remove your dependency on views.

Create your hook\_menu:

```
function MODULE_menu()
{
    $items['PATH'] = array(
        'title'            => t('TITLE'),
        'description'      => t('DESCRIPTION'),
        'page callback'    => 'drupal_get_form',
        'page arguments'   => array('MODULE_form_function'),
        'access arguments' => array('access content'),
        'type'             => MENU_NORMAL_ITEM,
    );

    return $items;
}

```

Create your form function (using the Form API and Database Abstraction Layer):

```
function MODULE_form_function($form, &$form_state)
{
    // handle creation of your form, including sql to replace views.

    return $form;
}

```

Create your validate and submit handlers:

```
function MODULE_form_function_validate(&$form_state)
{
    // handle the validation of your form
}

function MODULE_form_function_submit(&$form_state)
{
    // handle the submission of your form
}

```

This is a much simpler and proven way to accomplish what you are trying to do.

---
Tags: views, forms
---


# Question
Title: Add additional CSS class for particullar field in a node
I'm trying to add additional CSS class to a field after the field is added. But not for all fields of that particullar content type, but only for those, that editor would like to. Like a module **Formatter\_field** lets user to chose the field format - I have an image field and couple of different image formats, which I can chose after I upload an image which formatter\_field.

I cannot find anywhere a solution, how to add additional css class to the same field.

For example:

User uploads an image via image field, using formatter\_field he/she choses image format from image\_cache and then adds CSS class wich adds border. Then adds another image to the same node (as image field is set to "unlimited"), choses different format and adds different CSS class, which gives different border to that image. And all this in one node.

**update:**

In my exact case I want to create a horizontal gallery, where images and texts are shown inline horizontally in such a way, that some of the pictures are bigger, some are smaller and are aligned in different heights and sometimes between those pictures there are text blocks with explanations about the works. Like in on a real gallery wall. :) Would be great that all one gallery is one node as it is easier to edit.

# Answer
You could try theme\_field as well

> Returns HTML for a field.

This is the default theme implementation to display the value of a field. Theme developers who are comfortable with overriding theme functions may do so in order to customize this markup. This function can be overridden with varying levels of specificity. For example, for a field named 'body' displayed on the 'article' content type, any of the following functions will override this default implementation. The first of these functions that exists is used:

1. THEMENAME\_field\_*body*\_article()
2. THEMENAME\_field\__article()
3. THEMENAME\_field\__body()
4. THEMENAME\_field()
> 1 votes

# Answer
Forget my answer about the theme, you have to either hook\_form\_alter() the node-edit form or find your way through Field API in a custom module for starters

Got it, you have to either hack image\_field\_widget\_process() in image core module (really bad idea) or follow this very good answer
> 0 votes

---
Tags: theming, media, entities
---


# Question
Title: Sending webform submissions to email with csv export of submissions
I need help, because I dont know how to create csv file from submissions and send it as attachment in submission mail.

I have form with some field and after sending webform I need to create custom csv in specific format with values from webform and all this send it like attachment of normal submission mail.

Is there some modul for creating csv from webform, or I need to cook my own custom module to create it? Thanks a lot

# Answer
As tenken wrote, Webform module has a function for that, namely webform\_results\_export

Do you really want a single line of CSV e-mailed when a form is submitted, rather than periodic downloads? You could modify your e-mail template to print each value, comma, value, but it wouldn't be an attachment. If you absolutely need an attachment some custom code and/or Rules is the way to go.
> 1 votes

---
Tags: webforms, importing-exporting
---


# Question
Title: Views Slideshow Using Absolute Path to Images
We are using views\_slideshow to display a 3 image slideshow on our homepage. The Style is Slideshow, the Row Style is set to Fields. The Field is: Image attach: Attached images and we are filtering for a specific Node:Type. The Node Type were filtering for has an attached image which is what the slideshow uses.

The problem we are encountering is that the `<img src=""/>` references to the image appear to be absolute URLs so that if you view the site over https:// in Internet Explorer, you get the message about referencing unsecure content on a secure page. (since the URL to the image looks like: `http://www.foo.com/sites/dailyaccess.com/files/images/Banner1.jpg` even though you are viewing the page over https://)

How can we go about correcting this to use a relative URL or display the correct secure/unsecure URL?

# Answer
> 1 votes
Implement hook\_preprocess\_views\_view\_field() or hook\_preprocess\_views\_view\_fields(). In those you should be able to alter anything related to that image field. If the image field happens to be represented as a render array in the hook (assuming you are using Drupal 7), you can also change the theming function to use for that image. Within your own image theming function, you can get the path to the image using file\_create\_url(), which supports https.

If you need a good example of an image theming function, you can look at core's theme\_image(). For a complete list of Views preprocessors, you can look at the views/theme/theme.inc source code.

# Answer
> 1 votes
I've also posted this an an answer to Views to use relative paths for image fields

Add your image to the view (mine is called Image2)

Create a theme file for your image field, see screenshot. (mine is called views-view-field--relative-url-example--page--field-image2.tpl.php and it's bolded). Pick the last one for the most granular themeing possible.

(full size here)

After you have added the theme file to your theme templates (/sites/all/themes/THEME/templates or similar), hit the "Rescan template files" button. Your field template should be bolded now.

Add the following code to your theme file, I removed the comments but you can leave them in if you like:

```
<?php

/**
 * @file
 * This template is used to print a single field in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.
 *
 * When fetching output from the $row, this construct should be used:
 * $data = $row->{$field->field_alias}
 *
 * The above will guarantee that you'll always get the correct data,
 * regardless of any changes in the aliasing that might happen if
 * the view is modified.
 */
?>
<?php

    $url  = file_create_url($row->field_field_image2[0]["raw"]["uri"]);
    $url  = parse_url($url);
    $path = $url['path'];

    print $path;
?>

```

I only printed the path to demonstrate it works so you will need to add the image tag, etc.

Here is my output:

You may need to clear the cache and be sure to **save your view** after you update the theme file.

---
Tags: views, media, javascript
---


# Question
Title: Remove "Delete" in node/edit via hook_form_alter
I need to programmatically remove the Delete button in node edit forms under certain circumstances.

Normally, I'd do this in a hook\_form\_alter using `$form['actions']['delete']['#access'] = FALSE;`.

When I view in dpm(), "delete", however, does not have an "#access" key (though 'Submit' and 'Preview' do). How do I disable 'Delete'

(…and, if you know *why* it wouldn't provide #access, I'm curious about that too).

# Answer
You can use `hook_node_access` instead

e.g:

```
/**
 * Implements hook_node_access().
 */
function MODULE_node_access($node, $op, $account) {

  if ($op == "delete") {
    // If no user object is supplied, the access check is for the current user.
    if (empty($account)) {
      $account = $GLOBALS['user'];
    }
    // You can add your own condition check here...
    return user_access("delete content", $account) ? NODE_ACCESS_ALLOW : NODE_ACCESS_DENY;
  }

  return NODE_ACCESS_IGNORE;

}

```
> 1 votes

---
Tags: forms
---


# Question
Title: Services 3.5 q=system/connect.json 404 (Not Found)
I have code that use JQuery to call services module and login. After Login, I call token through ?q=services/session/token and gets the token of the user. I think that i have got the right token... After that the code calle to ?q=my\_services\_endpoint/system/connect.json and pass through the header the token.

the problem is that i get those lines in the console and no success of course...

> 7dR8Eo0pmiTeMCHLUeneAAQFCONn80NgXnJuNqhrtYw login.js:38
>
> OPTIONS http://{localhost}:8888/drupal2/?q=system/connect.json 404 (Not Found) jquery-1.6.4.min.js:4 POST
>
> POST http://{localhost}:8888/drupal2/?q=system/connect.json 404 (Not Found)

this is the code:

```
   $.ajax({
        url: "http://{localhost}:8888/drupal2/?q=test_test/user/login.json",
        type: 'post',
        data: 'username=' + encodeURIComponent(name) + '&password=' + encodeURIComponent(pass),
        dataType: 'json',
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert('page_login_submit - failed to login');
            console.log(JSON.stringify(XMLHttpRequest));
            console.log(JSON.stringify(textStatus));
            console.log(JSON.stringify(errorThrown));
        },
        success: function(data) {
            $.cookie("sessid", data.sessid);
            $.cookie("session_name", data.sessid);
            // Obtain session token.
            $.ajax({
                url: "http://{localhost}:8888/drupal2/?q=services/session/token",
                type: "get",
                dataType: "text",
                error: function(jqXHR, textStatus, errorThrown) {
                    alert("Didn't got the token");
                },
                success: function(token) {
                    console.log($.cookie("sessid"));
                    console.log(token);
                    // Call system connect with session token.
                    $.ajax({
                        url: 'http://{localhost}:8888/drupal2/?q=test_test/system/connect.json',
                        type: "post",
                        dataType: "json",
                        beforeSend: function(request) {
                            request.setRequestHeader("X-CSRF-Token", token);
                        },
                        error: function(jqXHR, textStatus, errorThrown) {
                            alert(errorThrown);
                        },
                        success: function(data) {
                            alert('Hello user #' + data.user.uid);
                        }
                    });
                }
            });

```

# Answer
> 1 votes
what version of drupal did you use?Can you try to remove the q?= and try it again?Also i notice on OPTIONS http://{localhost}:8888/drupal2/?q=system/connect.json 404,it doesn't contain your endpoint.

---
Tags: javascript, services
---


# Question
Title: Install Vanilla Wordpress to Drupal to use Vanilla Forum
any one knows how to install vanilla forum to drupal. I try to search a good article but could not success.I need step by step to do this.

# Answer
> 0 votes
You might need to install Orchid. Only by using this module you can integrate Drupal with Vannila Forum.

---
Tags: 7
---


# Question
Title: Not able to set the time for auction products, using the Ubercart Auction module
I guess this question is for those of us using the ubercart auction module

This module allow you to make auction of products (of the Product Content Type generated by Ubercart). When you create a new product you have to fill the `Auction Settings` and in there you have to set the **expiration** date and time of the auction.

My problem is that I see the field to set the date **but no input is shown to fill the time (i.e.: 18:00:00).**

The README file of the module says:

> Use the "Expiration date and time" field to set the expiration time for the auction.

then I understand that this is either a bug (I already posted the issue) or I have a mis-configuration on my site.

# Answer
> 2 votes
I think you just need to upgrade to the latest dev version, this is what the same fieldset looks like for me with that version:

This is on a blank Drupal 7.14 installation with only the required modules for uc\_auction enabled:

* Ubercart Auction - 7.x-1.x-dev (2011-Dec-11)
* Ubercart - 7.x-3.1
* Date - 7.x-2.5

It would be a good idea to make sure you have the latest stable versions of those contrib modules installed as well; if I remember rightly the date\_popup module used to have an issue with setting the `#default_value` of a `date_popup` type field, so the problem might just be that.

# Answer
> 0 votes
date still affects the product that is not auctioned. an error occured when I try to checkout with an unauctioned product. "Edit Issue Your order could not continue because one of the items you are trying to purchase using the “Buy Now” feature cannot be purchased because it has expired. Please remove the item from your cart to continue."

---
Tags: ubercart
---


# Question
Title: Views - user/role has access to edit node
I'm trying to set a view that shows only the nodes that current user or role has access to edit. I've tried with contextual filters and relationships but with no luck. Anyone know how to restrict it?

# Answer
Views accessed can be controlled by Views Access configuration, check the screen shots if it helps.

Step 1: Find the Views Access Configuration

Step 2 : Opt the permissions, which suit your needs

Step 3 : Configure the permissions
> 3 votes

# Answer
It can be done with Views PHP, but I don't think it can be done just within normal Views configuration - would be delighted to be contradicted.

If you're OK to use Views PHP the steps are:

1. Add `Content: Nid` as a Field in your view and exclude it from display.
2. Add a Global: PHP filter and include the following snippet:

```
return !node_access('update', node_load($row->nid));

```

**PHP explanation** (for non-seasoned PHPers) - the PHP snippet get the node object by using the node id that is made available by virtue of adding the `Content: Nid` field. With the first parameter of node\_access set as 'update' the function will check whether the the node is editable. You can also check for 'view', 'delete' or 'create' powers. If no third parameter is specified, the function checks the powers of the current user. The function will return true if the user can edit it, but the Global: PHP filter needs a return value of false in order to show the row, so the ! flips the true/false value returned by the function.
> -1 votes

# Answer
In Drupal 7 with Views 3 and Views PHP it can be done in one step. Create a Global PHP Filter and in the Filter code add:

```
return !node_access('update', node_load($data->nid));

```
> -3 votes

---
Tags: views, users, nodes
---


title: Use default installation profile?

text:
# Question
Title: Use default installation profile?
I've written a custom installation profile. When running install.php for the first time to install it, I have to select the installation profile I want to use. I then select mine and run the install profile, no problem. However, my client wants to be able to use the profile I put together as the default installation profile and skip that first step entirely (selecting an install profile). How can this be accomplished? Simply setting it as the default selected profile is not enough.

# Answer
> 5 votes
This part of your original question isn't quite clear:

> Simply setting it as the default selected profile is not enough.

However, all you have to do is to add `exclusive = TRUE` in the `.info` file of your installation profile.
This will automatically select your installation profile, and the user will proceed to the language selection screen.

Note 1: the setting above will be ignored if there are 2 or more installation profiles marked as exclusive. This might happen only if you downloaded another installation profile and are keeping it in the `/profiles` folder (e.g. Commerce Kickstart).

Note 2: this has been committed to Drupal 7.22 and is based on this issue/discussion.

# Answer
> 0 votes
Perhaps this helps you. How do I skip language selection with installation profile?

It´s about language, but this one works similar.

https://api.drupal.org/api/drupal/includes!install.core.inc/function/install\_select\_profile/7

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


# Question
Title: Views partial Contextual Filter on username
I have a view of users with a contextual filter for username which works great for whole usernames, but I need to allow this to work with partial names, or specifically whole words (userames are full names with spaces in this case), so if someone search for 'David' it will list all the 'David's, regardless of their surname.

Any help?

EDIT: a bit more googling revealed this, which was able to solve my problem: http://n00bsys0p.co.uk/blog/2012/08/21/drupal-views-3-contextual-filter

# Answer
You can achieve it by many way...make a relation with content:author and you will get all available options under user like (User: Name, User: First Name,User: last Name,User: Authentication name, User: Authmap ID, ) under contextual filter.
> 0 votes

# Answer
ok, then you can use views\_query\_alter to make a relation

```
function mymodule_views_query_alter(&$view, &$query)
{
if ($view->name == 'your_view_name')
{
  //dpm($query, __FUNCTION__);
   //dpm($view, __FUNCTION__);
   global $user;
   $tid =$user->mail;
   $join = new views_join;
   $join->construct('table_name', 'node', 'nid', 'nid', array(), 'LEFT');
   $query->add_relationship('table_name', $join, 'node');
   //$query->set_where_group('OR');
   // $view->query->set_group_operator('OR');
   //$query->add_where('table_name', 'table_name.field_name',$tid);
   //$query->where[1]['type']='AND';
   //$query->where[2]['type']='OR';
   //$query->group_operator='OR';
   //dpm($query, __FUNCTION__);
}
}

```

i am putting the comment line for the where condition and group before applying this you please enable the "Show the SQL query" from view setting.
> 0 votes

---
Tags: 7, views
---


title: Illegal choice error in log file

text:
# Question
Title: Illegal choice error in log file
I got this error in my log file. It was on a select element for an exposed View filter:

Illegal choice 24alert(0) in field\_item\_type\_tid element.

Is it someone trying to hack my site?

# Answer
> 3 votes
Someone (or something) is trying to submit a value for field\_item\_type\_tid that isn't in the list of allowed options for that field (as prepared by the form API prior to rendering the form/element).

The FAPI is objecting to that attempt (as it should; it's a security feature), so the user will receive the standard "Illegal choice" error message.

It might be an attempt at a hack, it might be something weird instigated by a user/browser extension, or it might be the result of some javascript trying to change the allowed values on the client-side, without informing the backend that the options need to change.

Without analysing the page and all the involved parameters it's only speculation, though. It might be being caused by any of the above, or perhaps some other external factor.

---
Tags: 7, views
---


# Question
Title: Rule check if field value changed give always true
I need a rule that checks if the value of a field has been changed by a particular role.

I created a rule with event "After updating existing content".

I added two conditions :

* user has role :

Parameter: User: \[site:current-user\], Roles: Web Team

* NOT data comparison :

Parameter: Data to compare: \[node:body\], Data value: \[node-unchanged:body\]

What I expect is to see the rule fired when a user with role "Web Team" changed the value of the body field of a node.

I expect the rule NOT to be fired when a user with role "Web Team" edit and save a node without changing anything.

And I expect the rule NOT to be fired when a user with no "Web Team" role edit and save a node.

But everytime the user with role "Web Team" edit and save a node, regardless if he changes something or not, the rule is fired.

I tried to change the event in "Before saving content" with no more success.

The log displayed after the save is the following :

```
0 ms Reacting on event Before saving content.
12.599 ms Evaluating conditions of rule test2. [edit]
19.604 ms The condition user_has_role evaluated to TRUE [edit]
23.194 ms The condition data_is evaluated to FALSE [edit]
23.23 ms AND evaluated to TRUE.

```

How AND can be evaluated to TRUE if one of its conditions is evaluated to FALSE?

I did many tests but really don't see how to solve that.

I hove somebody could help me.

Here is the rule exported :

```
{ "rules_test2" : {
    "LABEL" : "test2",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "workflow_rules" ],
    "ON" : { "node_presave" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "5" : "5" } }
        }
      },
      { "NOT data_is" : { "data" : [ "node:body" ], "value" : [ "node-unchanged:body" ] } }
    ],
    "DO" : [
      { "workflow_rules_set_state" : {
          "node" : [ "node" ],
          "workflow_state" : { "value" : { "11" : "11" } },
          "workflow_comment" : "Title or body modified by webteam. The content should return to contributors for validation."
        }
      },
      { "drupal_message" : { "message" : "node-title = [node:title]\r\n\r\nnode-body = [node:body]\r\n\r\nnode-unchanged-title = [node-unchanged:title]\r\n\r\nnode-unchanged-body = [node-unchanged:body]\r\n" } }
    ]
  }
}

```

Best regards

# Answer
> 5 votes
You have to use *:value* for the body or other textarea fields.

The problem is there:

```
{ "NOT data_is" : { "data" : [ "node:body" ], "value" : [ "node-unchanged:body" ] } }

```

Should be:

```
{ "NOT data_is" : { "data" : [ "node:body:value" ], "value" : [ "node-unchanged:body:value" ] } }

```

---
Tags: rules
---


# Question
Title: Adding a jQuery UI widget in the administrative front-end
I have created a form within the administrative front-end in my Drupal 7 site to allow administrators to change some configuration options. I've defined the path to it in the following way (in hook\_menu):

```
$items['admin/config/system/my_site_name/status'] = array(
  'title' => 'Change site status',
  'description' => 'My description',
  'access arguments' => array('administer site configuration'),
  'page callback' => 'drupal_get_form',
  'page arguments' => array('my_form_name'),
  'file' => 'forms_file.inc',
);

```

I want one of the items in this form to be a jQuery UI slider, bound to a hidden select element that has its same value, which is then fetched in the form's submit method (pretty much like in here: http://jqueryui.com/slider/#hotelrooms) by creating a .js file with the following.

```
(function ($) {
  Drupal.behaviors.site_status = {
    attach: function(context) {
      var select = $("#edit-site-status");
      var slider = $( "<div id='status-slider'></div>" ).insertAfter(select).slider({
        min: 0,
        max: 4,
        range: "min",
        value: select[0].selectedIndex,
        slide: function( event, ui ) {
          select[0].selectedIndex = ui.value;
        }
      });
      $( "#edit-site-status" ).change(function() {
        slider.slider( "value", this.selectedIndex);
      });
    }
  }

})(jQuery);

```

However, I've been unable to load the widget, as it seems the whole jQuery UI js file is missing.

> TypeError: $(...).insertAfter(...).slider is not a function

According to http://redhotchilliproject.com/blog/jquery-and-jquery-ui-in-drupal-7, I should manually load the jQuery file in some preprocess function, like this.

```
function MY_THEME_preprocess_page(&$variables, $hook) {
  drupal_add_library('system','ui.slider');
}

```

However this method doesn't get called from the page that contains my form. I've even tried to load the jQuery library in `MY_THEME_preprocess()` without any luck.

I don't want to include the file in the my\_module.info file, as I only need the slider to be in the administrative front-end and most users won't need it.

How can I get this slider to show up?

# Answer
> 2 votes
`drupal_add_library()` can be called from pretty much anywhere, including your form function:

```
function my_form_name($form, &$form_state) {
  drupal_add_library('system','ui.slider');

  // Build and return the form.
}

```

# Answer
> 2 votes
As alternative to Clive's answer, you can use the `#attached` property. The example in the documentation makes clear how to attach a library to a form.

```
if (!$user->uid) {
  $form['#attached']['library'][] = array('system', 'jquery.cookie');
  $form['#attributes']['class'][] = 'user-info-from-cookie';
}

```

Using `#attached` is the suggested way in Drupal 8, which doesn't use anymore the `hook_init()` hook.

---
Tags: 7, javascript
---


# Question
Title: How do I show a "results count" on my search results page?
I'm using Search API along with Facet API to administer a search for my products. I'm also overriding the search with a view. I'm looking for some method of counting the search results and displaying this information. For example, at the top of the search results page I want text to be displayed that reads something like "Showing 1 - 16 of 39,352 Results". I've read somewhere that views is able to do this easily, the problem is that I'm using facets and I don't think the results count from views will work together with applied facets. Can someone give me a solution or at least an idea?

# Answer
> 2 votes
In the view that I'm using to override my search results, I added "Global: Result summary" to the views Header and it seems to be working with the facets. Thanks.

# Answer
> 1 votes
There is already a module for this - https://drupal.org/project/views\_record\_count Provides same functionality you are looking for.

Some details from the module's project page:

> This module will add some additional functionality in views. You can see the record count in views header/footer if you have chosen pager. You will see record count option as well when you edit the view. If you setup some overridden values in you display, it work with them also. Default message region is footer. You can change it as well.

# Answer
> 0 votes
By using the below code, you can do that, It will display like this ***Showing 1-10 of 130 results***. on your result page.

Put this code in the page.tpl or **views Header and set the input filter as PHP code** in your view.

> ```
> <?php
> global $pager_page_array, $pager_total_items, $pager_total;
> $my_view = views_get_current_view();
> $items_per_page = $my_view->pager['items_per_page'];
> if ($pager_total[0] == 1) {
>   echo t('Showing <b>!pager_total_items</b> results',
>     array('!pager_total_items' => $pager_total_items[0])
>   );
> } else {
>   $start = 1 + ($pager_page_array[0] * $items_per_page);
>   $end = (1 + $pager_page_array[0]) * $items_per_page;
>   if ($end > $pager_total_items[0]) $end = $pager_total_items[0];
>   echo t('Showing !start-!end of <b>!pager_total_items</b> results',
>     array('!start' => $start, '!end' => $end, '!pager_total_items' => $pager_total_items[0])
>   );
> }
> ?>
>
> ```

---
Tags: theming, search
---


# Question
Title: CPU spikes enabling / disabling modules when site is under load
We are in the process of migrating our website to Drupal 7 and we had a failed launch this past week. We performed load testing and were certain that our server was going to work just fine with our current load, unfortunately we did not perform load testing with logged-in users (we use a 3rd party gateway login system and it was almost impossible to accomplish a load test this way). Long story short - logged in users overloaded our site and the server crashed.

So we've gone back to the drawing board, implemented APC and Memcache and we believe we have the problem fixed. The CPU no longer maxes out when under an expected load.

However, we now have a new issue that is a critical showstopper if we cannot find a fix for it.

While the server is under load from users, if an administrator attempts to enable or disable a module, ANY MODULE, (and sometimes even if we attempt to VIEW the modules page), the CPU will max out and the server will then eventually crash. The only option at that point is to restart the httpd service, which of course disrupts all user traffic.

When operating normally, CPU usage is at about 20 - 30%. When you attempt to enable or disable a module, the server IMMEDIATELY pegs the CPU at 100% and becomes nearly unresponsive from the browser and command line. Our normal page load times are 400ms, and they skyrocket to over a minute until the server crashes.

With no user load, the server operates as expected, though the action of enabling / disabling a module does spike the CPU for a short period of time. I have checked the sql slow query log and haven't found anything enlightening there. HTTPD is not spitting out any errors either.

Server has 2 CPU, 16GB memory and is dedicated to running this site alone; surely it isn't under powered.

What could possibly be causing this problem?

# Answer
> 1 votes
I wanted to come back and outline what we did to solve this issue.

Firstly, we installed Memcache and APC. Both were provided with as much memory as we could tolerate.

Secondly, we used the Mysql tuning scripts to adjust the MySQL settings. More information about that can be found here: http://www.askapache.com/mysql/performance-tuning-mysql.html

Thirdly, we reconfigured Apache. Internet suggested we add more workers and processes in order to get the server to cooperate. This actually caused more problems because the CPU was struggling to create and destroy the processes. By setting our start servers and Max servers to the same value, it maintains the same amount and does not create churn. By doing this, we were able to actually reduce the number of processes that we were running for Apache, while simultaneously increasing our throughput.

What we learned from this is that there is not a set solution that works. Good luck if you're having these same issues.

# Answer
> 8 votes
If you look at the source for `module_enable()` you can see what is going on. In particular, several cache tables get cleared, as does the registry. It also does filesystem scanning to rebuild module data. All of these are expensive operations.

If you look at the source for `system_modules()` (this is the callback for the modules page), you will see that `system_rebuild_module_data()` is called. This is also an expensive operation.

My *guess* is that something on your server isn't optimized. Even though you have gobs of CPU and RAM, Apache and MySQL may need tuning. I have seen similar instances to yours, where MySQL hangs due to heavy loads and then incoming HTTP requests stack up. Eventually, connections to the database will block, and slow things down more. When this happens, the system will very often hit swap due to the number of httpd processes. A live webserver hitting swap is a catastrophe; load/memory will swell exponentially.

In this case, you need do a few things.

First, run mysqltuner on your database, and make sure buffer sizes are OK, and that your max memory usage is sane.

Then, tune Apache to make sure you won't ever hit swap under normal conditions by limiting the number of concurrent servers. Enabling keepalives, and setting up some aggressive HTTP cache rules can also help reduce the number of active httpd processes. Using the CDN module can also help reduce Apache load by offloading most CSS, JS, and image requests to the CDN instead of your server.

It is also possible that your memcache doesn't have enough memory, and you are thrashing. You may need to check these settings, and also check which tables you are offloading.

I would also avoid enabling/disabling modules outside of maintenance mode. Schedule windows where you can do work. Assuming you stage/test everything properly, and work from a checklist, you shouldn't have more than 5-10 min downtime to do this.

---
Tags: 7, performance
---


# Question
Title: Which migration class should I extend to migrate user accounts?
I want to migrate users from a Drupal 5 site to a Drupal 7 site.

I installed the Migrate and Drupal-to-Drupal data migration modules. I know I have to make a custom module extending the built in classes of migrate\_d2d module to migrate users.

Which migration class should I extend while making the custom class? Is it correct that the custom class should be placed in the *user.inc* file?

# Answer
Upgrade from Drupal 5 to 6, then from 6 to 7. That's it. No further modules or writing your own code is needed, users and content will migrate just fine. You only need Migrate and other modules if you have some special stuff on your site, like Organic groups. CCK version 7 will be needed in most cases, but that's all in the documentation.

Here's the documentation, follow carefully:

From 5 to 6: https://drupal.org/documentation/upgrade/5/6

From 6 to 7: https://drupal.org/documentation/upgrade
> 2 votes

---
Tags: 7, migrations
---


# Question
Title: How can I get the $delta of block created using UI?
I have a created a block using UI .I want to change the content of the block programmatically. For this I am using hook\_block\_view\_alter(&$data, $block) for it as follows: I have just created a block using UI and I am going to assign certain pages which will be able to see that view..

```
function hook_block_view_alter(&$data, $block) {
if ($block->delta == 'HOW CAN I GET THE $DELTA here') {
$data['#markup'] = '<a href="www.google.com">Google</a>';

}

}

```

# Answer
If you go to `admin/structure/block` and mouseover the "configure" link you'll see something like this for blocks added through UI:

/admin/structure/block/manage/*block*/**1**/configure

something like this for blocks created with views:

/admin/structure/block/manage/*views*/**81e6b321879efa58ba9e546521c14467**/configure

something like this for blocks created with webform:

/admin/structure/block/manage/*webform*/**client-block-50**/configure

something like this for blocks created by the system (core):

/admin/structure/block/manage/*system*/**main**/configure

I've **bolded** the deltas and *italicized* the modules in each example.
> 5 votes

# Answer
Find the block on the Blocks configuration page, and click the "configure" link.

Look at the URL. The URL path tells you both the module that is responsible for the block, and the delta assigned to it. Here's the URL pattern:

/admin/structure/block/manage/ **MODULENAME** / **DELTA** /configure

So if your URL path is "/admin/structure/block/manage/block/5/configure", then that particular block is maintained by the "block" module, and the delta for the block is "5".
> 2 votes

# Answer
You can always get the delta by quering your DB (handy in cases where custom blocks are generated automatically and the delta is dynamic)

```
  $result = db_select('block_custom', 'b')
     ->fields('b', array('bid'))
     ->condition('info', '<ADMIN TITLE OF THE BLOCK>')
     ->execute()
     ->fetchAssoc();

  // if $result['bid'] exists..

  $delta = db_select('block', 'b')
     ->fields('b', array('delta'))
     ->condition('bid', $result['bid'])
     ->execute()
     ->fetchAssoc();

  $delta = $delta['delta'];

```
> 1 votes

---
Tags: blocks
---


# Question
Title: How to save custom value in DB from custom .module
I have *inherited* a custom module, which groups together some field of an custom ContentType and sends it by email.

In the module there are 3 functions.

Email check preg match:

```
function __autoload($class_name) {
  require_once($class_name . '.lib.php');
}
require_once('vumclass.lib.php');

```

This function gets triggered when the node is saved or updated. Right?

```
function vumveranstaltungsmailer_action_info() {
  return array(
    'vumveranstaltungsmailer_action' => array(
      'type' => 'node',
      'label' => 'vumveranstaltungsmailer_action',
      'configurable' => FALSE,
      'triggers' => array('node_insert', 'node_update'),
    ),
  );
}

```

Do stuff, send email:

```
function vumveranstaltungsmailer_action($object, $context) {
//do Stuff, sends email. Not shown here.

//I want to set this field to empty/clear it
$object->field_email_mailer_01['und']['0']['value']->set(NULL);

}

```

Bare with me, I am pretty a beginner/noob. I am a bit overwhelmed where and how to do it. Please give me a simple solution, so I understand it. Quick and dirty is fine for me ;-)

# Answer
> 1 votes
Once you get your nid of the node you can use the code below to change the field value

```
  $node = node_load($nid);

   unset($node->field_example['und'][0]['value']);
    //similarly for other fields you can change the value
    node_save($node);

```

---
Tags: 7
---


# Question
Title: How to make a user choose male or female and keep a default image on a specific content?
How can I make a user choose male or female and keep a default image on a specific content?

I mean I want two defaults pictures (for male and female), but only for default image in case user want to upload a different image this should be accept as normal.

And all this for one specific type of content.

I want this, just because this field must captures a photo but for the ones who don't want to upload a photo show a default profile image.

# Answer
> 2 votes
You can do this on the display level via

1. hook\_preprocess\_field() (thx Clive in the comments, give him a thumbs up!), OR
2. a custom formatter, OR
3. a custom Display suite field

hook\_preprocess\_field() on the image field is the easiest.

You have the full user entity available and can use information from other fields to alter the image.

The hook is fired every time theme('field', ..) is fired, so you need to figure out if this is the correct field.

EDIT: Instead of a detailed tutorial, here is what I usually do:

* Install devel
* Create your custom module with an implementation of hook\_preprocess\_field(&$variables).
* Do dpm($variables) inside that hook implementation to show the function argument (sometimes you need to refresh the page twice to see the result).
* Manipulate the part of $variables that you are interested in.

With a custom formatter, you can define your own way to display e.g. the image field, while having the data from other node fields available.

Then on the user display configuration, you can choose this formatter to display the image.

With the custom DS field, you can introduce a "field" - that is, a positionable element on the entity display. This field can use data from multiple data fields on the node entity. E.g. you first check if there is an explicitly uploaded image, and if not, you show an image depending on the gender (male, female, transgender / don't say).

You can also define a form to configure display options. E.g. you could make the image style configurable.

Steps:

* Enable Display suite
* Implement hook\_ds\_fields\_info() in a custom module, using e.g. DS\_FIELD\_TYPE\_FUNCTION.
* Provide the function to generate the html or render array (some examples)
* Configure your user to display with a Display suite layout.
* Enable your custom field.

There are more details to this. But I the main purpose of this answer is to point you in a direction.

---

The weakness of all these options is that you have to hardcode the field names, or at least one of them. If you want to reuse this on another site with other field names, you have to change the field names in the code.

# Answer
> 1 votes
Maybe you'ld like to add a taxonomy dropdown list to your user accounts `/admin/config/people/accounts/fields` and set a default user picture - corresponding to what's chosen there `&&` unless no user picture is uploaded already - in a custom `page–[node-type].tpl.php`.

More informations would be helpful to find out what you trying to do. Where should users choose their gender? Where you need the picture to be displayed exactly?

And last but not least: Not everyone counts itself as female or male. There are transgender people. And also people who don't like others to know their gender.

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


# Question
Title: Module for using Twitter's timeline widget on user's profile pages?
I want to use twitter's timeline widget on my site. This is different from the twitter drupal module that imports tweets as drupal content. I need all users of my site to be able to show the timeline widget on their profiles.

Is there a module that can assist with this?

Ive looked at the twitter timeline module but its not ideal. It would require giving users permission to create or edit a blocks. Also you have to enter the widget ID which I think some users will find confusing.

# Answer
> 1 votes
If you want to do this yourself, in broad strokes, you could create a custom module that does the following:

1. Creates two user profile fields that your users can edit if they want:

a. Their Twitter User Name

b. Their Twitter Widget ID
2. Creates a block that:

a. Is displayed when a User Profile is displayed and these two fields are filled out that

b. Takes these two fields from the user profile being displayed and integrates them into the HTML required by Twitter (see https://twitter.com/settings/widgets/new when logged into Twitter), eg, it outputs the twitter code from your previous question (https://drupal.stackexchange.com/questions/94079/allow-users-to-embed-twitter-feeds-without-allowing-script-tags) but fills in the USERNAME and WIDGET\_ID with the values of these two fields.

Once again, Twitter is *requiring* this Widget ID, so whether or not this is confusing to your users is, unfortunately, irrelevant.

---
Tags: social-network
---


# Question
Title: Null value in DB displays content on page
I have a blank category box on the bottom of the following page (http://www.suncorstainless.com/stainless-steel-hardware) and it appears that it's caused by a Null value in a table somewhere in my DB. I'm not the developer of this website and am having a hard time determining where this issue is in the DB.

Are there any tools available to determine the DB table that is displaying content on a page?

Thanks-in-Advance

# Answer
Use the Devel module and enable it's database query log. See this question.
> 0 votes

---
Tags: database
---


# Question
Title: Migrate module only imports first line of CSV file
I have a Migrate module class that works with CSV files and when I go through with the import it only goes through the first line of the CSV and then completes with a success message. That one line is imported correctly and the data is in place, but I'm wondering why it continues to stop at the first line.

When I run the import again it does not import anything and completes with success message again, mostly likely because the first line is already imported.

Any ideas?

```
class UserMigration extends MyMigration {
  public function __construct($arguments) {
    parent::__construct($arguments);

    $this->description = t('Import Users');
    $columns = array(
      0 => array('username', 'Username'),
      2 => array('email', 'Email'),
    );

    $this->source = new MigrateSourceCSV(drupal_get_path('module', 'my_module') . '/Users.csv', $columns);
    $this->destination = new MigrateDestinationUser();
    $this->addFieldMapping('name', 'username');
    $this->addFieldMapping('mail', 'email');
    $this->addFieldMapping('roles')
         ->defaultValue(DRUPAL_AUTHENTICATED_RID);
    $source_key = array(
      'username' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
      )
    );
    $this->map = new MigrateSQLMap($this->machineName, $source_key, MigrateDestinationUser::getKeySchema());

  }
}

```

# Answer
> 2 votes
It's possible that the CSV is saved with the wrong line endings. Try saving the CSV file with Unix-style line endings. By default, I believe Migrate expects a Unix format text file.

---
Tags: users, migrations
---


# Question
Title: Panels page variant that targets a single node
I am a little new to Panels, but I am using it to manage layouts for different content types and it is working out really well. However I want to be able to create a page variant that will only target a single node. Is there any way to do this based on the node's id?

# Answer
> 0 votes
What you probably want to do is use Panelizer.

Page manager itself can do it to, but I don't see a builtin rule to match on node ids. Copying an existing rule, such as `ctools/access/node_language.inc` would probably be the best way to solve that. See What are Ctools plugin (content type, access, etc), and how does one create them? for more details.

# Answer
> 8 votes
Assuming you already have the node override Panel enabled:

* Edit the panel page for the node override (node\_view for node/%node)
* Make a new variant, enable selection rules
* For the selection rule, choose **String: Url Path**
* In the criteria, keep **Allow access on the following pages** selected
* In the textarea, add the internal node paths for this nid(s) you want. To target nid 1234, use

node/1234
* Configure the test of the panel as needed.

Just make sure this comes before any less-specific rules, like matches on content type.

---
Tags: panels, chaos-tool-suite
---


# Question
Title: Using drush to sql-sync local to remote, without remote MySQL binaries on remote
I'm working with a prod and staging environment where the MySQL binaries (like mysqldump) are not installed. PHP can interact with MySQL just fine, but for reasons that are not relevant, the binaries aren't installed.

It appears that when performing an sql-sync, drush will attempt to ssh into the remote server, run the dump, then rsync the file down, then import it. Is there a way to avoid this, maybe a way of telling Drush to perform all the database operations locally? My workstation has access to the remote databases, so it is capable of performing mysql imports and dumps on the remote databases.

I understand that Drush cannot account for all edge cases like this. I wonder if anyone knows if there are workarounds for this or suggestions? I can just write my own scripts to do the syncing of databases, but would love to leverage drush.

# Answer
Drush version 3 and onward (via the sql-sync command) can only copy the database via the ssh + mysql executable method that you describe above. If you download drush 2.1 (https://drupal.org/node/614830), you will find a command `drush sql-load` that works as you describe. It's a lot slower than sql-sync, so if your database is very large, you might find this technique to be too cumbersome. If it works for you, though, it probably wouldn't be very hard to make your own external Drush commandfile to provide sql-load on a more recent version of Drush.
> 2 votes

---
Tags: drush
---


title: What Drupal theme is this site using?

text:
# Question
Title: What Drupal theme is this site using?
Does anyone know which Drupal theme these sites are using? I am interested in purchasing a copy.

1. http://www.kidsgardening.org/
2. http://www.garden.org/

# Answer
> 2 votes
http://www.kidsgardening.org is using a custom theme named "Kids Gardening" that is a subtheme of Zen.

http://www.garden.org is not a Drupal site.

---
Tags: theming
---


# Question
Title: How can I translate the <Any> option for a grouped exposed filter in Views?
I have an exposed filter in Views that uses the *Grouped filters* option to present choices to users. By default, an **`<Any>`** option is provided. My site is multilingual, so I want to translate this:

I am using the i18n suite of modules as well as i18nviews. I first searched using the *Translate interface* screen at `admin/config/regional/translate/translate` and I translated **`<Any>`**; however, when viewing the page, **`<Any>`** is still displayed, not the translated value.

There appears to be no option to customize the **`<Any>`** text within the Views UI.

I am able to translate the (user-defined) grouped filter options using i18n and i18nviews through the *Translate Interface* screen.

What do I need to do to translate **`<Any>`**?

# Answer
It turns out that there is a bug in Views at the moment, so I wrote a patch.

Once you apply the patch (or once the patch is committed to Views), you can translate as part of the built-in interface through the *Translate Interface* screen.
> 1 votes

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


# Question
Title: Is there any way to show user profile of authenticated user after loged in?
I would like to have a block that contains basic profile of authenticated user so that they can see their username, photo, email and log out link.

Any help will be appreciated.

# Answer
You can use Author Pane module to display a block of user information.

> Author Pane is a block of information about a given user, like those typically found on a forum post, but can be used in other places as well. From core, it collects the user picture, name, join date, online status, contact link, and profile information. In addition, any module or theme can feed it more information via the preprocess system. All of this information is then gathered and displayed using a template file.

If you do not want to use this module, then you can create a views to display user information.

* Go to Administration -\> Structure -\> Views
* Click on "Add new view" link
* Set name for views in "View name" field and select "users" from "show" drop down.
* Click on "Continue and Edit" button
* Create a block display for the views.
* Add "User: Picture", "User: E-mail", "User: Name" and "Global: Custom text (Custom text)".
* Check check-box "Output this field as a link" under "Rewrite results" section for "Global: Custom text" and set "user/logout" as Link path for the field.
* Save the views
> 7 votes

# Answer
Hope this will help you...

```
<?php
/**
 * Implementation of hook_block_info().
 */
function mymodule_block_info() {
  $blocks['my-block-id'] = array(
    'info' => t('User Summary'),
  );
  return $blocks;
}

 /**
 * Implementation of hook_block_view().
 */
function mymodule_block_view($delta='') {
  $block = array();
  switch ($delta) {
    case 'my-block-id':
     // $block['subject'] = t('Block Name');
      $block['content'] = user_contents();
      break;
  }
  return $block;
}
function user_contents() {
global $user;
//kpr($user);
$mstr = '';
$mstr .='<div id="first_block" >';
    $mstr .='<fieldset><legend>My Personal Details</legend><div style="margin-top:15px;"><b>User Name.</b></div><div style=""> </div><div class="user_name">'.$user->name.'</div>';
    $mstr .='<div style=""><b>User Id:</b> </div><div style=""> </div><div id="editme2" class="name1">'.$user->uid.'</div>';
    $mstr .='<div style=""><b>Mail id </b></div><div style=""> </div><div class="">'.$user->mail.'</div>';
    $mstr .='<div style=""><b>Timezone </b></div><div style=""> </div><div class="">'.$user->timezone.'</div>';
    $mstr .='</div>';

return $mstr;

}

```

this will create a block namely "user summary"
> 0 votes

---
Tags: users
---


title: unpublish node when edit it

text:
# Question
Title: unpublish node when edit it
I have a content type calles survey, When admin deletes a survey, the survey results should still be accessible and not deleted as well. So I want to unpublish the node when click on the delete button(it will be better to change this delete button to unpublish button). but I dont know how to unpublished a node. Any solution / alternative / suggestion will be greatly appreciated.

# Answer
> 1 votes
Hope this will help you, In my case i did it by updating the node and node\_revision table's status column set to "0".following code is for form submit action you can do it for your delete action..

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
 if ($form_id == 'your form')   {
 $form['#submit'][] = 'mymodule_form_submit';
 }

}

function mymodule_form_submit($form, &$form_state){
if (//your condition)
            {
            $query = db_update('node')
            ->fields(array(
            'status' => 0,//unpublished the node
                ))
            ->condition('nid',$form['nid']['#value'], '=')
            ->execute();

            $query = db_update('node_revision')
            ->fields(array(
            'status' => 0,//unpublished the node
                ))
            ->condition('nid',$form['nid']['#value'], '=')
            ->execute();
            }
        //  drupal_flush_all_caches();

}

```

# Answer
> 1 votes
You can find below code snippets for unpublished node.

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

  if ($form_id == 'article_node_form') {

    $form['actions']['delete']['#submit'] = array('custom_feature_node_delete_submit');

  }

}

function custom_feature_node_delete_submit($form, &$form_state) {

  $form_state['values']['status'] = 0;

  $node = node_form_submit_build_node($form, $form_state);
  node_save($node);

  $form_state['redirect'] = node_access('view', $node) ? 'node/' . $node->nid : '<front>';

}

```

Kindly see that you need to change `article_node_form` with your node edit form id. If you do not know, how to check form id, you can use `print $form_id` in `custom_feature_form_alter()` function.

---
Tags: nodes
---


# Question
Title: Which are the most effective methods of optimizing a drupal 7 site?
Is there any module which would help in optimizing drupal 7 site ?
The drupal site (used for **bank** both for transactions as well and for non transactions as well without using drupal commerce) becomes very slow in terms of loading pages or any nodes..
So which are different ways in which we can optimize the Drupal 7 site to work smoothly and efficiently?

# Answer
Boost module is the best option for performance issues, even it will works great in shared hosting. It will not hit the server for every request, instead it cache the pages and deliver them and Boost will cache & gzip compress html, xml, ajax, css, & javascript. Boosts cache expiration logic is very advanced; it's fairly simple to have different cache lifetimes for different parts of your site.

> Boost provides static page caching for Drupal enabling a very significant performance and scalability boost for sites that receive mostly anonymous traffic. For shared hosting this is your best option in terms of improving performance.
> 2 votes

---
Tags: 7
---


# Question
Title: Configuration page for module does not apear?
This is my hook\_menu.

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

        $items['coverflow']  = array(
            'title'           => 'Coverflow Slider',
            'page callback'     => 'coverflow_page',
            'access arguments'=> array('access content'),
        );

        $items['admin/config/coverflow'] = array(
                'title'                 => 'Coverflow Settings',
                'description'         => 'Coverflow Slider Settings.',
                'type'                  => 'MENU_NORMAL_ITEM',
                'page callback'     => 'drupal_get_form',
                'page arguments'    => array('coverflow_admin_form'),
                'access arguments'=> array('administer site configuration'),
                'file'            => 'coverflow_admin_form.inc',
                'file path'       => drupal_get_path('module', 'coverflow'),
            );

        return $items;
   }

```

And this is my callback function for coverflow\_admin\_form

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

    $form           = array();

    $form['height'] = array(
      '#title' => t('Height'),
      '#type' => 'textfield',
      '#size' => 40,
      '#maxlength' => 120,
      '#required' => TRUE,
    );

    $form['width'] = array(
      '#title' => t('Width'),
      '#type' => 'textfield',
      '#size' => 40,
      '#maxlength' => 120,
      '#required' => TRUE,
    );

    $form['font-size'] = array(
      '#title' => t('Font Size'),
      '#type'   => 'textfield',
      '#size'   => 40,
      '#maxlength' => 120,
      '#required' => TRUE,
    );

    $form['font-family'] = array(
      '#title' => t('Font Family'),
      '#type'   => 'textfield',
      '#size'   => 40,
      '#maxlength' => 120,
      '#required' => TRUE,
    );

    $form['font-color'] = array(
      '#title' => t('Font Color'),
      '#type'   => 'textfield',
      '#size'   => 40,
      '#maxlength' => 120,
      '#required' => TRUE,
    );

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

        return system_settings_form($form);

}

```

After installing module im not getting configuration link at admin/config/coverflow.

What is wrong in this code?

# Answer
Got the solution, just have to remove '' from 'MENU\_NORMAL\_ITEM' because MENU\_NORMAL\_ITEM is drupal constant for handling Menu Items, after removing '' the code is working as expected.
> 0 votes

---
Tags: 7
---


# Question
Title: How do I incorporate an if-statement within my array to hide/display a link?
Using the coding snippet below, how would I write the code to display the "Change" link only when the value in status is "A"?

I think i'm making this harder than it has to be, but the use of both drupal module structure and php are throwing me, since i am just learning module development.

The link showing in the array below appears at the end of each of my rows. I only want it to appear when the status equals "A".

Because this link is within this array, i can't figure out how and where to implement it. I just want an \[if statement\] like this:

```
if (drupal_render($form['status'][$key]['status']) == 'A',)
echo l(t('Change'), 'rooms/avail_room/' . $key . '/' . arg(1), array('attributes' => array('class' => 'room-stat-avail'))),
else{
echo "";
}

```

so when the html table is displayed, the 'Change' link will only appear in the last column when the value of status is "A"

Can't believe I got the module working, but can't turn this link on/off as i want. See code snippet below:

```
function team_room_available_form($form) {
    $output = "No space available.";

  if ($form['roomid']) {
    foreach (element_children($form['roomid']) as $key) {
      $rows[] = array(
        'data' => array(
          drupal_render($form[''][$key]),
          drupal_render($form['room_title'][$key]),
          drupal_render($form['username'][$key]),
          drupal_render($form['status'][$key]['status']),
          l(t('Change'), 'rooms/avail_room/' . $key . '/' . arg(1), array('attributes' => array('class' => 'room-stat-avail'))),
        ),
        'class' => $form['status'][$key]['#value'],
      );
    }

```

# Answer
You can use below code snippets:

```
$field = $form['status'][$key]['status'];

if (strip_tags($field) == 'A')
echo l(t('Change'), 'rooms/avail_room/' . $key . '/' . arg(1), array('attributes' => array('class' => 'room-stat-avail'))),
else{
echo "";
}

```
> 0 votes

---
Tags: 7
---


# Question
Title: Trying to add profile2 fields to user/edit page
I am trying to show the profile2 fields in my user edit page, but I can't figure out how for the life of me. I read that they should autmomatically show up but it's not happening..

I have added the following in my template.php:

```
function mytheme_theme($existing, $type, $theme, $path){

        $hooks['user_profile_form']    = array(
        'render element'       => 'form',
        'template'             => 'user-profile-form',
        'path'                 => drupal_get_path('theme','mytheme').'/templates');

    return $hooks;
}

function mytheme_preprocess_user_profile_form(&$variables) {
    global $user;
    $variables['form'] = drupal_render($variables['form']['account']);
    //???
    $profile2 = mytheme_profile_form();
}

function mytheme_form_user_profile_form_alter(&$form, &$form_state){
    global $user;
    $mainprofile = profile2_load_by_user($user->uid, 'main');
    $profile = profile2_load_by_user($user->uid, 'basic_information');

    //Example field
    $form['profile_basic_information']['field_field_1']['und']['#id'] = 'school-district';
    $form['profile_basic_information']['field_field_1']['und']['#attributes']['data-placeholder'] = "Choose your Field1";
    $form['profile_basic_information']['field_field_1']['und']['#attributes']['class'] = "input-xlarge";
    $form['profile_basic_information']['field_field_1']['und']['#default_value'] = !empty($profile) && isset($profile->field_field_1['und']) ? $profile->field_field_1['und'][0]['value'] : '';

}

function mytheme_form_user_profile_form_submit(&$form, &$form_state){
    //TODO
}

```

I also have user-profile-form.tpl which right now consists just of `echo $form;`

But the fields I am adding to the form are not being added.. I'm not sure that the form\_alter is affecting the output (it is running, though).

# Answer
> 2 votes
I do not think it is an issue regarding with your theme. I have also built a theme from scratch but its showing perfectly up there. You need to change the display settings while you edit your profile type. SO under profile type edit you would find options such as Manage fields, Display fields etc. Under Display fields there would be three tabs just below them...Default, User Account, and Profile Page. By default, the fields which are not required are hidden, you need to change them and then they should show up

# Answer
> 2 votes
You could try the Account Profile module:

> Merges Profile2 forms into user account form.
>
> Profile2 by default creates an additional tab for each new profile assigned to a user. Alternatively the submodule "Profile2 pages" provides a separated pages for viewing and editing profiles.

---
Tags: 7, users, forms
---


# Question
Title: hook_views_pre_render(&$view) seems to be called after the pager rendering
I am designing and ecommerce store and I am trying to sort the products by availability using a hook\_view. My function product\_eta\_seconds return the current eta of a product. Here is my module:

```
function availability_sort_views_pre_render(&$view) {
  if ('uc_products' == $view->name && 'page_1' == $view->current_display) {

    $view->result = array_reverse($view->result);
    $deliveryTime=array();
    foreach ($view->result as $viewRow){
        $deliveryTime[] = product_eta_seconds($viewRow->nid);
    }
    asort($deliveryTime);
    $view->result = sortArrayByArray($view->result,$deliveryTime);
  }
}

function sortArrayByArray($array,$orderArray) {
    $ordered = array();
    foreach($orderArray as $key=>$value) {
        if(array_key_exists($key,$array)) {

                $ordered[$key] = $array[$key];
                unset($array[$key]);
        }
    }
    return $ordered + $array;
}

```

The problem is the view-\>result returns only 9 items (my pager value) so when I look at page 2, there are results that should show up on the 1st page (with a lower eta). Is there a solution to get all items of the view without the pager and apply the pager, when the view is rendered ? Any other solution would suit though.

# Answer
> 2 votes
I couldn't find any hook to sort the views result after the results so I ended up using the module "Views PHP" and sort my view using the following:

```
<?php
    $deliveryTime1Arr = delivery_time_lookup($row1->nid);
    $deliveryTimeRow1=$deliveryTime1Arr[3];
    $deliveryTime2Arr = delivery_time_lookup($row2->nid);
    $deliveryTimeRow2=$deliveryTime2Arr[3];
    if($deliveryTimeRow1>$deliveryTimeRow2) return 1;
    else if($deliveryTimeRow1 == $deliveryTimeRow2) return 0;
    else if($deliveryTimeRow1 < $deliveryTimeRow2) return -1;
?>

```

# Answer
> 0 votes
Drupal view pager is generated from the result of view query. Even if you alter your display with pre\_render the total view result will not change. So the pager will not be altered with your custom result. Here you can use hook\_views\_query\_alter to alter your query and display according to your need.

---
Tags: hooks, views, paging
---


# Question
Title: drupal_goto() not remove url path of 404 page
I have a search form which returns to search page.

```
drupal_goto('/searchyour/trips', array('query' => $query));

```

this is work fine if a user in active page. search url will replace as eg: example.com/searchyour/trips

But if user in 404 page (example.com/nopage) and click search, search url will set to example.com/nopage/searchyour/trips I want to change this to example.com/searchyour/trips.

I'm new to drupal. Help me to solve this. :-)

# Answer
> 1 votes
Hope this will help you,

In Drupal 7 , you can check whether the page is 404 page or not. If it is a 404 page then change the drupal\_goto **$path** parameter.

```

  $status = drupal_get_http_header("status");
  $path = ($status == '404 Not Found'){
    //change the path from example.com/nopage/searchyour/trips to example.com/searchyour/trips
    drupal_goto('/searchyour/trips', array('query' => $query));
  }else{
    drupal_goto('/searchyour/trips', array('query' => $query));
  }

```

# Answer
> 0 votes
As I understood the question, there is search link on the page or in header section, which takes the user to 'searchyour/trips' URL. The URL for this link becomes invalid when you are on 404 URL.

I believe you can use url() function to make your search link on the page. For example,

url('searchyour/trips')

# Answer
> 0 votes
Thanks for your comments. I have solved this problem but it seems it isn't the correct way.

The problem I found here is drupal\_goto() function has used GET\['destination'\] value if the url is not secure (this is what I understand after reading the code). Otherwise it will empty.

```
  // A destination in $_GET always overrides the function arguments.
  // We do not allow absolute URLs to be passed via $_GET, as this can be an attack vector.

  if (isset($_GET['destination']) && !url_is_external($_GET['destination'])) {
    $destination = drupal_parse_url($_GET['destination']);
    $path = $destination['path'];
    $options['query'] = $destination['query'];
    $options['fragment'] = $destination['fragment'];
  }

```

If it's empty, then search your/trips path used in $path. Otherwise it will override to the $GET\['destination'\]. So if I clear the $GET\['destination'\], it works.

I doubt this is a good practice. So any comments about it will be appreciated.

---
Tags: views, theming, hooks
---


title: How do I achieve this effect?

text:
# Question
Title: How do I achieve this effect?
There are 50+ categories on my site,i want each category to achieve this effect:One row ,4 products.

I do not clone views one by one. Anyone can help me? THX

Note:I use drupal 7.

# Answer
You can try Views Fluid Grid module

This module provides the Fluid Grid style plugin for Views. This plugin displays the view as a fluid grid using an HTML list element.

> The plugin settings form provides options to define the width and height of the elements in the grid. But it also provides advanced layout options implemented in separate CSS classes that allow you to define item margins, alignment and a couple of CSS3 properties (box-shadow and border-radius).
> 1 votes

---
Tags: taxonomy-terms
---


# Question
Title: Rule to send an email on node save printing a field value of a referenced node
I am using Drupal 7, and the modules References and Rules.

I created two content types: A and B.

A has a field (A:b\_nodes) which is multiple node references of B which has field (B:time).

How can I configure a rule so that when A is saved, an email will be sent with body text like the following:

```
here are the B nodes time data contained in A

B1 : 2 januari 2013
B2 : 5 may 2013
B3 : 15 august 2013

```

# Answer
Go to **/admin/config/workflow/rules/reaction/add** and create a rule. Then in rules action section under system category select **Send email**. Then you will be redirect to a new page, here you can define the subject,content,recipient of mail. By using **Replacement Patterns** you can add dynamic variable in to mail content.
> 1 votes

---
Tags: 7, rules, emails
---


# Question
Title: How might I show only the first level of an Exposed Taxonomy Filter in Views?
In Drupal 7, I have a exposed filter set at first in its hierarchical fashion

with the following structure:

```
Adjunct
-Adjunct Lecturer
-Adjunct Professor
Chairperson
Clinician
Container
-Director Advising & Student Affairs
-Managing Director TIC
Deans
-Associate Dean Undergraduate Advising Administration
Department Chair
Emeritus
-Associate Professor Emeritus
-Professor Emeritus
Lecturer
-Senior Lecturer
Professor
-Assistant Professor
-Assistant Professor in Residence
-Associate Professor
-Associate Professor in Residence
-Research Scientist & Professor
Speech Pathologist
Visiting
-Visiting Assistant Professor
-Visiting Associate Professor

```

In the exposed filter, is there a way to expose only the parent (first level) items (Adjunct, Deans, Department Chair, etc)?

Update: Grouping the exposed filter in views did not work (ticket).

# Answer
Add " Taxonomy: Term ID (with depth)" and set the depth to "1" it will show the first level of terms.

For Drupal 6:

Views Taxonomy: limit exposed dropdown by term depth module provides enhanced functionality for the exposed dropdown filter for taxonomy terms in Views.

> Exposed term filters can already be limited to display only terms selected in the Views interface. But what if content creators add new taxonomy terms? They will have to navigate the Views interface and add these new terms to the list of terms shown by exposed filters.
> 1 votes

---
Tags: 7, taxonomy-terms, views
---


title: Profiles-2--user-edit-page

text:
# Question
Title: Profiles-2--user-edit-page
I made my custom `user-profile-edit.tpl.php` using

```
function mytheme_theme($existing, $type, $theme, $path)
{

$hooks['user_profile_form'] = array(
                                // Forms always take the form argument.
                                'arguments' => array('form' => NULL),
                                'render element' => 'form',
                                'template' => 'templates/user-profile-edit',
                                );
return $hooks;
}

```

Now I want in `user-profile-edit.tpl.php` to render the account form (default Drupal form for users) and my profiles2 forms, from the forms i created without click the upper links.

Does anyone know how I can achieve this?

# Answer
After creation template you need only implements form\_alter and set this custom theme for whole form - `$form['#theme'] = 'user_profile_form'` and then you will be able to build form structure inside your template.

You can check diff module ( 'diff\_node\_revisions' theme ) as an example.
> 0 votes

---
Tags: 7, theming
---


title: Hide 'configure block' for Omega theme?

text:
# Question
Title: Hide 'configure block' for Omega theme?
How can I hide the 'configure block' mouseover from appearing? Im using the Omega theme.

Its breaking parts of my site but I cant stop it from appearing with permissions as certain users need the permission to edit blocks.

# Answer
> 0 votes
Disabling Contextual Links fixed it.

# Answer
> 0 votes
If you are using Omega theme version 7.x-3.1, you can go to the templates folder and edit region--content.tpl.php. In line 12 you will find the following:

```
   <?php if ($action_links): ?><ul class="action-links"><?php print render($action_links); ?></ul><?php endif; ?>

```

You can comment this line out, or delete it.

---
Tags: 7, theming
---


# Question
Title: Difference and relationship between View, Page, Panel and Mini Panel?
I'm quite familiar with Views but for others, especially page, panel and mini panel introduced by the module, Panels. Can anyone provide some simple but elegant description between them?

# Answer
**Views** are used to create lists of things.

One difficulty with Views, is that when used on their own, views tend to become fairly static. Let's say that you have a view that lists "Friends of user X". In your view, you must know define where to find user X. This will mostly be either a contextual filter, possibly using a relationship, but whatever configuration you have, it becomes a static part of the view. This leads us to **Pages**.

**Pages** provide the rest of your site with `Context`. Continuing on the example above, a Page can figure out how to find user X at run-time, and then feed that as an argument to other components, such as the friend view. This means you can re-use the same view, and all the rules that go with it, on both the same page more than once, but also across pages, and having it base it's results on different users every time.

If you want to show the browsing users friends, *and* my best friends friends, on the same page, you tell the current `Page` about those two contexts, use the same View twice, and give each instance of that View, a different context as argument.

A page on it's own however, doesn't have a visible interface, neither back- nor front-end, which is were **Panels** comes in.

**Panels** Provides a GUI on top of Panels, allowing you to configure Page manager, as well as adding further functionality to Pages, such as render caching.

**Mini Panels** Essentially embeds an "small" Panel rendering into another Panel. You can think of it as a very intelligent version of a block, capable of defining layouts, requiring parameters, and more.
> 2 votes

# Answer
**Views**: It is used to create custom queries. If you want to make a list of particular type of content, view is suitable.

**Page**: Page that you can use to create static pages. If you want to create a custom static page, for example like **About us** page. That page my be not reside in any particular content type or anything, but you just want to create a static page. Pages are using panels to alter the contents inside it.

**Panels**: Panels are using to define a custom layout for a particular page. Means, for example your theme have basic structure firstsidebar|Main content but you need one rightsidebar region only for a particular page. Then panels are useful. In panels you can define custom layout for a particular page. And you can assign block or any contenets to the various regions of that page without writing any single line of code by using panels, here you can see how we can use panels for altering node layout.
> -1 votes

---
Tags: views, panels
---


# Question
Title: Ckeditor fake linebreaks with pasted text
**Problem**

When you paste text into ckeditor it creates line breaks in the display which don't appear in the actual text.

How can I either paste in text and have it create actual linebreaks, or paste in text and not show the fake linebreaks?

**Example**

In order to create an actual line break you have to press delete and then add two returns in order to create a genuine linebreak (I have CKEditor configured to create `<br>` on enter).

**Sample Text I Used: Taken from Dolor Ipsum Website**

(Shown in HTML Full Text format)

```
 <p>bibendum feugiat tortor a imperdiet. Ut nisl lorem, bibendum iaculis est quis,    mollis convallis neque. Vestibulum vitae erat vitae sem tempus consequat.</p><p>Integer a auctor lorem, sit amet sagittis lectus. Sed bibendum at purus eu mollis. Sed pretium tincidunt nulla vitae fringilla. Etiam ac fringilla nulla. Cras lectus magna, suscipit sed felis accumsan, sagittis lobortis justo. Vestibulum volutpat auctor mi, at </p>

```

# Answer
If you're experiencing weird behavior on the editing side of CKEditor it's probably because of the CSS file being loaded by CKEditor.

CKEditor implements this in a way where it doesn't show up in my firebug.

I can see the margins and padding when I hover on an element however nothing is shown when it lists the styles effecting the element. This causes the problem above.

**How to fix it:**

Changing the CSS file works, go to the CKEditor configuration page and select the CSS drop down menu.

Change CKEditor default to Define CSS and enter your own path for the CSS file.

What I did however was edit the CKEditor default css file. It's located in `../modules/ckeditor/ckeditor/contents.css`

I was getting a margin of 20px appearing on the top and bottom of all my elements. There was nothing in `contents.css` about it, I don't really know where it's coming from.

But I added the following snippet which fixed it.

```
p,
h1,
h2,
h3,
ul li {

margin: 0 auto;

}

```
> 0 votes

---
Tags: 7, wysiwyg
---


title: A container for items for each taxonomy

text:
# Question
Title: A container for items for each taxonomy
I have a content-type called "Member", which has four taxonomy terms.

Now in my block, i want to display entries in a different DIV for each taxonomy.

For example all items with the taxonomy "Boss" should be placed inside the first DIV, items with the taxonomy "Manager" should be placed in the second DIV, and so on..

How can i achieve this?

# Answer
> 0 votes
Hope this will help you.

Create a new view content type

**add field Content: All taxonomy terms (checked Exclude from display ) add field Content: Title**

**add filter Content: Type (= Member)**

go to format select HTML list on settings **Grouping field Nr.1 select Content: All taxonomy terms** unchecked "**Use rendered output to group rows**"

from add create a block you will get a new block in your block page.

---
Tags: views, taxonomy-terms, blocks
---