title: Tax calculation Drupal Commerce

text:
# Question
Title: Tax calculation Drupal Commerce
I've set-up a Drupal Commerce website. Clients add products in the backend and give each product a price INCLUDING taxes (in this case €160,00). The product fiches on the product page should show the products with taxes. In the shopping-cart block (in the sidebar) as well.

However, on the check-out pages, the line items should be shown WITHOUT taxes (€126,40 in this case). The taxes should only be added in the block on the bottom...

I hope I make myself clear with this picture:

Does anyone have an idea on how to do this? Because I don't :)

# Answer
The Commerce Price Components module allows you to change what elements of a price are included when displaying it, including whether tax is included in the amount. With that module, you can get the result you are looking for by editing the view behind your Checkout screen (from your screenshot).

1. Go to the Checkout screen so it looks like your screenshot. In other words, be sure you have a VAT tax set up, and a product in your shopping cart, and go to Checkout. The screen will look as you show above, ie the line item price will INCLUDE VAT.
2. There is a gear icon in the upper right of the screen (above the word TOTAL). Hover over this and click EDIT VIEW.
3. You will be in the Commerce Cart Summary View. In the FIELDS list, click on the Commerce Line Item Unit Price.
4. Change the Formatter to Price By Components, and be sure only Base Price is ticked.
5. Click APPLY
6. Do the same for the Commerce Line Item Total.
7. Click SAVE to save the View
> 1 votes

# Answer
Check this module: http://drupal.org/project/commerce\_extra\_price\_formatters After that change the view that displays the products and simply change the format of that price, you have multiple options with that module including the one to show it without taxes.

Hope it helps.
> 0 votes

---
Tags: commerce
---


title: Adding an operation to Content Types

text:
# Question
Title: Adding an operation to Content Types
I'm working on a module. I've added a tab to each Content Type in `hook_menu` using something like:

```
$items['admin/structure/types/manage/%/stuff'] = array(
    'title' => 'Manage stuff',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('stuff_content_type_stuff_form', 4),
    'access arguments' => array('administer content types'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 100
);

```

The tab appears fine when I visit `admin/structure/types/manage/article/edit`, for example. However, when I view `admin/structure/types` to view the list of content types, I'd like to see "Manage stuff" listed as a link in the "operations" column alongside "Manage fields" and "Manage display".

Is this possible? Can someone please provide a way to do this?

# Answer
The `admin/structure/types` page is created via the hook\_menu() in the node module:

```
$items['admin/structure/types'] = array(
  'title' => 'Content types',
  'description' => 'Manage content types, including default status, front page promotion, comment settings, etc.',
  'page callback' => 'node_overview_types',
  'access arguments' => array('administer content types'),
  'file' => 'content_types.inc',
);

```

which shows that the page is generated by the `node_overview_types` function in `content_types.inc`:

```
/**
 * Displays the content type admin overview page.
 */
function node_overview_types() {
  $types = node_type_get_types();
  $names = node_type_get_names();
  $field_ui = module_exists('field_ui');
  $header = array(t('Name'), array('data' => t('Operations'), 'colspan' => $field_ui ? '4' : '2'));
  $rows = array();

  foreach ($names as $key => $name) {
    $type = $types[$key];
    if (node_hook($type->type, 'form')) {
      $type_url_str = str_replace('_', '-', $type->type);
      $row = array(theme('node_admin_overview', array('name' => $name, 'type' => $type)));
      // Set the edit column.
      $row[] = array('data' => l(t('edit'), 'admin/structure/types/manage/' . $type_url_str));

      if ($field_ui) {
        // Manage fields.
        $row[] = array('data' => l(t('manage fields'), 'admin/structure/types/manage/' . $type_url_str . '/fields'));

        // Display fields.
        $row[] = array('data' => l(t('manage display'), 'admin/structure/types/manage/' . $type_url_str . '/display'));
      }

      // Set the delete column.
      if ($type->custom) {
        $row[] = array('data' => l(t('delete'), 'admin/structure/types/manage/' . $type_url_str . '/delete'));
      }
      else {
        $row[] = array('data' => '');
      }

      $rows[] = $row;
    }
  }

  $build['node_table'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' => t('No content types available. <a href="@link">Add content type</a>.', array('@link' => url('admin/structure/types/add'))),
  );

  return $build;
}

```

So, one way I can see to do this would be to in your module, do a hook\_menu\_alter() and point the page callback to a function in your module and just add to the core one's functionality, eg, something like this:

```
function YOURMODULE_menu_alter(&$items) {

  $items['admin/structure/types']['page callback']='YOURMODULE_node_overview_types';
  unset($items['admin/structure/types']['file']); // or point it to YOURMODULE_pages.inc if need be

}

```

and then basically just copy the code from `node_overview_types()` into `YOURMODULE_node_overview_types()` and then put in your functionality, eg, change the colspan to 5 or 3 and add in the l() to your menu item.

NOTE: Of course, if the node module is ever updated you'll have to keep that in mind and possibly redo this. So, yes, since a render array is returned, you could instead modify this in any number of hook alters before the page is rendered. If you want to look into this approach, Render Arrays in Drupal 7 is a good place to start.

ADDITION:

For completeness, this is one way you could use a hook\_page\_alter():

```
function YOURMODULE_page_alter(&$page) {

  if ($_GET['q']=='admin/structure/types') {

    $types = array_keys(node_type_get_types());

    $page['content']['system_main']['node_table']['#header'][1]['colspan']++;
    foreach($page['content']['system_main']['node_table']['#rows'] as $type => &$row) {
      $row[]='New menu link goes here for ' . $types[$type];
    }

  }

}

```

instead of the `hook_menu_alter()` approach above. But also, obviously, it too relies on the structure of the array returned by the node module.
> 1 votes

# Answer
Yes, it is possible, I have a suggestion for you

dont forget clear cache after apply this,

```
function yourmodule_menu_alter(&$items) {

      $items['admin/structure/types']['page callback']='yourmodule_node_overview_types',
    }

function yourmodule_node_overview_types() {
  $types = node_type_get_types();
  $names = node_type_get_names();
  $field_ui = module_exists('field_ui');
  $header = array(t('Name'), array('data' => t('Operations'), 'colspan' => $field_ui ? '4' : '2'));
  $rows = array();

  foreach ($names as $key => $name) {
    $type = $types[$key];
    if (node_hook($type->type, 'form')) {
      $type_url_str = str_replace('_', '-', $type->type);
      $row = array(theme('node_admin_overview', array('name' => $name, 'type' => $type)));
      // Set the edit column.
      $row[] = array('data' => l(t('edit'), 'admin/structure/types/manage/' . $type_url_str));
      $row[] = array('data' => l(t('Manage stuff'), 'admin/structure/types/manage/%/stuff' . $type_url_str));

      if ($field_ui) {
        // Manage fields.
        $row[] = array('data' => l(t('manage fields'), 'admin/structure/types/manage/' . $type_url_str . '/fields'));

        // Display fields.
        $row[] = array('data' => l(t('manage display'), 'admin/structure/types/manage/' . $type_url_str . '/display'));
      }

      // Set the delete column.
      if ($type->custom) {
        $row[] = array('data' => l(t('delete'), 'admin/structure/types/manage/' . $type_url_str . '/delete'));
      }
      else {
        $row[] = array('data' => '');
      }

      $rows[] = $row;
    }
  }

  $build['node_table'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' => t('No content types available. <a href="@link">Add content type</a>.', array('@link' => url('admin/structure/types/add'))),
  );

  return $build;
}

```
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: Unsetting a field before hook_form_alter
I have a field collection with two entity reference fields that I keep hidden on a node creation form. The reference fields in the hidden field collection are slowing down the page load time. I need to block the field collection from rendering at all. From what I understand it needs to happen before hook form alter. See Question - Does unset($form\['field'\]); in hook\_form\_alter stop entity reference views select list queries from running?. Any help would really be appreciated!

# Answer
> 1 votes
In case this helps anyone - the hidden node reference fields that I have been using were having their lists of selectable nodes generated by views. I ended up using hook\_views\_query\_alter to stop the view query from being run. Here's the code I put into my custom module:

```
/**
 * Implements hook_views_query_alter().
 *
 * Disables node reference views. This drammatically
 * speeds up performance.
 */
 function mymodule_views_query_alter(&$view, &$query) {
  if ($view->name == "my_view") {
    $view->executed = TRUE;
  }
  if ($view->name == "my_view2") {
    $view->executed = TRUE;
  }
 }

```

---
Tags: entities
---


# Question
Title: Zen theme: understanding the zen grids design in _responsive.scss?
Below is some of the code from \_responsive.scss from the latest release of the Zen theme. It controls the layout of the page. Does anyone know what I have marked 'FROM HERE' to 'TO HERE' is for? I was following the Zen grids method fine until I came across this section of Sass. It doesn't appear in the five column layout, just the three column layout. Thanks

```
/**
* The layout when there are two sidebars.
*/
.two-sidebars {
  /* Span 2 columns, starting in 2nd column from left. */
  #content {
    @include zen-grid-item(2, 2);
  }

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

  /* Start a new row and span all 3 columns. */
  .region-sidebar-second {
    @include zen-grid-item(3, 1);

    --- FROM HERE ---

    @include zen-nested-container(); // Since we're making every block in this region be      a grid item.
    @include zen-clear();

    /* Apply the shared properties of grid items in a single, efficient ruleset. */
    .block {
      @include zen-grid-item-base();
    }
    /* Span 1 column, starting in the 1st column from left. */
    .block:nth-child(3n+1) {
      @include zen-grid-item(1, 1);
      @include zen-clear();
    }
    /* Span 1 column, starting in the 2nd column from left. */
    .block:nth-child(3n+2) {
      @include zen-grid-item(1, 2);
    }
    /* Span 1 column, starting in the 3rd column from left. */
    .block:nth-child(3n) {
      @include zen-grid-item(1, 3);
    }

    --- TO HERE ---

  }

```

}

# Answer
> 4 votes
\*Note that this is also inside the `.region-sidebar-second` container

Also of note, is that zen-grids actually has nothing to do with Drupal apart from being created by John Albin. The documentation can be found here.

**Quick and dirty explanation:**

```
--FROM HERE--

@include zen-nested-container(); // Since we're making every block in this region be      a grid item.

```

Ensures that the element (in this case, `.region-sidebar-second`) does not have any guttering (margins outside of the declared columns).

```
@include zen-clear();

```

This means that the sidebar region will have a clearfix applied

```
/* Apply the shared properties of grid items in a single, efficient ruleset. */
.block {
  @include zen-grid-item-base();
}

```

This applies a set of base styles to all blocks that will be in the sidebar. Things such as gutter width and box sizing. It takes something of an OOCSS approach in that it encourages DRY CSS (i.e. you don't need to apply the same CS to each block individually).

```
/* Span 1 column, starting in the 1st column from left. */
.block:nth-child(3n+1) {
  @include zen-grid-item(1, 1);
  @include zen-clear();
}

```

For 1st block in a group of three (`3n+1`), make the block 1 column wide, and place it in the first "column". Then assign a clearfix. I tend to read `@include zen-clear()` as *new line*.

```
/* Span 1 column, starting in the 2nd column from left. */
.block:nth-child(3n+2) {
  @include zen-grid-item(1, 2);
}

```

For 2nd block in a group of three (`3n+1`), make the block 1 column wide, and put it in the second "column"

```
/* Span 1 column, starting in the 3rd column from left. */
.block:nth-child(3n) {
  @include zen-grid-item(1, 3);
}

```

For every third block, make it 1 grid item wide, and put it in the 3rd "column"

```
--- TO HERE ---

```

**Useful links:**

*Note: As of August 13th 2013 these all work fine, but they might go over the next few years. If they do go and you notice, please be a darling and remove/update them from this answer ;-)*

# Answer
> 0 votes
I'm answering your question specific to .region-sidebar-second, and the special treatment it gets in the default 3 column layout (medium size screens): to fit into that screen size, the second sidebar gets moved to a new row in the grid, and then lines up the blocks horizontally, when there are two sidebars. That's the only thing special about it, that it gets moved down when there are two sidebars in that second screen size breakpoint.

---
Tags: theming
---


# Question
Title: How to keep showing Administration menu when changing user?
I'm using the Administration menu, like thousands of others. I recently discovered that one can change from user by hoovering over the red "hello user" button at the right. It's a nice feature, but I was wondering if it's possible to keep showing the toolbar when one changes from user (even when that user doesn't have permission to use it) in order to be able to switch back to administrator quickly. When I, as an administrator, would like to see how the page looks like for another user, I now always have to log in again as administrator - quite time consuming.

Any suggestions?

# Answer
> 1 votes
There is the Masquerade module for seeing how a page looks like for another user https://drupal.org/project/masquerade.

Another way is to duplicate your tab in incoqnito tab or in another browser and become another user there.

Third way is to make sure (if possible) your browser remembers user names and passwords on login forms. Then logging in as administrator is as easy as typing the first letter to the username field and pressing enter. This is less cool of course...

---
Tags: 7, users, toolbar
---


# Question
Title: Custom template for custom page in custom module in D6
So I know there is a way to specify a custom template for custom content types etc, but if I have a custom module where I am using hook\_menu() to add custom pages with a page callback function, how can I specify that the pages I create use a custom template? This particular site is still on Drupal 6, so I would need to know the Drupal 6 method if it's possible

THANKS

# Answer
If you have something like this:

```
function YOURMODULE_menu() {

  $items=array();

  $items['yourmodule/cool/path'] = array(
    'page callback' => 'YOURMODULE_cool_path_callback',
    // etc
  );

  // etc

  return $items;

}

```

then Drupal will utilize `page-yourmodule-cool-path.tpl.php` (eg, the `/`s are turned into `-`s) if it exists without any further action besides clearing your caches to pick it up.

In fact, if you create a `page-yourmodule.tpl.php` file, Drupal will use it for ANY path starting with `yourmodule`, eg, `yourmodule/cool/path`, `yourmodule/cooler/path,` etc., that doesn't have a more specific template created for it.

See Drupal 6 Template Suggestions for more info.

But, of course, if you have lots of paths that you want to use a single custom page template for that aren't so similarly defined, you can certainly use hook\_preprocess\_page() to suggest a non-standard template file:

```
function YOURMODULE_OR_THEME_preprocess_page(&$variables) {

  if (/* whatever is true */) {
    $variables['template_files'][] = 'page-custom';
  }

}

```

which would then have Drupal using `page-custom.tpl.php` for whatever was true in that `if`. Just realize if `custom` is defined as a path somewhere on your system, or is the start of a path, Drupal will use this template there as well.

Just realize somewhat obviously that whichever route you take, the page templates reside in your theme's directory and not with your module unless you use a registry alter:

```
function YOURMODULE_theme_registry_alter(&$theme_registry) {
  $theme_hook = 'page';
  $modulepath = drupal_get_path('module', 'YOURMODULE') . '/tpl/page';
  array_unshift($theme_registry[$theme_hook]['theme paths'], $modulepath);
}

```

which *should* cause Drupal to look in a `tpl/page` directory of your module for them but this brings up all sorts of other issues.
> 0 votes

# Answer
Your custom callback functions still use url aliases so you would just need to define a preprocess\_hook that adds template files if that particular alias is being served. Here is a basic function you can use in your template.php file, modified from this handbook page:

```
function YOURTHEMENAME_preprocess_page(&$vars) {

    $alias = drupal_get_path_alias(str_replace('/edit','',$_GET['q']));

    if (($alias != $_GET['q']) && ($alias == 'YOUR CUSTOM HOOK')) {;
      $template_filename = 'page' . '-' . 'YOUR CUSTOM TEMPLATE';
      $vars['template_files'][] = $template_filename;
    }

}

```

So, for example, if your menu hook was /trigger/awesome then the code could look like this:

```
function YOURTHEMENAME_preprocess_page(&$vars) {

    $alias = drupal_get_path_alias(str_replace('/edit','',$_GET['q']));

    if (($alias != $_GET['q']) && ($alias == 'trigger/awesome')) {;
      $template_filename = 'page' . '-' . 'awesome';
      $vars['template_files'][] = $template_filename;
    }

}

```

and the theme would now look to serve this page using the page-awesome.tpl.php file in your theme folder.
> 0 votes

---
Tags: theming, 6, routes
---


title: How to style every element in a theme?

text:
# Question
Title: How to style every element in a theme?
I created a theme from scratch and I didnt make a lot of changes to the `theme template` files which listed as below:

> * block.tpl.php
> * html.tpl.php
> * node.tpl.php
> * node--article.tpl.php
> * page.tpl.php
> * page--front.tpl.php
> * views-view.tpl.php
> * views-view-fields.tpl.php

A lot of styling that I made with `HTML/CSS` was missed up when I start creating contents and didn't appear as I expected.

Below code is used for getting the whole content, but how am I able to break it into artic title, article meta, article content body?

```
print render($content);

```

So I would like to know how am I able to edit the `PHP` files and giving styles to each element? Also some of elements that are specific for home page and category pages are shown into the article pages, so how shall I fix that too?

**EDIT:** here is title's code from `page.tpl.php`:

```
<?php print render($title_prefix); ?>
<?php if ($title): ?><h1 class="pageTitle"><?php print $title; ?></h1><?php endif; ?>
<?php print render($title_suffix); ?>

```

and that's the title code from `node--article.tpl.php`:

```
<?php print render($title_prefix); ?>
<?php if (!$page): ?>
<h3 class="postTitle"><a href="<?php print $node_url; ?>"><?php print $title; ?></a></h3>
<?php endif; ?>
<?php print render($title_suffix); ?>

```

But still all articles getting its title styling from `page.tpl.php` and it is staying outisde of the div that I specified for the `node--article.tpl.php` file. So how to fix that?

# Answer
> 0 votes
Your question is very broad. As I understand it, you want to know how the Drupal theming system works ;)

If you want to style the output of a node then have a look at the default node template in order to find out, what variables are available.

Before creating a theme from scratch I find it highly advisable though, to look through the default core themes and some more popular contrib themes in order to understand different approaches. If it's only about some styling changes, you could also use a minimalistic theme and change it according to your needs.

> A lot of styling that I made with HTML/CSS was missed up when I start creating contents and didn't appear as I expected.

Is it possible that you use a wysiwyg editor for content editing and that this interferes with the CSS in your theme?

**Edit:** The title in `node--article.tpl.php` will only be printed if the node is not shown as a full node (but in teaser view), e.g. no visiting `/node/NID`. That's controlled by the $page variable. Once again, please look at the default node template: node.tpl.php to see what variables are available and what they mean. If you visit `/node/NID` then the default behavior in Drupal is that the page title (the one used in `page.tpl.php` is set to the node title and displayed in the page template, not in the node template. You can change that off course, but you have to adapt the display logic inside the templates to match your needs. You could try something like the following.

In `page.tpl.php`:

```
<?php if (!isset($node) || $node->type != 'article'): ?>
    <?php print render($title_prefix); ?>
    <?php if ($title): ?><h1 class="pageTitle"><?php print $title; ?></h1><?php endif; ?>
    <?php print render($title_suffix); ?>
<?php endif; ?>

```

This will print the page title only if you are not on a node page or if the node is not of type article.

In `node--article.tpl.php`:

```
<?php print render($title_prefix); ?>
<h3 class="postTitle"><a href="<?php print $node_url; ?>"><?php print $title; ?></a></h3>
<?php print render($title_suffix); ?>

```

This will always print the nodes title whenever `node--article.tpl.php` is used, regardless if the node is displayed as a full page or as a teaser view.

---
Tags: theming
---


title: How to add more data to a field

text:
# Question
Title: How to add more data to a field
I'm trying to find the best way to extend a field's data set (not even sure of the right terminology).

What I want, is to attach some other information to an existing field. Let's take a file field, called "my\_file", and attach some "other" information to it.

The end result should be, when using `node_load` and `entity_metadata_wrapper`, I can get the "other" value.

So these code snippets should give me the value:

```
$node = node_load($nid);
return $node->field_my_file['und'][0]['other'];
// And this should work:
$wrapper = entity_metadata_wrapper('node', $node);
return $wrapper->field_my_file->other();

```

I'm not that familiar with the Field API, so if you can point me in the right direction that'd be good.

# Answer
Hm, if I understand you correctly you want to extend a fields schema. As far as I know, there is no easy way of doing this, e.g. there is no `hook_field_schema_alter()`. And the way that comes into my mind to achieve this is rather complicated and involves a lot of different hooks and logic that seems just bloated and error prone.

Instead I would recommend to create a new field type module based on the one that you want to extend, then alter this so that it suits your needs. Obviously this should only be done if you are still in the development phase of your site. If there is already any content this could do more harm than good, because you would need to migrate the content.

Another way, little elegant, but certainly possible is to create your proper storage solution for the information that you want to attach to the field(s) in question, meaning providing custom database tables and implementing the hooks described in field.api.php that you need for your use case.
> 1 votes

# Answer
All this will work if you add the Fields to your Drupal Nodes.

You may add the `Fields` to your content type (a Node) as a administrator at the following url of your site: `/admin/structure/types/manage/NODE_TYPE/fields`

**EDIT**

read up on an Introduction to Entities in Drupal 7.
> 0 votes

---
Tags: entities
---


# Question
Title: Good method/approach in improving advanced Drupal development skills
This might be a bad place to post this, but here it goes.

I'm looking for a good approach in bettering my knowledge/skills to Drupal. I have been using it since D5 and I still feel like I am so 'unskilled' in doing advanced development. I still struggle with how to create a custom module or hook alter methods properly (with 1 try and not 10) through the template.php file. I have seen others create some insane modules or scripts and I just boggles me on how they come up with it.

It's always been trial-and-error for me, and sometimes I get it to work but never can get an answer on 'Why that worked'.

I have been a php developer for over 10+ years, touched a bit of C#, Ruby, and Java but nothing hugely professional. I have always been driven to continue pursuing Drupal development. Just so incredibly overwhelming still at times. I have high hopes to make the next DrupalCon in Austin, Texas.

# Answer
> 2 votes
I have found the Drupal Examples module to be a great starting point for learning enough to develop my own modules, or to aid in solving a particularly thorny problem I'm having.

There's also the Devel and Dev Themer modules, which help to illuminate some of what's going on behind the scenes.

Then there is the API documentation, which I personally have a harder time understanding until I read some of the comments.

These are the ones I use most; others will probably chime in with others, which I know about but lack enough experience in to form a helpful opinion.

---
Tags: 7, theming, community-official-site
---


# Question
Title: Drush command to show site information configuration
I would like to display all available information about a site using its alias name.

the closer thing I could find is drush status.

```
$ drush @loc.my-project-7-26-2-5-dev status

```

> PHP executable : xxxxxxxx
> PHP configuration : xxxxxxxx
> PHP OS : xxxxxxxx
> Drush version : xxxxxxxx
> Drush configuration : xxxxxxxx
> Drush alias files : xxxxxxxx

I would like the site information, such as Drupal version, profile name, default theme, temporary directory path etc.. to be displayed instead.

# Answer
> 6 votes
If you are running multisite then you can do

```
$ drush @sites status

```

Or site specific

```
$ drush [site-name] status

```

*Note : You should be in Drupal installation directory to run drush commands.*

---
Tags: drush
---


# Question
Title: Is it possible to use the batch API with transactions?
I'm using the batch api for reading large csv files and storing some information in my database. If something fails during the batch run I want all the processed information to be gone, I would like to use drupals transactions for this, but I don't know if this is supported.

If this is not supported is there any known workaround for this?

# Answer
> 2 votes
I'm afraid not. Batch API divides task into separate steps, each in it's own PHP call. In pure PHP (for simplicity) you use transactions like that:

```
try {
    // First of all, let's begin a transaction
    $db->beginTransaction();

    // A set of queries; if one fails, an exception should be thrown
    $db->query('first query');
    $db->query('second query');
    $db->query('third query');

    // If we arrive here, it means that no exception was thrown
    // i.e. no query has failed, and we can commit the transaction
    $db->commit();
} catch (Exception $e) {
    // An exception has been thrown
    // We must rollback the transaction
    $db->rollback();
}

```

To split it into multiple calls, you would need to store PDO object and pass it between calls, but PDO objects cannot be serialized.

**Workaround** would be to import to a temporary table, and when (if) it was successful, use one more batch api step to move data from temporary one to real destination. And that one last move you can do in one step, so you can wrap it with transaction.

---
Tags: 7, database, batch-operations
---


# Question
Title: Using Drush To Download Modules When You Dont Really Know The Name
Hello im a drush newbie and im enjoying ints functionality. Years ago i saw a video of someone using drush to download modules and if he got the project name slighly wrong t would show him some alterntives in his command line interface.

Did i imagine this or is it possible?

Thanks

ps i just use drush dl modulename at the moment

# Answer
Well I think your imagination did the trick! but the closest thing I can imagine is to use this sandbox module

> Allows you to search for modules from drush
> 1 votes

---
Tags: drush
---


# Question
Title: Drupal 7 CDN Module not altering URLs for themed Pages
I have themed a page on my Drupal 7 website by mentioning the template file as page--node--.tpl.php The CSS and Images which are coming on this page are getting picked from the site itself and not from the static url i have configured in CDN. Other than this page my website is picking CSS JS & Images from CDN Any suggestions ?

Basic page--node--123.tpl.php

```
<?php
global $base_url;
$img_actl_path =  "$base_url/".drupal_get_path('theme','theme-name')."/images/v1/";
?>
<a href="#"><img src="<?php print $img_actl_path;?>image1.jpg" width="380" height="197" /></a>

```

# Answer
> 3 votes
The problem is that you are not using the Drupal API.

The CDN module needs to be able to alter the path from your Drupal site to your CDN. It does this by catching the URL via `hook_file_url_alter()`, and changing it.

The proper way to to make a URL in this case is with `file_create_url()`. Something like this should work

```
function MYTHEME_preprocess_page(&$variables) {
  $path = drupal_get_path('theme', 'MYTHEME');
  $variables['mysrc'] = file_create_url($path . '/images/v1/image1.jpg');
}

```

And then in your theme you would use

```
<a href="#"><img src="<?php print $mysrc; ?>" width="380" height="197" /></a>

```

However, as Mołot suggests, using a proper theme function to make a renderable image would probably be best.

---
Tags: 7, cdn
---


# Question
Title: Invalid address: return even on successfully sent e-mail
Need help ASAP. My function is sending e-mail on successful quit. E-mail is sent well. The problem is that i'm always getting "Invalid address:" before my normal exit message. Code is following:

```
$message_text = array(
'id' => 'modulename' . '_' . 'key',
'to' => '2@example.com',
'subject' => "OK",
'body' => array("OK"),
'headers' => array(
    'From' => '1@example.com',
    'Sender' => '1@example.com',
    'Return-Path' => '1@example.com',
          ),
);
$system = drupal_mail_system($module, $key);
$message = $system->format($message_text);
$system->mail($message);

```

Thanks.

# Answer
This is because of the absence of $message\_text\['from'\]; In SMTP module smtp.module.inc line 74-85 there is hack that handles the absence of 'Reply-To' by setting it to $message\['from'\] which is also absent, consequently 'Reply-To' will be empty hence throwing the error Invalid address:. add $message\_text\['from'\] = 'your from address' this will solve the issue.
> 1 votes

# Answer
Try at last

```
$system = drupal_mail_system($module, $key);
if ($system->mail($message)) {
  // Success.
}
else {
  // Failure.
}

```
> 0 votes

---
Tags: 7, emails
---


title: Handling id from autocomplete field

text:
# Question
Title: Handling id from autocomplete field
I have an autocomplete field that selects id,text data from db table. I want to show the text in the field but need to put the selected id inside a hidden field so that, when the user submits the form, it is passed as form\_values\[\] to \_submit hook. Which is the correct way to do it in D7?

# Answer
> -1 votes
I've run into the same topics and found a solution, check it here: Autocomplete field - fill the selected id into another form element (eg. hidden field)

---
Tags: 7, ajax
---


# Question
Title: What is Content Construction Kit (CCK) in Drupal
What is Content Construction Kit (CCK) in Drupal and what is the purpose of CCK?

# Answer
It used to be called CCK in Drupal prior to Drupal 7, and came in the shape of a contributed module. In Drupal 7, most of the functionality of the CCK module was moved into the core and it is now usually referred to as "fields" (or "fields in core").

The purpose of the CCK was to provide a simple UI for adding new "fields" to entities so that new, specific content types could be created by site designers.

In Drupal 7, you do exactly the same thing by adding "fields" (which may be typed) to entities. A full tutorial about CCK/fields is beyond the scope of this Q+A site, but GIYF (Google Is Your Friend).

**Edit:** As noted in a comment by jimajamma, the CCK project page has more information and links to tutorials.
> 3 votes

---
Tags: entities
---


# Question
Title: How can I link a gallery made with views to another gallery made in views?
I am trying to do a gallery with a page of preview of the pics, I got how to do it with views and tags for the full size pictures and with image styles; I got the preview gallery (btw for this one I am using Nodequeues). Now I don't know how to link the galleries from the previews to the full size ones, I did try with the output linking in the override section of the view, I tried creating a new field with the URL and nothing, it always links to content/node but not to /photos/node

Btw this is the website http://www.nellens.com/home/

Thank you.

# Answer
If you are looking for using a view into another as a field then you can use Views Field View to achieve this.

Module page describe :

> This module allows you to embed a view as a field in a view. A new field handler is made available, so this can also be used in area (header/footer/empty) handlers as well as rows.
>
> This view handler can accept arguments from fields of the parent view using tokens and pass them into the child view for each row. Raw or rendered token values can be used, as well as static values.
> 0 votes

---
Tags: views, media, navigation, uri
---


title: jplayer in drupal 7 preloads the audio

text:
# Question
Title: jplayer in drupal 7 preloads the audio
There is a content type called `song` and it has a file fields. I'm going to add a player on website using jplayer. the problem is, it preloads all of the songs. I mean all of the songs in the page are loaded with the page while I want it to be loaded when the user clicks on the play button. any idea or alternative for jplayer?

# Answer
> 1 votes
try to use MediaElement and library MediaElement.js
simply install and enable it and put the library in sites/all/library/mediaelement .

Creat content type and add song/video field then go to manage display anad select which type of media you want (Song or Video)
That's it , you're done
let me know what's happen ;)

---
Tags: javascript
---


# Question
Title: Drupal Login for my Android application?
How to use drupal login in my android application I want to use the same database that is used in the drupal site.I want to login with the same user name and password that is used in drupal

Please any one help me with this

# Answer
Services module allows remote login validation using REST calls.
> 3 votes

# Answer
This is a complex topic and probably too broad of a question. That said, there was a session about automatically generating Drupal apps using Phonegap at Drupalcon Denver 2012. The beginning of the presentation gives a decent overview of the many different ways in which Drupal can interact with mobile apps.
> 1 votes

# Answer
Simply use the Phonegap and DrupalGap module, install and set permission for the same and use this code http://code.google.com/p/drupal-phonegap/downloads/list and paste into your assets Directory in your android project and copy apk file from bin directory and use it in your phone instead of using Emulator

What u need is

1) JDK(6) 2) Eclipse 3) ADT 4) PhoneGap and DrupalGap modules On your drupal Site

While using this u need to set(append) your Enviornment Variable from this link http://docs.phonegap.com/en/2.2.0/guide\_getting-started\_android\_index.md.html#Getting%20Started%20with%20Android

Hope it will Help you :-)
> 1 votes

# Answer
DrupalGap has this feature out of the box. Otherwise you can use the Services module and the User Login Resource.
> 0 votes

---
Tags: 7
---


title: drupal7 Webservices create a node

text:
# Question
Title: drupal7 Webservices create a node
I am using Drupal 7 and creating a webservice. and using **http://delta.indivar.info/tanenttest/drupalgap/node** this webservice. i am trying to create a node using poster plugin of Firefox and i am passing parameters as

type='page'

it shows \["Access denied for user anonymous"\]

i can't give permission for Anonymous user. is there is any way so that only authenaticate user can create node.

# Answer
> 0 votes
When using the Poster plugin for Firefox, you need to be logged into your Drupal site in another tab. Then you can use the Node Create resource. Keep in mind that you'll need to pass along the X-CSRF-Token in the header of the request. You can get the token from here, after logging in:

http://www.example.com/?q=services/session/token

---
Tags: 7
---


# Question
Title: Why does the Configuration Management module warn not to use in production?
In the Configurations Management module, right before you click the Import button, it warns:

> Importing configurations will write your configurations directly to the activestore. **DO NOT USE THIS ON A PRODUCTION SITE!**

Should I heed this warning? If so, why? What's the point of this module if it shouldn't be used in production?!

# Answer
> 1 votes
As you can see module is in Alpha phase. It's available for community testing so that they can able to fix issues and make it stable.

Every project in Drupal.org go through different phases. Please see more above Project Versions here.

Alpha version refers to

> These are the first to come out, and are therefore the least stable. Most reported errors are resolved but there are most likely still outstanding known issues, which might include security issues.
>
> These releases are not yet stable enough for production use, but are essential milestones on the way towards the official release. They allow a much wider pool of users to test the latest code and provide feedback before the official stable release. These releases should only be downloaded and used by developers very familiar with Drupal or those wishing to help find bugs in the software.

Since Drupal projects entirely community driven, Module maintainers releases projects for testing. Once they are stable you can use them in Production Environment.

---
Tags: 7, configuration
---


title: "Node Picker" for custom module?

text:
# Question
Title: "Node Picker" for custom module?
I'm building a custom module so the editors at my company can select several nodes and spit them out as a newsletter. There are some modules that get me halfway, but due to some specific requirements, coupled with me really wanting to wrap my head around creating custom modules, I'm starting from scratch.

I understand the hooks, and have set up the menu, permissions, and most of the form fields where users can select a template and other options. I'm stuck at the part where they actually pick the nodes.

I was thinking I can probably create a View with some exposed filters and maybe hook into that, if it's possible. Ideally, I'd let them drag and drop the nodes, reorder them, etc.

I'm not looking for someone to code this out for me, would just like to be pointed in the right direction.

# Answer
Without knowing the full scope or what modules/custom code you've already developed, this could be done fairly easily with a hook\_menu, custom form and a content type. The new content type would have a multi-select (probably auto complete) node reference field which will allow for simple reordering. You could then implement a hook\_menu with a custom form returning all the newsletters in a select list and when the form is submitted you can use node\_load() to get all the referenced nodes from the selected node. Your submit handler would pass the applicable values to whatever batch mail module/functions you're using.
> 0 votes

---
Tags: views, 7
---


# Question
Title: Within Panels, get node ids that contain taxonomy term
I have a panel with a content pane that shows a node based on the Taxonomy Term Name in the URL of the panel. This is working using "(Content) Content: Has taxonomy term ID" as a contextual filter, and "From panel argument" within the content pane.

I am also wanting to add the add comments form to the panel. Which could be done using the nid of the node displayed in the above mentioned panel.

So, from within panels, how can I get the nid of a node that has the taxonomy term as a field, where the taxonomy term is within the URL?

Can taxonomy\_select\_nodes($array\_with\_tids); be used within panels?

Using Drupal 7, Panels 7.x-3.3

Thanks

# Answer
> 0 votes
Rather than getting the nid from within Panels, I just used taxonomy\_select\_nodes and passed the result to panels as a second argument in the URL eg panels-view/%tid/%nid.

This solved my problem.

Thanks

---
Tags: panels
---


# Question
Title: How can show block when mouse over icon in menu
How can show block when mouse over icon in menu like this

when i put mouse in any link in this menu its show me block.

How can i do this.

# Answer
That looks like a "Megamenu" type menu configuration.

You could try using a module like

To acheive that design effect.
> 1 votes

---
Tags: routes, blocks
---


# Question
Title: "Signature" user field not appearing in list of user fields
I have the Drupal core *Signature* field that appears on the user edit page; it doesn't seem to show up as a field on the *Manage Display* tab when I go to re-order and group the fields on the edit page.

Does anyone know how I can get this field to appear in the field list with the rest of the fields so I can group and reorder it?

# Answer
While it doesn't appear that you can put it in the field list directly and drag and drop it around as the user module only exposes the account and timezone in its hook\_fields\_extra\_fields(), you certainly can move it around "manually" in a hook\_form\_alter() in a custom module, eg something along these lines:

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

  switch ($form_id) {

    case 'user_profile_form':

      drupal_set_message('<pre>' . print_r($form, TRUE) . '</pre>'); // to see what you have to work with

      $form['signature_settings']['#weight']='8';
      $form['field_my_second_custom_field']['#weight']='9';

      break;

    // other forms go here

  }

}

```

...which, if you had the following in your user:

...would create this in the edit form:

...eg, we moved the `#weight` around, which is what the drag and drop anchors do in the UI.

In this example, `user.module` initially creates the signature settings with a weight of 1, and then the custom fields with 7 and above, so, by changing the weight to 8 for the signature settings and the next field to 9, it puts it between those two fields. Check out the Drupal Form API and #weight for more information on what this is all about.

If you click `show row weights` at `admin/config/people/accounts/fields` you can see this more directly:

**ADDITION: Using Field Groups**

If you had it set up like this:

...and wanted to put the signature settings inside the "My Group" field group, you could do something like this:

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

  switch ($form_id) {

    case 'user_profile_form':

      $form['signature_settings']['#weight']='6';
      $form['field_my_second_custom_field']['#weight']='7';

      $form['#fieldgroups']['group_my_group']->children[]='signature_settings';
      $form['#group_children']['signature_settings'] = 'group_my_group';

      break;

    // other forms go here

  }

}

```

...which would produce this:

**YET MORE ADDITIONS: Tab Groups**

If you want to put it in a tab group, eg:

...this will do it:

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

  switch ($form_id) {

    case 'user_profile_form':

      $form['signature_settings']['#weight']='6';
      $form['field_my_second_custom_field']['#weight']='7';

      // $form['#fieldgroups']['group_my_group']->children[]='signature_settings'; // apparently this isn't needed afterall
      $form['#group_children']['signature_settings'] = 'group_my_group';

      break;

    // other forms go here

  }

}

```

...which produces this:
> 4 votes

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


# Question
Title: How can I check which nodes have the highest value in a certain field?
My content type 'Article' has an integer field called 'Ranking'. How can I check which nodes have the three highest values after saving a new node or comment? I'd like to use the result in a rule, so I'm looking for some kind of "The node has ranking 1/2/3" condition.

Any ideas how I can achieve this?

# Answer
If within your Computed Field you've selected `Store value in the database`, you can easily use Views to sort results based upon this field.

So, for example, in broad strokes, you could create a View that filtered on whatever you needed, most probably published and node type; then for sort, you would select this field and select descending; in paging, you'd select a specific number, eg, 3; and in fields, you'd select whatever you wanted to display.

If you wanted to have a block of the top three nodes, in the fields I could see you selecting the title and so forth, but if you are wanting to see if a specific node was in the top three, I'd just put the node nid in there.

So, if that's the case, when this View is run, it will return three nids.

If you look into views\_get\_view\_result() you can quite easily access that output, eg:

```
$result=views_get_view_result('top_three'); // or whatever the name of the view is

```

will populate `$result` with something along these lines:

```
Array
(
    [0] => stdClass Object
        (
            [nid] => 2340
            [node_created] => 1390349535
        )

    [1] => stdClass Object
        (
            [nid] => 1176
            [node_created] => 1390086303
        )

    [2] => stdClass Object
        (
            [nid] => 1133
            [node_created] => 1390086313
        )

)

```

So, now you just have to look in there to see if your current nid is in there and if so, act accordingly.

Now, of course, the other question is where to put all of this? I'd suggest looking into hook\_node\_update() but be aware of the performance considerations of doing all of this each time a node is updated. Caching is certainly your friend here.
> 1 votes

---
Tags: rules, 7
---


# Question
Title: How can i allow users to give different responses to content types other than comments?
How can i allow users to give different responses to content types other than comments? for example if i want users to be able give blog posts a "like" or "thumbs up/down" or something similar?

# Answer
> 1 votes
You could try any of these modules (with quotes included from their project pages):

* Fivestar:

> ... adds a clean, attractive voting widget to nodes and comments and any entity.
* Rate:

> ... provides flexible voting widgets for nodes and comments ("*The cck model for voting with Drupal*").
* Vote Up/Down:

> ... allows votes on some Drupal entities and provides the base for implementing votes on other entities.

---
Tags: nodes, comments
---


# Question
Title: How to filter a field in the add content window in Drupal?
I am very new to Drupal so I'm sorry for my lack of familiarity with Drupal terminology.

I have a content type with multiple fields (A, B, C, etc..). Each field is a selectable vocabulary list. I would like the user to select any terms in A and B fields. But I want only relevant terms to display in the C field (depending on A and B selections). In this way, A and B are independent fields and terms that appear in C are dependent.

**Example:**

Content type: Food dish at a restaurant

Field A: Appears on Menu type (Breakfast menu, lunch menu, dinner menu, wine list,etc.)

Field C: Appear in Menu section (Appetizers, Entrees, Deserts, etc.)

If the user selects "Breakfast Menu" for field A, it wouldn't make much sense to allow the user to select "Desert" for field C. But selecting "Appetizers" or "Entrees" would be fine. I want to filter the selectable terms in field C depending on which options are selected for field A.

Thank you for helping me out! Really :)

# Answer
You can try the Conditional Fields module. It allows you to show/hide fields based on the value of other fields.

The Hierarchical Select module suggested in jimajamma's answer is meant only for hierarchically structured vocabularies. Conditional fields doesn't have a fancy animated interface like HS, but it provides more flexibility. For instance, you could make a text field depend on a taxonomy term:
> 1 votes

# Answer
I would look into the Hierarchical Select Module:

> This module defines the "hierarchical\_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.

With it, you should easily be able to do your A & C hierarchy; since you only briefly mention B, I don't know what you need to do with that.
> 0 votes

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


# Question
Title: How to run code after hook_node_delete has completely run?
I have a node to which I have a number of images attached through the usual content type image field mechanism. The attachment is done correctly, such that when I delete the node, the images are also deleted.

My problem is that these images are held in a subdirectory, which is not deleted by the file deletion process, and I end up with a bunch of empty and useless directories littering my file system. I tried deleting the directory with `hook_node_delete()`, but this fails because Drupal hasn't yet gotten around to deleting the images when that hook gets called, and the `rmdir()` function I was using to delete the directory fails because the directory isn't empty.

So: Is there a hook I can call that will run after the files have been deleted? I suppose I could write my own code in `hook_node_delete()` to delete the files and then the directory, but I'd rather not hack around the architecture like that, if possible.

# Answer
> 2 votes
You may want to look into hook\_field\_attach\_delete(). This runs after all fields have been removed from a node/entity. So, if all the file fields (and the actual files) have been removed, and all of them in such a node are all in one directory and they are the only files in that directory, removing that directory in this hook should succeed.

# Answer
> 1 votes
You could try instead using

`hook_file_delete`

> Respond to a file being deleted. - $file: The file that has just been deleted.

e.g:

```
/**
 * Implements hook_file_delete
 */
function MYMODULE_file_delete($file) {
  // Attempt to delete empty file directory, on error resume next
  @drupal_rmdir(dirname(drupal_realpath($file->uri)));
}

```

Might not need drupal\_realpath, but that should work.

---
Tags: 7, nodes
---


# Question
Title: colorbox custom caption via field collection
I want to have a content type with a field collection of an image and a text field. The image is to be displayed via Colorbox, the text field is to be used as the caption for the image.
I am sure I achieved this without problems before.
When I want to chose the relevant token for the custom image caption in cbox, the token browser does not allow me to use the other field. Only the current date, page use, files, random and site information token groups are available (see image below).
What am i doing wrong?

# Answer
One needs to enable the entity API / entity token (included in Entity API) modules. The field collection text fields become available to tokens and can thus be used as captions.
> 0 votes

---
Tags: entities, javascript
---


# Question
Title: Drupal Commerce order total amount not update after I programmatically changed line item's price
I am using Drupal Commerce. Now I have to alter the product price programmatically. After search on google and here, I found some people did it: Alter cart unit price and total amount

Then I made a test by using hook\_commerce\_cart\_order\_refresh(). Here is my code:

```
function mymodule_commerce_cart_order_refresh($order_wrapper){
    foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
        $line_item = $line_item_wrapper->value();
        $qty = $line_item->quantity;
        $line_item->commerce_unit_price['und']['0']['amount']=100;
        $line_item->commerce_total['und']['0']['amount']=$qty*100;
        commerce_line_item_save($line_item);
    }
}

```

It changed the cart and order line item unit price and line item totoal amont. But the order total will not changed. Still calculated on the old price.

I also notice somebody have the same question:Order Total not updating after I change the line item price , but I don't know that answer how it works. It said using following code:

The solution was to use commerce\_price\_add\_component()

```
$line_item_wrapper = entity_metadata_wrapper("commerce_line_item", $commerce_line_item);
$line_item_wrapper->commerce_unit_price->data = commerce_price_component_add(
    $line_item_wrapper->commerce_unit_price->value(),
    'base_price',
    array(
            'amount' => $booking_price,
            'currency_code' => 'AUD',
            'data' => array(),
    ),
    TRUE
);

```

But I don't know where to use the above code, put in a hook?

Is some one can give me a idea?

# Answer
I'v found the way. Put answer here:

```
function mymodule_commerce_cart_line_item_refresh($line_item, $order_wrapper){
    $line_item->commerce_unit_price['und']['0']['amount']=110;
    $line_item->commerce_unit_price['und']['0']['data']['components']['0']['price']        ['amount']=110;
}

```

Because the commerce\_order\_calculate\_total() is based on components, so if you only changed the commerce\_unit\_price amount is not enough. Must change data also.
> 2 votes

---
Tags: commerce
---


# Question
Title: How to add a custom class or id to a menu
I have several menus that I want to use, and theme differently. I'm looking into different ways to theme them and it appears that the most elegant way would be to use the template.php file with menu tree. I'm not quite sure how to set different conditions for different menus in this file however.

# Answer
> 2 votes
Menu Attributes is definitely a way to do this.

> This simple module allows you to specify some additional attributes for menu items such as id, name, class, style, and rel.
>
> You should use this module when
>
> * You want to "nofollow" certain menu items to sculpt the flow of PageRank through your site
> * You want to give a menu item an ID so you can easily select it using jQuery
> * You want to add additional classes or styles to a menu item
>
> The module currently allows you to set the following attributes for each menu item:
>
> * Id
> * Name
> * Target
> * Rel
> * Class
> * Style
> * Accesskey

---
Tags: 7, routes
---


# Question
Title: How to change the label of the "To:" field in the Date Module
This doesn't seem to be the kind of thing you can change using `hook_form_alter()` unless I'm missing something.

The label of the "From" field can be any value you want, but the "to" field, if you have one, defaults to "to", see `modules/date/date_elements.inc`, line 369:

```
    $element[$to_field]['#title'] = t('to:');

```

so what's the correct way to change that to a value of my choosing, i.e. "Expires"? Via the Theme?

# Answer
If you look further on down in `date_elements.inc` at line 412 you'll notice:

```
drupal_alter('date_combo_process', $element, $form_state, $context);

```

which allows any module to alter what it's created, eg, something like this:

```
function YOURMODULE_date_combo_process_alter(&$element, &$form_state, &$context) {

  $element['value2']['#title'] = t('expires:'); // this will change that to: to expires:

}

```

Just realize this simple example will do this for every instance of a combination to/from date, but information to get more specific is contained in `$element`, `$form_state` and `$context`. For example, the specific field name is contained in `$element['#field_name']` and the form\_id is in `$form_state['build_info']['form_id']`.
> 3 votes

# Answer
I always do this kind of thing with `hook_form_alter()` and `pre_render` function: example:

```
function MY_MODULE_OR_THEME_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'MY_FORM_ID') {
   $form['#pre_render'][] = 'MY_CUSTOM_pre_render';
  }
}

function MY_CUSTOM_pre_render($element) {
  //dpm($form);
  //$element['MY_FIELD_NAME']['max']['#title'] = t('MY NEW TITLE'); // Find your proper field element.
  return $element;
}

```
> 1 votes

# Answer
There is a module named String Overrides that lets you override any string that is inserted via the `t()` function. You should be able to use that to module override "to:".
> 0 votes

---
Tags: 7, theming, forms, datetime
---


title: Add a custom VBO action

text:
# Question
Title: Add a custom VBO action
I want to add a custom VBO action.

It display in the actions list of the view, it should like a tree, like this:

-Add Role-

RoleA

RoleB

-Remove Role-

RoleA

RoleB

And When I select RoleA(-Remove Role-), check some users, click the submit.

The users checked should be removed RoleA.

How can I code a custom VBO action like this ?

# Answer
> 0 votes
You can create custom VBO action by implementing `hook_action_info()` hook. Here are some useful links which can help you achieve what you want:

1. Views Bulk Operations development guide (Drupal 7)
2. Programmatically adding and removing roles to users in Drupal
3. HOWTO assign a user to a role programatically

additionally, Examples module can help you to learn about `Actions`.

---
Tags: views
---


title: make field group repeatable

text:
# Question
Title: make field group repeatable
I am using Field Group module and I would like to make certain group repeatable if needed, like adding a plus (+) icon next to it. Is that possible? and how?

# Answer
> 0 votes
You could try the Field Collection module. It allows you to group fields and add more of these "collections" inside the same node. Works great for slideshows for instance when you don't know how many images the site editor wants to use and you need custom fields (like big headline, small headline, promo text, link etc) grouped with the image.

---
Tags: entities
---


# Question
Title: How to resolve max execution time error in Drupal commons?
Getting this error on xampp using drupal commons distribution , by opening localhost/commons

```
PHP Max Execution Time  30
Your PHP execution time is too low, please set it greater than or equal to 120 seconds.

```

What to do?

# Answer
go to `php.ini` and then find `max_execution_time` and set `120` or more what u are comfort with.
> 3 votes

---
Tags: 7
---


# Question
Title: Custom redirect on custom page for admin user
I've created a basic page with url login.

The node id is 129 and I've made a custom `page--node--129.tpl.php` in my theme. On that file I've put this:

```
<?php print $messages; ?>
<div class="admin-login">
<?php print drupal_render(drupal_get_form('user_login')); ?>
</div>

```

So on this page I'm rendering the user\_login form and I'm using it as a page for admin login. How can I set redirect when admin is logging, lets say to admin/content?

# Answer
I've managed to solve this by using Rules module and here's the process, so maybe will help someone.

Create a new rule.

Events: User has logged in.

Condition: User has role

Actions: Page redirect
> 0 votes

# Answer
Implement `hook_user_login()`:

```
function MY_MODULE_user_login(&$edit, $account) {
  if(/* CONDITION, e.g.: $account->uid == 1 */) {
    $edit['redirect'] = 'admin/content';
  }
}

```
> 2 votes

---
Tags: forms, redirection
---


title: Loading fields of a node

text:
# Question
Title: Loading fields of a node
I have a simple content type, which contains the fields:

* Title
* Body

In my view the titles of the above content type are listed. When I click on a title, I want the body of the corresponding node to be loaded with AJAX and appended after the title.

Has anyone a hint for me, how to accomplish that?

# Answer
Use built-in Drupal Ajax framework.. Steps:

* implement hook\_menu
* build ajax callback
* render links (titles) like `/[menu callback menu item]/nojs/arguments` and add class `use-ajax`

Here is a good tutorial: A little Ajax-driven article reader built with the Drupal Ajax framework
> 5 votes

# Answer
You can use Views Accordion module for the same. Module uses jquery accordion style plugin to show hide contents. It's not exactly what you are looking for since module uses hide and show concept instead of Ajax calls to load content. But User Experience wise good option.

Project Pages says

> Views Accordion provides a display style plugin for the Views module. It will take the results and display them as a JQuery accordion, using the first field as the header for the accordion rows.
> 2 votes

---
Tags: views, ajax
---


# Question
Title: User registration form: Give username "username n+1" value, if and when n is already used
I'm using the first & last name in the user registration form to generate the username for the new user:

```
$firstname = $form_state['values']['field_firstname'][LANGUAGE_NONE][0]['value'];
$lastname = $form_state['values']['field_lastname'][LANGUAGE_NONE][0]['value'];
$username = $firstname.''.$lastname;
$result = db_query("SELECT COUNT(*) FROM {users} WHERE name = :name", array(':name' => $username));
$results_number = $result->rowCount();
if ($results_number == 0) {
    $form_state['values']['name'] = $username;
}
else {
    $i = 1;
    $username = $firstname.''.$lastname.''.$i;
    while ($results_number > 0) {
        $result = db_query("SELECT COUNT(*) FROM {users} WHERE name = :name", array(':name' => $username));
        $results_number = $result->rowCount();
        $i++;
        $username = $firstname.''.$lastname.''.$i;
        $form_state['values']['name'] = $username;
    }
}

```

But I get an infinite loop. There is a problem with that while loop, any suggestions on the best way to fix that?

# Answer
So here is what I used to increment the username's suffix by 1 if the initial value is not found:

```
function increment_string($str, $separator, $first = 1) {
    preg_match('/(.+)'.$separator.'([0-9]+)$/', $str, $match);
    return isset($match[2]) ? $match[1].$separator.($match[2] + 1) : $str.$separator.$first;
}

$username = $firstname . ' ' . $lastname;
$result = db_query("SELECT uid FROM {users} WHERE name = :name", array(':name' => $username));
$results_number = $result->rowCount();
    if ($results_number == 0) {
        $form_state['values']['name'] = $username;
    }
    else {
    while ($results_number >= 1) {
        $username = increment_string($username_to_store, ' ');
        $result = db_query('SELECT uid FROM {users} WHERE name LIKE :name_pattern', array(':name_pattern' => db_like($username)));
        $results_number = $result->rowCount();
    }
    $form_state['values']['name'] = $username;
    }

```
> 1 votes

# Answer
Try below solution.

```
$firstname = $form_state['values']['field_firstname'][LANGUAGE_NONE][0]['value'];
$lastname = $form_state['values']['field_lastname'][LANGUAGE_NONE][0]['value'];
$username = $firstname.''.$lastname;
$result = db_query("SELECT uid FROM {users} WHERE name like '$username%'");
$results_number = $result->rowCount();
if($results_number == 0){
  $form_state['values']['name'] = $username;
}else{
  $form_state['values']['name'] = $username.$results_number;
}

```
> 0 votes

---
Tags: forms
---


title: Cached taxonomy menu block problem?

text:
# Question
Title: Cached taxonomy menu block problem?
I created a taxonomy menu block based on a vocabulary I have. It didn't work how I wanted so I removed it. I have created a view (page) that has the same URL as one of the links in the taxonomy menu block, and that URL displays nothing (which is what happened when it corresponded to a link in the TMB), even though it shouldn't - its preview displays a list of content items. If I modify the view's URL the content displays, if I set it back to what I want it to be it displays nothing.

I've cleared Drupal's cache and even removed the TMB modules, but I still get the same thing.

Am I right to think it's likely to be related to the TMB that I got rid of? And can anyone suggest any steps to getting the content to display on the URL?

Thanks,

Toby

# Answer
I've resolved this, I think, but would be interested to hear if there are alternative solutions. I *think* the Taxonomy Menu Block was a red herring - it was just using the URL alias for the associated term references, which exist whether or not a TMB is used. My view had the same URL alias, hence the conflict; setting either alias to something else was all that needed to be done.
> 0 votes

---
Tags: views, taxonomy-terms, routes
---


# Question
Title: An illegal choice has been detected. Please contact the site administrator is given on ajax form after programmaticly adding an item to a select list
I have a form in Drupal. On a select list I am using the ajax built into the form api to trigger a callback on change.

I need to be able to add an option to the select list via javascript. Set the value on the select list to be that new value and then trigger the ajax call.

I have something like:

```
var select_list = $('#edit-example');

select_list.append($("<option></option>")
  .attr("value", data.ObjectID)
  .text(data.Name));
select_list.val(data.ObjectID);
select_list.change();

```

Where data is a JSON object.

So the option is being added to the select list. The value has changed to my new option. I trigger the ajax event. However I am getting the error message:

> An illegal choice has been detected. Please contact the site administrator.

The callback is working fine except the error is displayed. What can I do to stop this message appearing?

# Answer
Upon validation, the FAPI checks that the values given for any select/option/radios match what was originally available when the form was first built. This is a security check, and is built in to all form processing.

Changing the values of an existing select list with javascript means your form has been altered outside of Drupal's control (perhaps maliciously, the FAPI cannot know), and so the validation fails.

To stop the message appearing, you should use the AJAX framework to build you form, instead of manipulating it directly with jQuery.
> 6 votes

---
Tags: forms, javascript
---


# Question
Title: Panel pages context and View contextual filters - cannot get it working
I have a content type which has field\_section of type Taxonomy term.

**Views**

I created a View pane with contextual filters set to field\_section. It means that the view pane should show all nodes which have field\_section set to a specified value. It works when manually setting the section in Views preview, e.g. to 39.

In the Views contextual filter settings, in the section "WHEN THE FILTER VALUE IS NOT AVAILABLE", it says "This display does not have a source for contextual filters, so no contextual filter value will be available unless you select 'Provide default'." But what default value to choose? All values with "url" are no good, because there is nothing in the url.

**Panels**

I created a Panel Page for the home page. The page address is like http://example.com. I added the View pane.

In the Panel page, View pane settings there are no settings at all:

I've added a context and a relationship to the Panel page (not sure if relationship is necessary):

Previously, I've been passing page arguments to view panes by configuring the "Argument input" setting in Views, and it was working. But in this case, there are no page arguments. I want to pass a specific term ID tid=39 to the view pane and don't know how.

# Answer
> 5 votes
1) Views -\> Contextual filter: add a filter

2) Views -\> Pane settings -\> Argument input: choose "Input on pane config" (notice the label)

3) Panel page -\> Content: add the View pane

4) Panel page -\> Content: in the pane settings, set the argument (notice the same label)

5) For this scenario, the Panel page -\> Context is not needed

---
Tags: 7, panels, views
---


# Question
Title: How to redirect before page processing along with all the sent data?
I have a link on my Drupal page. This link points to the page "\node\23423". When user clicks on this link, the user should get redirect to another path "\node\45644".

But this should happen before Drupal starts processing the original path. Also any POST data that is being sent to the original page should be passed to the next redirect page.

Is there a possible way to do this?

# Answer
> 0 votes
My suggestion (experimental) is something like this (but NOT RECOMMENDED):

```
function MY_THEME_preprocess_page(&$variables) {
  if(arg(0) == 'node' && is_numeric(arg(1))) {
    $nid = arg(1);
    if($nid == '23423') {
      drupal_goto('node\45644');
    }
  }
}

function MY_THEME_node_view($node, $view_mode, $langcode) {
  if($node->nid == 45644) {
    $old_node = node_load(23423);
    $old_node_view = node_view($old_node);

    $node->content['body'] = $old_node_view['body'];
  }
}

```

---
Tags: 7, redirection
---


# Question
Title: How can I leave empty values in gmap field?
I use gmap module to display a map on nodes that I want to have a location. On some nodes I don't want any location, and on those I don't want the map displayed at all. I tried to set default value in lat/long-fields to NaN or leave them empty, but then I get error when I save the node. Is there any way I can choose to display the map or not?

# Answer
If you want to have an option to leave field blank, simply don't make it required. Go to */admin/structure/types/manage/your\_content\_type/fields/field\_name* and clear the "required" checkbox.
> 0 votes

---
Tags: google-maps
---


# Question
Title: How to show taxonomy term image on node creation page drupal?
I have added an image field to my taxonomy terms. I upload images to each term. I just wanted to show term images on node creation page. Currently it showing term name only and showing image after node creation.
I want to show term image on node creation page.

Any help would be appreciated.

# Answer
Instead of term reference field try Entity reference field with Entity Reference view widget. This will help you to specify a view for field. Create an entity reference view that shows your additional image field. Select this view in your entity reference field settings.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Drupal Commerce "product type" vs kickstart "variation type"
I am new to online shops creation, and I am looking at Drupal Commerce and its popular distribution package, Drupal Kickstart.

I understand more or less the concept behind "product type" in Drupal Commerce, but Kickstart uses different terminology - "product variation type". Is it the same thing? Is there difference?

# Answer
> 5 votes
Product variations types within Drupal Commerce Kickstart are the same as product types referenced by vanilla Drupal Commerce.

I think the label changed within Kickstart so that it is a little less ambigious.

---
Tags: commerce
---


# Question
Title: Search box result => node add (searched string = node title)
What I want to achieve is quite simple, when performing a search trough the search block , instead of receiving the message "your search yielded no results" when the searched string is not in the DB I would like to have the possibility to add it as a node (question box "do you want to add yes or no?) , so the searched text would be the new node title.

# Answer
This is probably because of not indexing the content after adding it. You can re-index the site by visiting `http://<your-site-url>/admin/config/search/settings` and click "Re-index site".

P.S: This will queue the items for re-indexing. The items will actually be re-indexed when "cron" runs for the next time (manually or scheduled cron job.
> 1 votes

---
Tags: search
---


# Question
Title: get form_state values from ajax callback through hook_form_alter?
I'm having a little problem with my drupal 7 module. I'm trying to get the `$form_state['values']` from `$form['base']['st-volume-pricing']['price']` and `$form['base']['st-volume-pricing']['till-amount']` in my ajax callback so that I can add them to a results table.

Is this the right way to do it or am I missing something?

```
function mymodule_form_alter($form, &$form_state) {
  $form['base']['st-volume-pricing']['price'] = array(
    '#type' => 'uc_price',
    '#title' => t('Price'),
    '#description' => t('Set the price for this volume\'s reduction'),
    '#size' => 10,
    '#prefix' => '<table id="volume-pricing-standard-input"><tr><td>',
    '#suffix' => '</td>',
  );
  $form['base']['st-volume-pricing']['till-amount'] = array(
    '#type' => 'textfield',
    '#title' => t('Till Amount'),
    '#description' => t('The amount till which the volume discount applies'),
    '#size' => 10,
    '#prefix' => '<td>',
    '#suffix' => '</td>',
  );
  $form['base']['st-volume-pricing']['add'] = array(
    '#type' => 'submit',
    '#value' => t('Add'),
    '#submit' => array('mymodule_add_volume_standard'),
    '#ajax' => array(
      'callback' => 'mymodule_add_volume_standard_ajax_callback',
      'wrapper' => 'st-volume-results',
      'method' => 'append',
      'effect' => 'fade',
    ),
    '#prefix' => '<td>',
    '#suffix' => '</td></tr>',
    '#title' => t('Click this button to add a standard volume price'),
  );

  //this is our results table
  $form['base']['st-volume-pricing']['st-volume-results'] = array(
    '#type' => 'markup',
    '#markup' => '<table id="st-volume-results"><thead><tr><th>' . t('Price') . '</th><th>' . t('From Amount') . '</th><th>' . t('Till Amount') . '</th></tr></thead></table>',
  );
  variable_set('vol-st-price', NULL)
  variable_set('vol-st-from', 1)
  variable_set('vol-st-till', NULL)

  //this is our row that will be inserted
  $form['base']['st-volume-pricing']['st-volume-results']['row'] = array(
    '#type' => 'markup',
    '#markup' => '<tr><td>' . variable_get('vol-st-price') . '</td><td>' . variable_get('vol-st-from') . '</td><td>' . variable_get('vol-st-till') . '</td></tr>',
  );
}

```

When I'm using it inside here:

```
function mymodule_add_volume_standard_ajax_callback($form, &$form_state) {
  //check if there is a previous volume price and set the from field
  if (variable_get('vol-st-till') !== NULL) {
    variable_set('vol-st-from') = variable_get('vol-st-till') + 1;
  };
  //add or overwrite the value entered in price
  variable_set('vol-st-price') = $form_state['values']['base']['st-volume-pricing']['price'];
  //add or overwrite the value entered in till
  variable_set('vol-st-till') = $form_state['values']['base']['st-volume-pricing']['till-amount'];
  //create new row in results table
  return $form['base']['st-volume-pricing']['st-volume-results']['row'];
}

```

`drupal_set_message("<pre>" . print_r($form_state['values']) . "</pre>");` displays 1.

I suppose that $form\_state\['values'\] should only work during the submission of a form. How would one go about doing this when using a hook\_form\_alter() and ajax callbacks?

I also tried displaying `drupal_set_message("<pre>" . print_r($form_state['values']) . "</pre>");` in my `function mymodule_add_volume_standard`. Which also displayed 1. Neither does it work when trying it in the hook\_form\_alter() which is default behaviour I suppose?

I'd really appreciate it if someone could clarify some things for me.

# Answer
> 1 votes
Some basics:

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

```
1. `hook_form_alter` is a generic alter function that receives a third argument `$form_id` to distinguish the possible forms. Right now you would alter every form in your site.
2. The correct function signature is:

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

```

You can see, that the $form itself is passed as a reference and can be changed. There is no way of changing $form\_state directly during the form building process, which is when `hook_form_alter` is invoked.

Concerning `$form_state['values']` in validation and submit handlers: All elements defined in the `$form` array are by default inserted into a flat structure in `$form_state['values']`. This means that with your setup, you would access the value entered in `$form['base']['st-volume-pricing']['till-amount']` as `$form_state['values']['till-amount']`. You can change that behavior by defining `#tree`for the form element's parent, see for example: https://drupal.org/node/48643

**Edit:** The general approach for ajax forms is that in the submit you store values inside `$form_state`, e.g. in `$form_state['storage']`, set `$form_state['rebuild']` which assures that the form builder and hence your alter function is called again, and then test for the presence of stored values inside your form alter function. Depending on the submitted values you would then implement the logic to achieve what you want.

---
Tags: ajax, forms
---


# Question
Title: how can control of number word show in article in frontpage
I would like to limit the amount of text that show in frontpage. Is there an easy way to do this?

in general i do this :-

but in front page show me article as not good like this:-

its bad in style ,,, what can i do

# Answer
Select your body field within your view.

Click the **"Rewrite results"** fieldset and check **"Trim this field to a maximum length"**.

Set your maximum length and then check **"Trim only on a word boundary".**

This will prevent your body text from being cut off.
> 1 votes

---
Tags: charts
---


# Question
Title: Access Denied on file attachment when node state is Draft in Workbench
I have a file attachment field defined in a content type I have under Workbench moderation. The file field stores the attachment in the private files folder.

PROBLEM:

When I create a node for that content type and view it in Draft mode I get a 403 access denied if I try to download the file attachment with any role other than admin. If I publish the node I can download the file fine. Revert it back to Draft and I'm back to the 403 access denied.

I've tried enabling “Bypass moderation restrictions” for a role but that does not work around this error.

I really need a solution/workaround for this issue since I have a non-admin role that needs to be able review the node and the file attachment posted by users before they are published. I'm sure this is a fairly common scenario but I haven't been able to find any posts with a similar issue.

# Answer
> 5 votes
When using the private file system file\_file\_download() only checks access for files attached to the current revision of an entity (via file\_get\_file\_references()).

This is to stop users who have access to view the node from viewing files attached to old revisions (that might contain out of date files), and other similar things.

If there are no current revisions that contain that file it returns NULL, which then in file\_download() means that get access denied.

See a related drupal core issue: https://drupal.org/node/1453138
The D8 version of that issue is: https://www.drupal.org/node/1452100

In theory, you should be able to implement a hook\_file\_download() that checks all revisions by essentially copying file\_file\_download, but making file\_get\_file\_references() return for all revisions.

The problem with that solution is it can introduce a security hole, which is that users who have access to view the published version of the node can also now view files attached to other revisions of the node, which depending on your use case may or may not be an issue but since you are using the private file system in the first place I assume it might be a problem.

To avoid that, you could then implement hook\_file\_download\_access(), which does more complex access control than just calling node\_access() like the node\_file\_download\_access() function does. In that hook you would want current revisions to run through node\_access() and non-current revisions to use extra access control, like checking the users workbench permissions or node creation/editing permissions.

---
Tags: 7, workbench
---


# Question
Title: How to filter a view on a property of optional entityreference-related content (table join / views relationship)?
Consider this example: we have three content types: Concept, Language, and Word.

The Word content type has two entityreference fields:

* field\_concept references concept nodes, and
* field\_language references a language node.

The view shoud list all existing concepts, with related words (referencing the concept via entityreference) in a second column. The words are optional; we always want to show all concept nodes. We can accomplish this by creating a non-required Views relationship based on the field\_concept entityreference (Entity Reference: Referencing entity). (This results in a LEFT JOIN in SQL).

The problem is how to filter words on the field\_language value, without filtering out any of the concepts. Consider the following data.

```
Concept | Word   | Language
---------------------------
CAT
DOG     | Hund   | German
DOG     | chien  | French
FIRE    | fuego  | Spanish
WATER   | Wasser | German

```

Say we want related words (if any) filtered on a particular language. The desired views result for German is this:

```
CAT
DOG     | Hund
FIRE
WATER   | Wasser

```

We cannot use regular (grouped) filters with a condition like `field_language = German OR field_language = NULL`: while this would show CAT, DOG and WATER, it would remove "FIRE" from the results, since there is a Spanish result for FIRE.

So it seems we need to have a condition on the JOIN itself, preventing any words other than German ones to be joined. This question somewhat addresses how this should work, but: how would I access the field\_language values? This is the basic query created by Views to show the concept and word titles - I'm not seeing how I should modify this:

```
SELECT node.title AS node_title, node.nid AS nid, field_concept_node.title AS field_concept_node_title
FROM
{node} node
LEFT JOIN {field_data_field_concept} field_data_field_concept ON node.nid = field_data_field_concept.field_concept_target_id AND (field_data_field_concept.entity_type = 'node' AND field_data_field_concept.deleted = '0')
LEFT JOIN {node} field_concept_node ON field_data_field_concept.entity_id = field_concept_node.nid
WHERE (( (node.status = '1') AND (node.type IN  ('concept')) ))

```

It seems we cannot use the `field_data_field_language.field_language_target_id` value as a condition on the first LEFT JOIN without having another JOIN first, which would defeat the purpose - or am I missing something?

Can this be achieved with Views? Or are there alternative ways of doing this?

# Answer
> 0 votes
In the end I just had to turn my query around. While starting with a listing of concepts makes sense conceptually, this would require a subquery in order to join only words in a particular language to those concepts.

Instead, we can list all items in a particular language, and then RIGHT JOIN all concepts. The Views UI doesn't support RIGHT JOINs, but we can use hook\_views\_query\_alter to change the query to use a RIGHT JOIN, as pointed out here.

# Answer
> 2 votes
> It seems we cannot use the field\_data\_field\_language.field\_language\_target\_id value as a condition on the first LEFT JOIN without having another JOIN first, which would defeat the purpose - or am I missing something?

Why would adding the column defeat the purpose? Add `field_data_field_language.field_language_target_id` from your `Word` and `exclude` it from the Views display.

Then in your view under `Advanced Options` add a `tag` to the query such as `concept_word_lang_matrix_view`

Then in a custom module implement hook\_query\_alter() to add your custom join (but not muck with the View fields or anything directly persay -- your Join is just refining results fetched by your View configured in the Views Admin UI)

A sample implementation of hook\_query\_TAG\_alter looks like:

```
/**
 * Implements hook_query_TAG_alter for the Submission Is Open authentication
 * check of my business logic.
 */
function MYMODULE_query_SubmissionIsOpen_alter(QueryAlterableInterface $query) {
  #dpm(_MYMODULE_get_raw_sql_string($query));
  #dpq($query);
}

/**
 * This is a helper function to output the raw SQL from a db_select() type
 * query.
 *
 * Found via:
 * http://drupal.stackexchange.com/questions/51333/print-the-query-which-is-built-using-db-select
 */
function _MYMODULE_get_raw_sql_string(SelectQueryInterface $query) {
  $string = (string) $query;
  $arguments = $query->arguments();

  if (!empty($arguments) && is_array($arguments)) {
    foreach ($arguments as $placeholder => &$value) {
      if (is_string($value)) {
        $value = "'$value'";
      }
    }
    $string = strtr($string, $arguments);
  }
  return $string;
}

```

dpm() and dqp() are from the Devel module, they let you preview the SQL running from Views from within your module (where you're tweaking it).

Without having your server/DB I cannot just give you the SQL (nobody can do your homework for you). Writting the correct SQL is the hard part; altering the Views SQL is somewhat tricky but outlined here. goodluck.

**EDIT** you may also find this documentation helpful: https://drupal.org/node/1705998

---
Tags: 7, views
---


# Question
Title: Best practice for node expiration with email notification
I have a page where users can create meetings which have a specific start date and time, other users can join this meetings until up to an hour before it starts.

One hour before the meeting starts i would like to send an e-mail to the participants to tell them that the meeting will take place, or that it is canceled because not enough participants have been found. So i need to filter all the existing and not yet closed/started meetings and see if any of them are less than one hour away from starting.

**Question:**

Whats the best practice to do this kind of data evaluation in Drupal. Is there a recommended way of doing this?

**My idea:**

Just create an external PHP file including all the drupal shebang, call it every x minutes with a cron job and access the DB from inside this script.

# Answer
> 1 votes
Drupal has a custom module available called Rules with a submodule Rules Scheduler that will allow you to set up custom scenarios for when you want a certain action to take place.

In your specific scenario you would use Rules and Rules Scheduler to set up custom emails to be sent out at your specified time based off of your time field.

Node one has several tutorial videos available to watch with a specific video available about how to use content fields and rules scheduler to set up time specific actions.

---
Tags: 7, database
---


# Question
Title: Allow all users to view all groups (private or public) with Organic groups, but not private content
I am using Drupal 7.25 (I need to update to 7.26) and organic groups 7.x-2.4. I currently have public and private groups working. I have two users (admin and a normal user). I have a menu tab that opens the og list (/og-list) view which I want to list all groups (public or private)

Currently all public groups show up for the normal user. The private groups are still not shown in this list to the normal user. If I log in as admin they see all private and public groups.

How can I make private groups show up in this list to all users? When they click on the group they shouldn't be able to view the content, just the group name and a subscription link. If I type in the direct link to the group is gives me an an Access is denied page.

Thanks for the help!

# Answer
List Private Organic Groups Publicly without giving access to the node page? That post answered my question. Thanks Damien Tournoud for posting the following answer:

> You can tell Views to ignore the access control of some of the Views. On Views 3.x, this parameter can be found under "Query Settings" / "Disable SQL rewriting", and is described as:
>
> Disabling SQL rewriting will disable node\_access checks as well as other modules that implement hook\_db\_rewrite\_sql(). The full nodes will stay private, so you should make sure not to link to them in the View so that your users do not land on "Access Denied" (403) pages.
> 1 votes

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


# Question
Title: Permissions based on multiple OG groups?
Is it possible to have permissions, based on multiple organic groups?

I have 2 group content types: One 'Organisation' group type and one 'Department' group type. There are multiple organisations and each organisation and multiple departments. Each organisation has the same departments. So for example:

ORGANISATION GROUPS:

* Google
* Yahoo
* Microsoft
* Samsung

DEPARTMENT GROUPS:

* Customer Service
* Management
* Finance
* Sales

Each user will be a member of one organisation and one or more departments.

What I want is: If an admin adds content (like a news article), he can choose the organisations and/or departments. Users in both the chosen organisations and departments can see the content. If a user is in a chosen organisation, but not in a chosen department, he can not see the content.

If no organisation is checked, the users in all organisations can see the content (if they are in the chosen departments). If no department is checked, the users in all departments can see the content (if they are in the chosen organisations). If no organisation and no department is checked, all users can see the content.

I tried to use sub-groups, but then the admin has to choose all the (for example) 'Sales' departments of all the organisations instead of just clicking one 'Sales' department.

# Answer
> 0 votes
It's not possible out-of-the-box. Organic groups access control basically says if a user is in one group they can see the content in that group.

However you could write your own hook\_node\_access that evaluates the logic you described.

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


# Question
Title: How can I group view results based on the week of the year using a date field?
I have a list of events (custom content type *event*) shown in a view.

There are several events each week. Each event has a **date** field, *date*, that records the date that the event will be held.

I would like to group the events by the week of the year that they occur. For example:

* Next week
* Two weeks from now
* Three weeks from now
* Four weeks from now

Is there a fancy way to compute the week using the date field and views grouping?

# Answer
> 2 votes
You can do this without using a PHP field (or similar). Those modules are usually bad practice to put PHP into the database like that.

You can create a date format in Drupal for 'Week'. Then you add the date field to the View and use this week format. That will output the value of the date as a week #. Then you group on that value.

A views filter can also help restrict the view to now + 4 weeks. And some views theming can make each week header be whatever you need it to be.

---
Tags: views, datetime
---


# Question
Title: How to show form elements within PDF by print module?
I'm using the print module to convert a node to a PDF. I see that there is the print.tpl.php for theming, but where can I say that I want to show form elements (eg. input fields, radiobuttons, ..) within the PDF?

# Answer
Not sure if this is exactly what you mean but you can show / hide elements via the ui.

1. go to **admin/structure/types/manage/your-content-type/display**
2. Under Custom Display Settings enable Print
3. **admin/structure/types/manage/page/your-content-type/print**

This will show or hide form elements for the pdf version as well as the print version.
> 0 votes

---
Tags: forms
---


title: Mail System module replacement?

text:
# Question
Title: Mail System module replacement?
We recently updated Drupal Core to 7.26. Since that update Mailsystem doesn't work correctly. We've had to remove it from our site.

The error message we recieve is:

> PDOException: SQLSTATE\[HY000\]: General error: 1 Can't create/write to file '/tmp/#sql\_52d3\_0.MYI' (Errcode: 28): SELECT DISTINCT registry.name AS name, registry.filename AS filename FROM {registry} registry WHERE (type=:type AND ( filename like :filename OR name like :name )) ; Array ( \[:type\] =\> class \[:name\] =\> %MailSystem \[:filename\] =\> %.mail.% ) in mailsystem\_get\_classes() (line 282 of /sites/all/modules/contrib/mailsystem/mailsystem.module). The website encountered an unexpected error. Please try again later.

Any suggestions for a fix or replacement module?

Thanks in advance

# Answer
> 0 votes
Here are some suggestions which can help:

* Check permissions of temporary folder
* create .htaccess file in temporary, files folders with this content:

.htaccess:

```
Options None
Options +FollowSymLinks

SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

```

// this options recently added to Drupal system.

---
Tags: emails
---


# Question
Title: Events showing on a calendar is radically different formats
With event nodes imported using the Feeds Importer. How might I get the Jan 1 event to appear *only* on January 1st?

These events shown below on Jan 1 and 4 are all day events. Their individual date formats are listed below. The dates entered in both seem to be the same, but the difference in the rendering is baffling.

Additional information: Based on a helpful comment below. Here is what the Inspector shows in Firefox.

*Jan 1 event, should not span two days*

(full size image)

*Jan 4 event with proper rendering*

(full size image)

# Answer
> 1 votes
Well I half-way solved my the issue by changing a Multi-day event to a single column. I have some more reading and research to do on importing calendar events but for now, the rendering is correct.

This setting is found in the Views Format box by clicking `Settings` next to `Format: Calendar`.

---
Tags: views, feeds, datetime
---


# Question
Title: Which module allows for tracking recently viewed content per user?
I am searching for a module that will enable me to track recently viewed content per user. I found the Recently read module but it does not appear to enable me to configure it per content type. For example, I want to show all recently viewed content by this given user for content type a and content type b. Is anyone aware of a module that would allow this?

# Answer
> 0 votes
The Recently Read module does not allow you out of the box to be configure per content type, but it seems to me that the views you create to show the content can easily be filtered by content type. See comments #3 and #5 of this thread.

Also a quick scan of the modules source code tells me, that there is still support for relationships in views. So you should be able to follow the configuration guidelines in the linked comments to achieve what you want.

---
Tags: users
---


# Question
Title: In view, $content is null when show: fields
I'm trying to customize the row style template for one of my views. The settings are

* Format: **HTML List**
* Show: **Fields**

With these settings, `$content` is `null` in my `.tpl.php` file. I know about `$fields`, and I can see my values in there when I `var_dump`. However, the values are buried SO DEEP in there that I'm having trouble getting at them. I'm sure I must be doing something wrong.

How do I access my fields in a custom tpl for a view?

# Answer
> 1 votes
It is possible that you don't override the correct template. For the reference see here: Views template files.

There are several different approaches possible, depending of your requirements.

1. The usual way is to change the output of each field individually, using the field specific override. Access to the raw value and the already rendered content is straight forward using the provided variables. It's very difficult to break something here.
2. Another way is to use a row specific override. Following this approach it is your responsible to assure to output all fields in the result set for each row. In exchange this can be much more flexible regarding the created markup structure, because it's entirely up to you,

You could go even higher up the abstraction road, but the use cases for that are becoming incredibly scarce. So the odds are your simply in the wrong template.

Also, just in case you don't know that, there is an overview for the available and the used template files in the Views UI. In Drupal 7 and Views 3 it is in the outer right block the last link on the bottom:

---
Tags: views, theming
---