# Question
Title: How to list duplicate nodes based on title with views
I'm trying to **list** all duplicate nodes based on node title with **views**.

In views aggregation settings it's said that:

> If enabled, some fields may become unavailable. All fields that are selected for grouping will be collapsed to one record per distinct value. Other fields which are selected for aggregation will have the function run on them. **For example, you can group nodes on title and count the number of nids in order to get a list of duplicate titles.**

I enabled aggregation and added a node content title filter (aggregation: count) to count nodes and list if a title has more than one node (count: Is greater than 1). But it doesn't work for me, it lists nodes with unique titles and duplicate titles (I mean no affect).

How can I list all nodes with duplicate titles by using views?

# Answer
> 3 votes
The filter should be on content:nid. Set it to aggregate on COUNT, and 'Is greater than' value 1.

Then check all of your fields that you have added. None of the fields for nodes with the same title should output a different value. Title for instance, can be unique, depending on how you output it. If you for instance output it as a link (the default), then for each title that is the same, but that belongs to another node, the link is unique, therefore you view won't perform the way you want it to. So deselect 'Link this field to the original piece of content' and it should work.

---
Tags: 7, views, nodes
---


# Question
Title: Is a block changed programmaticaly with hook_block_view_alter cached?
I have a lateral section which will be different for every page in my site, but the content is practically unaltered for every single page.

I had the intention of using hook\_block\_view\_alter. I would create an empty block in the region, and would fill the content dinamically with PHP in a hook in a custom module.

Will the content be cached or should I better create different blocks for every single page and change the content only if the content changes?

# Answer
hook\_block\_view\_alter() isn't going to affect the cache settings for the block automatically, though you can find a way if you really want to as Molot points out below; typically you use hook\_block\_info\_alter() to change the cache settings for a block:

```
function mymodule_block_info_alter(&$blocks, $theme, $code_blocks) {
  $blocks['block']['my_block_id']['cache'] = DRUPAL_CACHE_PER_PAGE;
}

```

Here, DRUPAL\_CACHE\_PER\_PAGE will cache your block for each page, which could be quite a bit better than not caching at all and creating the content dynamically for each page. If you need dynamic content every time, choose DRUPAL\_NO\_CACHE. Clear the block cache to make Drupal aware of your new settings.

But! If you are prepared to have a custom module to run alter hooks, consider writing a block from scratch. If you are going to have a custom block, I feel that it helps if it is impossible to accidentally delete in the Drupal UI.

To implement a basic block you need hook\_block\_info and hook\_block\_view.

hook\_block\_info is where you tell Drupal that the block exists and how to cache it:

```
function mymodule_block_info() {
  $blocks['myblock'] = array(
    'info' => t('My Awesome Block'),
    'cache' => DRUPAL_CACHE_PER_PAGE,
  );
  return $blocks;
}

```

Next, hook\_block\_view does the work of generating the content. I find that assigning the content to a callback makes my code easier to read, but do what works for you. Using switch() makes it easy to add more blocks to your module later on.

```
function mymodule_block_view($delta='') {
  $block = array();

  switch ($delta) {

    case 'myblock':
      $block['subject'] = t('My awesome block');
      $block['content'] = mymodule_some_function_to_build_the_block_content();
      break;

  }

  return $block;
}

```
> 4 votes

---
Tags: caching
---


# Question
Title: How do you get the weather module to recognise SVG files?
How do you get the weather module to recognise SVG files?

I have my SVGs in: `/sites/default/files/icons/svg`

They are named correctly: 01d.svg, 01m.svg ...etc.

and that is where I am pointing to (`icons/svg`) from: `admin/config/user-interface/weather`.

PNGs work fine, but when I switch to SVGs the display falls back to the default icon set?

Thanks.

# Answer
I don't like to, but I hacked the module: weather\_theme.inc. I altered:

```
$image = $custom_path . $symbol . '.svg';

```

Here's the full function:

```
/**
 * Returns the <img> tag for the weather image to use for the current condition.
 *
 * @param $symbol
 *   The weather condition number from yr.no
 * @param $condition
 *   The translated condition text.
 *
 * @return $string
 *   Ready formatted HTML <img> tag
 */
function weather_format_image($symbol, $condition) {
  // Support a custom image directory. If the variable is not set or the specified
  // file is not available, fall back to the default images of the module.
  $custom_path = file_default_scheme() . '://' . variable_get('weather_image_directory', '') . '/';
  // Construct the filename
  $image = $custom_path . $symbol . '.png';
  if (!is_readable($image)) {
    $default_path = drupal_get_path('module', 'weather') . '/images/';
    $image = $default_path . $symbol . '.png';
  }
  $size = getimagesize($image);
  // Prepare the <img> tag
  return theme('image', array(
    'path' => $image,
    'width' => $size[0],
    'height' => $size[1],
    'alt' => $condition,
    'title' => $condition,
    'attributes' => array('class' => 'weather-image')
  ));
}

```
> 1 votes

---
Tags: theming
---


# Question
Title: Only display image field when administrator approves it
I'm building an advertising website using Drupal 7, in my case anyone can add an advertisement without any restriction, except that the images should be hidden first until the website admin approves it.

# Answer
> 0 votes
I already found a solution for my case.

I solved the problem in the following way:

1. Install Entity API, Entity Reference, Automatic Entity Label and Automatic Nodetitles modules.
2. Create new content type named 'image' and apply Automatic Entity Label to it.
3. Create new content type named 'classified' and create an Entity Reference field that can be used to point to an 'image' node.
4. Now if you create a 'classified' node and an 'image' node from 'classified' node itself, the information appears without an image because the image content will be unpublished by default (until the admin publishes it).

Finally, thanks a lot for your support and help especially J. Reynolds.

# Answer
> 0 votes
Have a look at File admin.

> File admin extends the File entity module to add administrative options to files, including published, promoted, and sticky status.

It has a dependency on File entity, which is a prerequisite when working with files as first class citizens.

Please also look at File admin's issue queue. A lot of extra functionality can be added via a few select patches.

---
Tags: media, workflows
---


# Question
Title: How to display view in all available languages?
I need to set up a view that lists content in all available languages despite user's current language. I tried creating content translation relationships to all languages and setting fields to use these relationships, but it doesn't work. It only shows fields with the user's current language. How do I get it to list all fields in all languages?

# Answer
> 0 votes
You could try to do this with the field language setting in view. I would try to set this to language neutral.

I have not tested this myself, just my 2 cents ;-)

Look to screenshots for clarification

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


# Question
Title: Show a required textfield when user select only ups shipping service on checkout form
I am using drupal commerce for my client ecommerce site. For shipping methods I am using commerce\_shipping, commerce\_ups, commerce\_usps.

Everything is working but my client wants when a user select any *ups shipping service* a textbox should be shown and should be required.

What I have done till now :

I have created a pane which contains a textbox using order setting. And that taexbox is showing on checkout form . But when I make this textbox as a required field than it is not possible to submit the form when user select usps or flat rate shipping services.

So how I can show a textfield on checkout form which should be required only when user select any ups shippping service.

Thanks!

# Answer
You could try to do this via #states property in form API.

More information about that can be found here: How to make a form required with states?

Personally i only used it to hide/display form elements, but required/non-required should be possible as well.
> 0 votes

---
Tags: commerce
---


# Question
Title: How to display drupal user page tabs on 3 different page
We want to display a 3 tab "Create new account(Lawyer Registration)" , "Log In" , "Forgot Password" link on 3 different pages. when we click on log in then they display all 3 tabs.

Actually we have 2 different type of registration process one for lawyer and another one is for normal user. when we click to login then they display above 3 tabs and this is confusing for user. so i want to hide this lawyer registration process form user page and call them to from different page.

So please help me how i can remove them from above tabs and call user/register page from different ways.

# Answer
> 1 votes
One quick solution to hide the tabs is to change the menu type form tabs to callback:

```
/**
 * Implements hook_menu_alter().
 */
function yourmodule_menu_alter(&$items) {
  $items['user/login']['type']    = MENU_CALLBACK;
  $items['user/register']['type'] = MENU_CALLBACK;
  $items['user/password']['type'] = MENU_CALLBACK;
}

```

You could render the user register form whatever you want with this:

```
$elements = drupal_get_form("user_register_form");
$form = drupal_render($elements);
echo $form;

```

# Answer
> 0 votes
This is perfectly possible with the use of Profile2 module (https://www.drupal.org/project/profile2) in combination with Profile2 regpath module (https://www.drupal.org/project/profile2\_regpath)

This way you can setup a specific registration path per profile.

---
Tags: users
---


# Question
Title: Combine fields that has same value in views
Current view

What I want to achieve

The data are from 2 different entityforms. And then I merged them in my view. As you can see, in date row, two data(05/29/2014) has the same value. I want to merge the same value then the field of the 2nd date will align to the first date.

# Answer
Have you tried using the 'group by' option in views?

Under display, you can select to group by date for example.
> 0 votes

---
Tags: views
---


# Question
Title: How do I add a suffix to the price field?
I'm using drupal commerce in my current project, I want to display the price like "$299 excluding tax/month", but the price field is not editable by default. there is a way to add this suffix to the price?

# Answer
> 0 votes
Do you need to include the value in the field? If not, you could just put it in place with a template file. You can create a template file that formats that specific field, for example; see Drupal 7 Template (Theme Hook) Suggestions.

Otherwise, you can use the Simple Field Formatter module.

> The Simple Field Formatter module allows site administrators to easily control the display of field values with following features.
>
> ### Features:
>
> * Prepend the field value with specified text/HTML
> * Append the field value with specified text/HTML
> * Reverse the Field Value
> * Trim the Field Value
> * Convert the field value to lowercase letters
> * Convert the field value to uppercase letters
> * Convert the first character of the field value to uppercase
> * Convert the first character of each word in the field value to uppercase (7.x-1.x-dev)
> * Replace some characters with some other characters in the field value (7.x-1.x-dev)
> * Link the field value to node(7.x-2.x-dev)

# Answer
> 0 votes
You can use the Money, Currency or Measured Value Field module.

The Money module will give you more advanced functionality including different type of currencies.

---
Tags: commerce
---


# Question
Title: Adding extra field on Main menu, similar to Amazon.com
I'm building a new website on Drupal 7 and my client wants a menu that in addition to the menu items he be able to add html content, very similar to Amazon.com menu. Should I create a content type for my menu instead?

# Answer
> 3 votes
Your best option is to use the TB mega menu module add your html content to a block and add the block to the menu

> TB Mega Menu is developed following Drupal standards and best practices. Along with those must-have functions of a mega menu: display not just menu items but image, slideshow, video, article and customize any of them upon your favour...

# Answer
> 0 votes
This module will help a lot for your requirements https://www.drupal.org/project/menu\_descriptions

---
Tags: 7, routes, navigation
---


# Question
Title: Do not map (update) some fields with migrate in update action
I have a custom migrate import that imports some fields like:

```
...
$this->addFieldMapping('title', 'title');
$this->addFieldMapping('body', 'description');
$this->addFieldMapping('created', 'created');
...

```

If I run an update of some items (the source data is a live site) I don't want to update the `title` or `body` fields because editors are changing this content in the drupal site.

I'm using this workarround but I'm not sure this is the best way to do this:

```
/**
 * Migrate prepare method.
 */
public function prepare($entity, $row) {
  if (isset($entity->is_new) && $entity->is_new === FALSE) {
    unset($entity->body);
    unset($entity->title);
  }
}

```

Thanks!

# Answer
> 4 votes
Good news! You are doing this exactly right. By "unsetting" the fields in the source data you are taking the proper approach. This practice is common and the relative snippet of documentation is buried a bit in the Migrate Handbook:

> To use default values for NULL or '' or array() values, be sure to remove the item with unset() in your prepareRow() \[or prepare()\] function.

From https://www.drupal.org/node/1133448

Good luck with the migration!

---
Tags: 7, migrations
---


# Question
Title: How to change the directory of file_create_url to default for a custom domain
Suppose, we have a file: /sites/default/files/picture.jpg

Drupal is installed into a subdirectory: /drupal. There are 2 domains, attached to the site:

1. exchange
2. exchange-test (uses different DB)

---

```
 | domain        | settings.php path     |
 |---------------+-----------------------+
 | exchange      | /sites/default/       |
 | exchange-test | /sites/exchange-test/ |

```

When we call

```
print file_create_url('public://picture.jpg');

```

we get:

```
| site          | result                                        |
|---------------+-----------------------------------------------|
| exchange      | /drupal/sites/default/files/picture.jpg       |
| exchange-test | /drupal/sites/exchange-test/files/picture.jpg |

```

But the file is stored in default directory even for `exchange-test` domain.

As far as I could find, the path is being generated, using function conf\_path. It scans the config directory to find a subdir with current domain name:

```
 $server = explode('.', implode('.', array_reverse(explode(':', rtrim($_SERVER['HTTP_HOST'], '.')))));
  for ($i = count($uri) - 1; $i > 0; $i--) {
    for ($j = count($server); $j > 0; $j--) {
      $dir = implode('.', array_slice($server, -$j)) .
             implode('.', array_slice($uri, 0, $i));
      if (isset($sites[$dir]) &&
          file_exists(DRUPAL_ROOT . '/' . $confdir . '/' . $sites[$dir])) {
            $dir = $sites[$dir];
      }
      if (file_exists(DRUPAL_ROOT . '/' . $confdir . '/' . $dir . '/settings.php') ||
         (!$require_settings && file_exists(DRUPAL_ROOT . '/' . $confdir . '/' . $dir))) {
            $conf = "$confdir/$dir";
            return $conf;
      }
    }
  }

```

If found, it uses this directory as files path.

So, one way is to temporarily change `$_SERVER['HTTP_HOST']`:

```
$_SERVER['HTTP_HOST'] = 'exchange';
print file_create_url('public://picture.jpg');
$_SERVER['HTTP_HOST'] = 'exchange-test';

```

Will give the correct result. But this trick seems clumsy to me. Is there any way to get the default directory without such hacks?

# Answer
> 1 votes
try setting the public file system path in your -test site to match that of the other in /admin/config/media/file-system

---
Tags: 7, files, uri
---


# Question
Title: How to restrict access to the site during development?
I am creating a new Drupal 7 based site.

The development will be on a server that is publicly accessible. I am working in a multi-site environment.

I would like to totally block access to the site to anyone & anything but authorized users. Including access to the site name, theme, etc...

I used Secure Site for similar tasks before. It did http-level authentication and returned 403 when authentication failed. It doesn't have a D7 version.

What would be the easiest way to do this?

# Answer
Make a module and paste following code in your module file:

```
<?php

/**
 * Implementation of hook_boot().
 *
 * Ask for user credentials and try to authenticate.
 */
function foo_boot() {
  require_once DRUPAL_ROOT . '/includes/password.inc';

  if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
    $query = "SELECT pass FROM {users} WHERE name = :name";
    $result = db_query($query, array(':name' => $_SERVER['PHP_AUTH_USER']));
    $account = new stdClass();
    foreach ($result as $row) {
      $account->pass = $row->pass;
    }
    if (isset($account->pass)) {
      if (user_check_password($_SERVER['PHP_AUTH_PW'], $account)) {
        return;
      }
    }
  }

  header('WWW-Authenticate: Basic realm="Development"');
  header('HTTP/1.0 401 Unauthorized');
  exit;
}

```

This uses HTTP Authentication and checks the Drupal Database for a valid username and password.

If you have any problems with PHP CLI, Drush or cron, you can add following code in the hook:

```
  // Allow cron through
  if (basename($_SERVER['PHP_SELF']) == 'cron.php') {
    return;
  }

  // Allow PHP CLI/Drush through
  if (isset($_SERVER['argc'])) {
    if (php_sapi_name() == 'cli' || (is_numeric($_SERVER['argc']) && $_SERVER['argc'] > 0)) {
      return;
    }
  }

```
> 15 votes

# Answer
If you're using Drupal 7 the Shield module is available for this purpose. It authenticates a single, shared user and password.

> PHP Authentication shield. It creates a simple shield for the site with Apache authentication. It hides the sites, if the user does not know a simple username/password. It handles Drupal as a "walled garden". This module helps you to protect your (dev) site with HTTP authentication.
> 5 votes

# Answer
Add `mod_auth` to apache setup. This varies depending on your host (linux, windows). This may involve downloading a module, it may involve just uncommenting a line in your httpd.conf

```
 LoadModule auth_basic_module modules/mod_auth_basic.so

```

Create an .htpasswd file, using the `htpasswd` command in the apache binaries folder

```
 htpasswd -c user pass

```

Add the following code to your `<DIRECTORY>` statement right after your clean URLs rewrite rule:

```
AuthType Basic
AuthName "My Auth"
AuthUserFile \path\to\.htpasswd
Require valid-user

```

Restart apache. Profit.
> 3 votes

# Answer
Use HTTP authentication. How this is done with Apache is documented at http://httpd.apache.org/docs/2.2/howto/auth.html. For a multisite installation, the \<Directory\> section of the \<VirtualHost\> would be an appropriate place to put the configuration directives.
> 0 votes

# Answer
The OP has commented that this is on shared hosting. Most shared hosting provides cPanel or some other control panel, which will do simple .htaccess password protection for directories.

I have protected the top-level directory of a site under development using this method. If you use cPanel to protect the directory, look for the "Password Protect Directories" menu item.

If you protect the top-level directory before you install Drupal, cPanel will create a .htaccess file in that directory. Append or prepend the contents of that file with the .htaccess file that Drupal provides. If you protect the directory after installing Drupal, I am fairly sure cPanel will just add the lines it needs to the existing Drupal .htaccess file and not disturb the rest of the file. Just make sure you preserve those lines if you replace the .htaccess file during a Drupal upgrade.
> 0 votes

---
Tags: 7, users
---


# Question
Title: Jquery Ajax to Drupal to External site, reading response
I have a drupal site.

There is a page (page 1) with a form that gathers user info and submits it via AJAX to a Drupal Module page.

The AJAX format is jquery

```
var responseTarget = '/site/module/page_name';
  jQuery.post(responseTarget, {
      key1: value1, key2: value2,.......
  }, function(responseText, statusText, xhr) {
    if (xhr.status === 200) {
      PROCESS SUCCESS
    }
    else PROCESS FAILURE

```

The module page has the URL format "site/module/page\_name" (page 2) and is constructed from the module file "page\_name.tpl.php".

This (page 2) processes the user information and sends it to an external server.

The server replies to my (page 2) which processes the response by saving a value to the user account.

The (page 2) then responds to the AJAX call on (page 1).

When my AJAX receives the response it is the response from Drupal (page 2), not from the external server.

* responseText = the whole Drupal page2, as it is part of a module it contains the header and footer and the processed php of the page as HTML, no objects or values.
* xhr.status = 200 // Drupal page2 success

What I would like to do is read the response from the server in my page 2 and pass this pack to the AJAX script, or process the value returned from the server in page 2 and pass a status/value/... back to the AJAX script based on this.

I have tried getting Drupal page 2 to echo a JSON object but this is done within the module and Drupal prints it out as part of the page HTML.

Summary

\[page 1 (ajax)\] --\> \[page 2 (Drupal module)\] --\> \[External Server\]

\[External Server (modifies an object)\] --\> \[page 2 (processes the object and incorporates it into a full Drupal page, and removes whatever header, status was sent from external server\] --\> \[page 1 (ajax) receives the status and data from page 2\]

# Answer
> 2 votes
Try this:

```
ctools_include('ajax');
ctools_add_js('ajax-responder');
$commands[] = ctools_ajax_command_redirect('node/1');
print ajax_render($commands);
exit;

```

Reference D7 AJAX Form Redirect.

---
Tags: ajax, http-request
---


# Question
Title: Solutions for frontpage that consist of only blocks
What methods are there to construct a frontpage that consist of only blocks. I know i can setup panels + pagemanager and add blocks in that manner, but it seems a bit overkill to install panels just for 1 page of the site. Another solution was to create an empty Views page, but that seems a bit hacky.

Having that the frontpage consist of only blocks, what other methods are there that doesnt seem hacky or bloated?

# Answer
Assuming I understand the question correctly, you could use a lightweight module such as Empty Page:

> The Empty Page module is a simple empty page solution. It provides an interface that assists in managing "empty" menu callbacks, mostly used for pages that only consist of blocks.

Then you can create and place blocks wherever you want, and restrict them to the front page if desired.

If you need to customize the general layout, you can use something like Themekey:

> ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules.

And use a sub-theme of your main theme for just the front page - then you can alter it to suit the layout of just containing blocks in whatever format you want and whatever regions you need.
> 0 votes

# Answer
The pages are already built from blocks, where the 'main content' block is the page content. These blocks are positioned in regions defined in the template.

I guess you want to reorganize the blocks? Have maybe multiple columns and so? Then you can either use panels or alter the theme with the regions you want. (This basically is what panels does, but at the position of the 'main content block'. Leaving the other blocks intact.)
> 0 votes

# Answer
It seems this was the minimal setup by using: https://www.drupal.org/project/empty\_front\_page
> 0 votes

---
Tags: 7, blocks
---


title: Content type with date groups

text:
# Question
Title: Content type with date groups
I currently have a content type called Training from which I have created a node for each training course I have. Each node has a multiple date field for when a course runs over more than one day (not necessarily days running after each other).

How would I create additional occurrences of a course dates without duplicating the node.

Eg

Fire course
2 day course
**Session 1:**
25/12/14 & 25/01/15
**Session 2:**
14/3/15 & 15/3/15

# Answer
You need to separate your sessions from your course type. The ideal solution would be to implement Field Collection.

> Provides a field-collection field, to which any number of fields can be attached.
>
> A field collection is internally represented as an entity, which is embedded in the host entity. Thus, if desired field collections may be viewed and edited separately too.

It is an actively maintained module with views integration. For a quick intro look at this tutorial.
> 1 votes

---
Tags: datetime
---


title: Get name of table for a field

text:
# Question
Title: Get name of table for a field
I've been using EntityFieldQuery to query my fields but I need the SQL 'like' operator. For this I'm querying the database manually. Question: How do I get the name of a field's table?

# Answer
> 3 votes
What you need to use is the `fieldCondition`, which works pretty much like `entityCondition` and `propertyCondition`, only you are adding a condition for the field and not the entity or one of it's properties.

This is how you should query fields and entities.

If you wanted to get info about the how the data of a field was stored, that information is available on the field itself. So you could do

```
$field = field_info_field('field_name');
$storage_details = $field['storage']['details'];

```

What info you get depends on how the field is stored, as Drupal support multiple storage backends for fields.

# Answer
> 2 votes
There is another way for obtaining storage details - field\_info\_fields() function. If you need to get more than one table (data and revisions in your situation) you may use it

```
$fields = field_info_fields();
$field_current_tbl_name = array_keys($fields[FIELD_NAME]['storage']['details]['sql']['FIELD_LOAD_CURRENT']);
$field_revision_tbl_name = array_keys($fields[FIELD_NAME]['storage']['details]['sql']['FIELD_LOAD_REVISION']);

```

Don't forget that field\_info\_fields() - memory eater, so it is better to use field\_info\_field() if you need only single field data.

---
Tags: 7, entities
---


# Question
Title: How to set a page level variable that views has access to
I'm trying to build a custom responsive theme using Zurb Foundation. I'm also using Views to render a grid of nodes, let's call them *Events*, that are each wrapped in Foundation classes to lay them out in a responsive grid.

**The Problem:**

The Foundation classes I need to use need to change based on the visible regions on the page.

For example, if the **sidebar\_first** region is showing, each item in the events list needs to have the classes: `columns large-4 medium-6 small-6`.

If the sidebar is not rendered, each item needs the classes: `columns large-3 medium-4 small-6`.

I cannot find a way to evaluate which regions will be rendered at the time the View is being built. I'm currently using `template_preprocess_views_view_unformatted()` to add the Foundation classes to the Views template, however this hook is being fired well before `template_preprocess_page()` for example, where I might be able to evaluate the visible regions and set a variable with information about the sidebar.

See the below pseudo code for the ideal structure when the sidebar is rendered:

```
<div class="row">
  <div class="region-content columns large-9">
    <div class="row">
      <div class="views-row columns large-4">...</div>
      <div class="views-row columns large-4">...</div>
      <div class="views-row columns large-4">...</div>
      ...
    </div>
  </div>
  <div class="region-sidebar-first columns large-3">...</div>
</div>

```

See the below pseudo code for the ideal structure when the sidebar is **not** rendered:

```
<div class="row">
  <div class="region-content columns large-12">
    <div class="row">
      <div class="views-row columns large-3">...</div>
      <div class="views-row columns large-3">...</div>
      <div class="views-row columns large-3">...</div>
      <div class="views-row columns large-3">...</div>
      ...
    </div>
  </div>
</div>

```

Ideally, without the sidebar rendered the events will be 4 across spanning all 12 columns. With the sidebar rendered they will be 3 across spanning only 9 columns, as the above classes in the pseudo code imply.

# Answer
> 1 votes
I must be addicted to Drupal because it is Christmas and I'm working on this, but here goes.

Delete the page display of your view so that only the master display is left. Then create a custom module with this code in it. (I created a module 'custom', my view is called 'zurb', and my path is 'zurb').

In custom module:

```
function custom_menu(){
  $items['zurb'] = array(
    'page callback' => 'custom_zurb_callback',
    'access callback' => true,
  );
  return $items;
}

function custom_zurb_callback(){
  $view = array(
    '#theme' => 'render_view',
    '#view' => 'zurb',
  );
  return $view;
}

function custom_theme(){
  return array(
    'render_view' => array(
      'variables' => array(
        'view' => NULL,
        'display' => 'default',
        'args' => array(),
        'regions' => array(),
      ),
    ),
  );
}

function theme_render_view($variables){
  $view = views_get_view($variables['view']);
  $view->set_display($variables['display']);
  $view->set_arguments($variables['args']);
  $view->pre_execute();
  $view->custom_regions = $variables['regions'];
  $view->execute();
  return $view->render();
}

function custom_preprocess_page(&$vars){
    if (current_path() == 'zurb' && count($vars['page']['sidebar_first'])) {
      $regions = array();
      $regions[] = 'sidebar-first';
      $vars['page']['content']['system_main']['#regions'] = $regions;
    }
}

```

Now in your views template file or views preprocess function you can access `$view->custom_regions`.

Perhaps there is a better way to pass the $regions to the view than adding it as a member on the $view object, but I don't see it being a problem. If it is a concern you can always just use drupal\_static

This code is also re-usable as it uses a theme function.

---
Tags: 7, views
---


# Question
Title: New path creation through hook menu problem
I have installed Drupal 7. I created new module (.module file and .info file), enabled the module, and gave the permission to menu item also. If I go to localhost/siva/shop/catalog/products, it redirects to the home page.

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

  $items['shop/catalog/products'] = array(
    'title' => 'Products',
    'description' => 'Configure the cart page display and settings.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('displayproducts_show_form'),
    'access arguments' => array('view displayproducts'),
    'file' => 'uc_cart.admin.inc',
  );
  return $items;
}

function displayproducts_permission() {
  $perms = array(
    'view displayproducts' => array(
      'title' => t('view displayproducts'),
    ),
  );

  return $perms;
}

function displayproducts_show_form(){
    echo "hello world";
}

```

Why does this happens?

# Answer
> 0 votes
You form function callback is incorrect you need to return a valid form, try this code:

```
function displayproducts_show_form($form, &$form_state){
  $form['item1'] = array(
   '#markup' => "hello world",
  );
  // @TODO: include more form items.
  return $form;
}

```

Documentation: FAPI

Make sure that this function is in your uc\_cart.admin.inc file as you indicate in the hook menu declaration: `'file' => 'uc_cart.admin.inc',` if it is in your main module file (.module) remove this line and clear the caches again.

---
Tags: 7, routes, hooks
---


title: relation users to orders

text:
# Question
Title: relation users to orders
I want to create a list of users with their orders. I know I can create it with the Views module, but when I select user as view type, there is no relation I can use to get their orders.

Some users may not have any order. I want the list to include also those users without any order.

# Answer
You can try to write a custom module that implements `hook_views_data_alter()` to programmatically define a relationship. See also the example code for `hook_views_data()`.
> 1 votes

---
Tags: views
---


# Question
Title: Can I delete old hook_update_N functions?
Suppose you have a custom module, and you have `hook_update_N()` implementations in your `.install` file.

If you have old update functions, and all updates have run in all sites that the module is installed, is it safe to delete those functions? Please note this is about custom modules that you have access to all sites and updates have been run.

Thank you in advance and I wish everyone a merry Christmas!

# Answer
> 5 votes
As long as you can be sure that they will never be needed it is safe to delete them.

Definitely make sure that you have made any changes required in the main install sections before removing the `hook_update_N` section.

If possible use some form of version control so you have clear record of the changes if you find you have missed upgrading that module on a site it will be super easy to restore that section for a one-off update.

# Answer
> 6 votes
Actually, there is a situation where you could need to keep the older update hooks: when you restored the database from an old backup and you need to update the database to the latest version of the installed modules.
If that is never your case, then—as long as you are sure all the sites have been updated to the same version of the module—you can remove the old update hooks. Keep in mind that, if you delete an update hook you needed for a site, the alternative is uninstalling the module, and then install the latest version, but this will cause data loss.

Updates hooks are **only** invoked when updating an installed module, and they are not invoked contemporarly to `hook_schema()` and `hook_install()`. When a module is installed, `hook_update_N()` is not invoked; `hook_schema()` and `hook_install()` are **only** invoked when a module is installed. That is the reason why old `hook_update_X()` could be removed, once a module is updated to version X or older.

Usually, the update hooks are removed when passing from a Drupal version of the module a more recent one (e.g. from the Drupal 6 module to the Drupal 7 module). Since the installation file is loaded just on updating and installing (and other limited situations), removing the update hooks doesn't give any significant gain.

# Answer
> 3 votes
Thanks for the other answers, but I'm answering the questions with some of of my findings.

When you define the database schema in a `hook_schema`, that should be **always** the latest version of the database. For other hooks, such as `hook_install` and `hook_enable`, it's same. All 3 hooks should use the latest functionality as you are installing the module afresh.

Schema version is stored in the `system` table, along with the module name. To answer my own question, yes I can remove old `hook_update_N()` functions if I'm sure all sites already have the update.

You can skip update numbers, and Drupal still can figure out the upgrade steps. If your scheme version is `7004`, and the module's `.install` file contains only `hook_update_7009`, only the `7009` will be called. See `update_get_update_function_list`. Also, you can implement `hook_update_last_removed` to inform Drupal about updates that are no longer available, and it will look for greater update `N`s.

---
Tags: nodes, updating
---


# Question
Title: With the Simplenews module, how can I use a custom mytheme/node--type.tpl.php with emails?
With the Simplenews module, how can I use a custom mytheme/node--type.tpl.php with emails?

# Answer
> 1 votes
You cannot, since the Simplenews module is using the simplenews-newsletter-body.tpl.php template file (this file, in case you are using Drupal 6). The Drupal 7 template file is described as follows:

> Copy this file in your theme directory to create a custom themed body. Rename it to override it. Available templates: simplenews-newsletter-body--\[tid\].tpl.php simplenews-newsletter-body--\[view mode\].tpl.php simplenews-newsletter-body--\[tid\]--\[view mode\].tpl.php See README.txt for more details.

Before Drupal 8, Drupal doesn't have the concept of including a template file from another one, so you can just copy the relevant parts of the template file inside another one, and adapt it basing on the variables the new template file gets.

---
Tags: theming, emails
---


# Question
Title: What function or $user variable do I edit to manually increase a user's session timeout?
I'm using the simpleSAMLphp module which redirects the user offsite to login and then hits them back to drupal in a logged in state, but for some reason the sessions aren't getting applied. When the user closes the browser it causes the user to be logged out.

But when I login via the drupal login page, the user session persists even if the browser is closed.

* What function should I look for in the simpleSAMLphp module where it logs the user in?
* What might I need to know or edit to make a assign a session time to a user?
* Is the session information stored in the $user variable and can I manipulate it from there? or is it a database edit?

# Answer
There are several modules that can do this for you.

https://www.drupal.org/project/session\_cookie\_lifetime https://www.drupal.org/project/remember\_me https://www.drupal.org/project/persistent\_login

I've had some problems with remember me and am still testing the others, but they give you more control over the session lenght.

By default drupals session expire after about 3 weeks, according to

```
ini_set('session.cookie_lifetime',  2000000);

```

You should be able to override this variable at database level as well, if you want to.
> 0 votes

---
Tags: 7, users, sessions
---


# Question
Title: View add a new field it can't find the fields "All disappeared "
Something strange happened to my website and suddenly all the fields disappeared from view.

I tried to create new view with content type building. the building content type has the following fields Title, photos,address,building ready,price,description and logo.

at the time of creating the view I can find all the above fields and can add them without any problem but after few minutes the fields disappears from view and going back to add field only few common fields are available

Going back to view i can see a message "This view has been automatically updated to fix missing relationships. While this View should continue to work, you should verify that the automatic updates are correct and save this view."

During creating the view all the field are available

creating new view configuration screen

I tried to update Drupal noting changed

I tired to update Views noting changed

I tired Registry Rebuild noting changed

# Answer
> 0 votes
After spending two nights I finally manage to make it work for me by Always show the master display from /admin/structure/views/settings and enabling.

However this is a major bug in view and to be honest pain in the bottom !

Hope next release of view will consider looking into this bug.

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


# Question
Title: Is it possible to edit Views code instead of the ui?
I'm aware that I can export and import a Views code. I'm wondering if there is a way to edit and add relationships or contextual filters of a current view within the code instead of the UI.

The reason is sometimes its just easier to add the code rather than drilling down to the relationship within the UI.

If not, I guess the workaround would be to export, then change, then import and overwrite. Not sure how this will effect the site if the views were created from a module installation.

# Answer
An easy way to do this would be if you had the features module that will contain the code of the view. Otherwise this information is stored in the database. Simply enable the module, create a new feature and add your view to it. Then it will be stored in code for you to alter.
> 3 votes

# Answer
Thanks for the suggestion guys.

I think the easiest way to avoid heavy database manipulation or adding different modules is to just export the view then change/add code and import and replace the view with newest changed version.
> 0 votes

---
Tags: views
---


# Question
Title: How can I make a mobile app that is basically a mobile browser to access my live Drupal site?
There is a question about exporting Drupal pages for use in a mobile app, but I would like to know if there is an easy way to make a mobile app (iOS, Android, etc.) that simply loads the existing site in a browser for online-only access.

I looked into Phonegap, but (as far as I can tell) you have to export the pages as HTML for that. However, the primary purpose of my site is to send messages back and forth using the Private Message module, so making the site accessible offline makes no sense.

I already have a responsive theme, so the site also looks decent in mobile browsers. I just want a mobile app because I want the site to appear in App Store and Google Play searches.

Is there a straightforward way to address this use case?

# Answer
> 3 votes
There is no module(convenient) to build all apps in Drupal, You have to build your own or if you have a mobile site then you can do it without Drupal help, see my article for android app. There are so many builders like iBuildApp, Appypie, Como, and so many.

---
Tags: theming
---


# Question
Title: How to change the date format for date entity field
I created an entity with date field. Currently the date is being output in the format "mm/dd/yyyy":

How can I use the format "dd.mm.yyyy"? I couldn't find any settings, related to it, in the field configuration form.

# Answer
The format can be changed in the settings of the field. You need to:

1. Click "More settings and values"
2. Select "Custom format" in Date entry options
3. Insert the format: "d.m.Y"
> 0 votes

# Answer
You can usually only change the output of a date field, as it is easier to convert an existing date to something else. The input is often standardised to make sure the system understands the input.

In order to change the output, create a new date format admin/config/regional/date-time/formats and enable it on admin/config/regional/date-time. Then you can use it as a display for the field on the display tab.
> 0 votes

---
Tags: 7, entities, datetime
---


# Question
Title: Automatically choose specific option from select field attribute based on inbound link / previous page?
I have three pages that each describe a product that we sell. Each of those pages has a button/link that says "buy now". Those links all take you to a single Ubercart product page with a select list attribute where they can select the name of any of the three products that I mentioned previously and add that product to their cart.

I'd like to have the name of the product from which they came automatically selected in that attribute field. Is there a way to do this via some kind of URL string, or another method?

Thanks!

# Answer
> 0 votes
Use hook\_form\_alter or hook\_form\_FORM\_ID\_alter, check your stuff (get parameter maybe), then apply the selected item though the form api

---
Tags: 7, ubercart
---


# Question
Title: How do I properly combine UNION with LIMIT?
I'm trying to get content from database divided by category. I want strictly max 4 entries of type "people" and 4 other entries of type "organization".

I tried to do it like that:

```
$query = db_select('node', 'n')
->fields('n', array('title','type'))
->fields('i', array('field_image_fid'))
->fields('f', array('uri'))
->condition('n.title', '%'. db_like($keys) . '%', 'LIKE')
->condition('type', array('people'))
->range(0,4);
$query->leftJoin('field_data_field_image', 'i', 'i.entity_id = n.nid');
$query->leftJoin('file_managed', 'f', 'f.fid = i.field_image_fid');

$query2 = db_select('node', 'n')
->fields('n', array('title','type'))
->fields('i', array('field_image_fid'))
->fields('f', array('uri'))
->condition('n.title', '%'. db_like($keys) . '%', 'LIKE')
->condition('type', array('organization'))
->range(0,4);
$query2->leftJoin('field_data_field_image', 'i', 'i.entity_id = n.nid');
$query2->leftJoin('file_managed', 'f', 'f.fid = i.field_image_fid');

$query->union($query2, 'UNION');
$result = $query
->execute();

```

The problem is that this query is returning only the first 4 occurrences of people or organization combined. So if there are 4 people returned by the query, I will not be able to see any organization.

I also tried something like this:

```
    $query = db_query('

        SELECT p.title,p.type
            FROM node as p
            WHERE p.type = :type
            LIMIT 4'
        , array(':type' => 'people',':type1' => 'organization'))->fetchAll();

$query2 = db_query('

        SELECT o.title,o.type
            FROM node as o
            WHERE o.type = :type1
            LIMIT 4'
        , array(':type' => 'people',':type1' => 'organization'))->fetchAll();

$query->union($query2, 'UNION');

```

or like this:

```
$result = db_query('

    SELECT title,type
        FROM {node}
        WHERE type = :type
        LIMIT 4
    UNION ALL
    SELECT title,type
        FROM {node}
        WHERE type = :type1
        LIMIT 4'
    , array(':type' => 'people',':type1' => 'organization'))->fetchAll();

```

But these two approaches are only returning the 4 people and no organizations, I mean never..

Thank you if you can help!

--------------------EDIT--------------------

Thank you for your comment Clive. I hadn't tried yet to do it directly in plain SQL.

The query is something like that

```
(SELECT title,type FROM node WHERE type = 'organization'  LIMIT 4)
UNION
(SELECT  title,type FROM node WHERE type = 'people'  LIMIT 4)

```

I didn't know but the parentheses are necessary to act as I need. Like that I get 4 of each, then 8 maximum in total.

So the same in drupal using db\_query is something like:

```
$result = db_query('

(SELECT title,type
    FROM {node}
    WHERE type = :type
    LIMIT 4 )
UNION ALL
(SELECT title,type
    FROM {node}
    WHERE type = :type1
    LIMIT 4)'
, array(':type' => 'people',':type1' => 'organization'))->fetchAll();

```

I don't know if it's possible to do the same with db\_select

--------------EDIT2---------------------------

Regarding to Molot comments, I changed my query to:

```
    $subquery_1 = db_select('node', 'n')
    ->fields('n', array('title','type'))
    ->fields('i', array('field_image_fid'))
    ->fields('f', array('uri'))
    ->condition('n.title', '%'. db_like($keys) . '%', 'LIKE')
    ->condition('type', array('people'))
    ->range(0,3);
    $subquery_1->leftJoin('field_data_field_image', 'i', 'i.entity_id = n.nid');
    $subquery_1->leftJoin('file_managed', 'f', 'f.fid = i.field_image_fid');

    $subquery_2 = db_select('node', 'n')
    ->fields('n', array('title','type'))
    ->fields('i', array('field_image_fid'))
    ->fields('f', array('uri'))
    ->condition('n.title', '%'. db_like($keys) . '%', 'LIKE')
    ->condition('type', array('organization'))
    ->range(0,5);
    $subquery_2->leftJoin('field_data_field_image', 'i', 'i.entity_id = n.nid');
    $subquery_2->leftJoin('file_managed', 'f', 'f.fid = i.field_image_fid');

    $query = $subquery_1->union($subquery_2);
    $f->fb((string)$query);
    $result = $query
  ->execute();

```

Now the query return People and Organizations together and limited to 5. Here is the print of the query:

```
SELECT n.title AS title, n.type AS type, i.field_image_fid AS field_image_fid, f.uri AS uri FROM {node} n LEFT OUTER JOIN {field_data_field_image} i ON i.entity_id = n.nid LEFT OUTER JOIN {file_managed} f ON f.fid = i.field_image_fid WHERE (n.title LIKE :db_condition_placeholder_0 ESCAPE '\\') AND (type IN (:db_condition_placeholder_1)) LIMIT 3 OFFSET 0 UNION SELECT n.title AS title, n.type AS type, i.field_image_fid AS field_image_fid, f.uri AS uri FROM {node} n LEFT OUTER JOIN {field_data_field_image} i ON i.entity_id = n.nid LEFT OUTER JOIN {file_managed} f ON f.fid = i.field_image_fid WHERE (n.title LIKE :db_condition_placeholder_2 ESCAPE '\\') AND (type IN (:db_condition_placeholder_3)) LIMIT 5 OFFSET 0

```

# Answer
Create both subqueries separately, with their limits. Then, use:

```
$query = $subquery_1->union($subquery_2);

```

That should do it.
> 2 votes

# Answer
looks like there is small bug in Drupal. but there is workaround:

```
$subquery_1 = db_select('node', 'n')
->range(0,4);

$subquery_2 = db_select('node', 'n')
->range(0,8);

$query = $subquery_1->union($subquery_2);

```

-\>range(0,4); is for the first query and -\>range(0, 8) is for both queries.

Problem is that $subquery\_1-\>union doesn't add () around 2nd query.

issue with this approach is that if 1st query returns less than 4 rows then 2nd will return more to make 8
> 1 votes

---
Tags: database
---


# Question
Title: How can I implement this floating sidebar block?
I'm going to implement a floating sidebar block that can contain user's selections. It is a kind of cart. Please check the image below.

If the use press 'Add to my favorite', then it should be contained in the sidebar. The floating sidebar block should slide up and down with buttons. Each item of it should be removed if the user press some kind of cross mark at the edge of item. After selection, the user can check all the items which have selected using 'View my favorites' button.

What is the right solution to do this? I was thinking that I needed to use 'Views module'. But I can't imagine how to make this sidebar slided.

# Answer
You can achieve it with HotBlocks module, Check out the screencast

* Add, remove, and reorder nodes or blocks to a page without leaving or reloading the page or using editors
* Content added to hotblocks can be constrained to individual pages or be made global to display on all pages that contain the hotblock
* Can display multiple instances of the same block or node in multiple regions
* Can give end users the ability to add and remove blocks to pages without exposing the administer blocks permission
* Provides a means to filter which of those blocks are available to the user for adding so every block in the system is not exposed
* See an overview and administer all of your assigned hotblock content grouped by region, url, or taxonomy on a single page
* Allow users to add and remove content to a page without giving them permission to edit that content
* Advanced permissioning possible - allows you to control which roles can assign/remove/reorder each type of content to every hotblock individually if necessary
* You can use your own custom icon set for the UI controls to customize look and feel
* If you don't like the term "hotblock" you can customize the terminology exposed to the user to suit your purposes

and for floating use Floating block module.
> 1 votes

# Answer
It seems you can achieve that by using the combination of following modules

Floating block

> The Floating block module allows you to keep html blocks, selected using jquery selectors in a fixed position on the page as you scroll. It works in a similar way the table header fixer in Drupal Core. This means that when the user scrolls their browser selected parts of the page can stay in the users view.

Close Block

> Close Block - is a module which allows to add a "close" button to any block.
> 0 votes

---
Tags: 7, blocks
---


title: Theme Hook Suggestion for Drupal 5

text:
# Question
Title: Theme Hook Suggestion for Drupal 5
I wonder if any still remember how to override a particular node in Drupal 5 ? I have tried out several ways but didn't work. Couldn't find such info any more on google.

node-13.tpl.php

node--13.tpl.php

# Answer
> 3 votes
In Drupal 5 you need to add the suggestion yourself by placing this function in your theme's template.php:

```
function _phptemplate_variables($hook, $vars = array()) {
  switch ($hook) {
    case 'node':
      $vars['template_files'] = array('node-'. $vars['nid']);
      break;
  }
  return $vars;
}

```

Once that's done you'll be able to use node-13.tpl.php (note the single dash).

Source: Separate node template for a specific node.

---
Tags: theming, 5
---


# Question
Title: How to create a view of nodes *without* comments from currently logged in user
I'm trying to create a view that lists nodes that don't have any comments from the currently logged in user. The nodes may have comments from other users, but if there is no comment from the current user then it should be listed.

I can show nodes *with* comments from the currently logged in user but not nodes *without* comments.

Almost like a "to-do" list of nodes that need to be commented on by the current user.

I'm a fairly advance views user (I've tried all I know by way of contextual filters, relationships, different content approaches like listing comments or users and connecting them through relationships... ) but all to no avail.

Anyone else come across this or have ideas where I can make more progress?

# Answer
**REVISED ANSWER**

This can be accomplished in two step process.

1. Create a very plain view to only show node titles. Do not filter it except by type if you wish, and do not place any contextual filters on it. For this answer I created a view called 'not\_commented' with a page display of 'page\_1'.
2. Create a custom module. We will use it to alter the views query. For this answer I created a module called 'custom'.

Add this code to custom.module:

```
function custom_views_api(){
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'custom') . '/includes/views',
  );
}

```

Now create a folder 'includes' in the module folder, and then a folder 'views' inside the includes folder so that the folder structure is : `sites/all/modules/custom/includes/views`

Create a file `custom.view.inc` within folder `views`. Place this code in the file:

```
<?php

function custom_views_query_alter(&$view, &$query){
  if ($view->name == "not_commented" && $view->current_display == "page_1"){
    // get all nodes commented on by this author
    $sql = "SELECT n.nid, COUNT(n.nid) " .
      "FROM {node} n LEFT JOIN {comment} c ON n.nid = c.nid " .
      "WHERE (c.uid = :uid AND n.status = '1') GROUP BY n.nid";
    global $user;
    $query_2_result = db_query($sql, array(':uid' => $user->uid))->fetchAllKeyed(0,0);

    $query->where[1]['conditions'][] = array(
      'field' => 'node.nid',
      'value' => $query_2_result,
      'operator' => 'not in',
    );
  }
}

```

Clear you cache.

Please replace module and views/display names etc. as applicable. If there are any problems please inspect the $query object to see if you have the right where array key etc.
> 0 votes

---
Tags: views, comments
---


# Question
Title: drupal_redirect_form not working with entity
I have created custom submit form handler for entity using below

```
$form['#submit'][]='app_contact_form_submit_message_alter';

```

but when i used

```
drupal_get_messages($type = NULL);
drupal_set_message('Thanks for your feedback we will contact soon.');
drupal_redirect_form($form_state);

```

It redirect correctly but entity is not created.

and even if i use `drupal_goto()` same thing happening.

# Answer
> 2 votes
If you want to redirect a form submit you should use the redirect parameter:

```
function app_contact_form_submit_message_alter(&$form, &$form_state) {
  drupal_get_messages($type = NULL);
  drupal_set_message('Thanks for your feedback we will contact soon.');
  $form_state['redirect'] = 'node/23'; // The path you want to go
}

```

This will call drupal\_redirect\_form($form\_state) byt its self, if you call it directly you are skipping the save step.

More info: https://api.drupal.org/comment/18139#comment-18139

---
Tags: redirection
---


# Question
Title: Rewriting a field in organic group member view
I am not sure if this is possible..

My organic group 'member view' filters all the members of a particular group. I have created the view so that the first member gets listed in a sidebar to become a link 'members' pointing to the complete member list for the current group.

The same view is used for a different grouptype. So the first member gets listed as a link as well. However with this grouptype i want my 'first member link' to be 'rewritten' as 'friends' instead of 'members'

Can this be done with one view?

I have tried using two fields to display rewriting one as 'members' and the other as 'friends'. Without succes i tried finding a proper relationship for them....

Help appreciated.

# Answer
did you try https://www.drupal.org/project/views\_conditional?

it allows to conditionally format/rewrite the output of certain views fields depending on the value of other fields that you have added in your view.
> 0 votes

---
Tags: organic-groups, views
---


# Question
Title: Custom contextual filter on views using Group module in Drupal
I need to add a custom contextual filter in my view for the logged in user who is also a member of a Group specified in field\_groups of my node. field\_group is an entity reference field referencing group entity provided by the https://www.drupal.org/project/group module.

What is the simplest way of doing it? I am open to suggestions.

# Answer
> 0 votes
I did not found anything about view filters for the `group` module. You can only list group entities, not nodes from a group.

Looks like there some support for Panels but I don't know the module that much.

So I took the time to write some code, I just finished testing it.

Just change `yourmodule` and `your_view_id` with the correct data and your view should only display nodes attached to groups from the current user:

```
/**
 * Implements hook_views_query_alter().
 */
function yourmodule_views_query_alter(&$view, &$query) {
  if ($view->name == 'your_view_id') {
    global $user;

    // Get current user groups.
    $groups = group_membership_load_by_user($user->uid);
    $groups = array_keys($groups);

    // Add join to filter on group ID.
    $join = new views_join;
    $join->construct(
      'group_entity',
      'node',
      'nid',
      'entity_id',
      array(array(
        'table' => 'group_entity',
        'field' => 'gid',
        'value' => $groups,
      )),
      'inner'
    );

    $query->add_relationship('group_entity', $join, 'node');
  }
}

```

---
Tags: views
---


title: Obtain an image url

text:
# Question
Title: Obtain an image url
I've a module that in the .install creates a table. In that table I have to save the information of one image, that's imagen\_leyenda.

I obtain that image from a form, that I have created in my custom module. To save that image, I have the next code:

```
function guardar_leyenda(&$form_state,$values){
        $icono = $form_state['step_information'][1]['stored_values']['icono'];
        $query = db_insert('leyenda')->fields(array('imagen_leyenda','texto_grande','fecha_inicio','fecha_fin'));
        $query->values(array($icono,$texto2,date('Y-m-d H:i:s'),NULL));
        $query->execute();

```

Now, what I need is to obtain the url of that image, but as you can see in the table, the id of the image is store, and what I need is the name of the image.

Is there any way to do that? Or maybe, have I to change something of the previous code?

Thank you very much!

EDIT 1:

This piece of code is the form icono

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

    $form['icono'] = array(
        '#title' => t('Icono'),
        '#type' => 'managed_file',
        '#upload_validators' => array('file_validate_extensions' => array('jpeg jpg png gif')),
        '#upload_location' => 'public://',
        '#progress_indicator' => 'throbber',
        '#status' => FILE_STATUS_PERMANENT,
        '#progress_message' => 'One moment while we save your file...',
        );

```

So, after when the user upload an image, drupal generates the id stored in imagen\_leyenda.

# Answer
Since you store the file ID, you can fetch the value from the database and obtain the image URL like this:

```
$file = file_load($file_id);
$image_url = file_create_url($file->uri);

```

Also, you can get the uploaded image with custom dimensions with `image_style_url($style, $image_url)`. You can configure styles here `admin/config/media/image-styles`.
> 2 votes

---
Tags: forms, media, database, uri
---


# Question
Title: How do you export forum topics from one drupal installation to another?
I have tried to export a list of forum topics and/or containers from my development environment to production using features, strongarm, migrate, node\_export and bulk\_export. So far none have worked. Am I doing something wrong or is this not possible via contrib modules?

# Answer
> 0 votes
If your environments can communicate via rsync then use `drush sql-sync`

Check the syntax www.drushcommands.com/drush-7x/sql/sql-sync to see how to pass a list of tables via the tables-list parameter.

else just use mysqldump.

---
Tags: features, nodes, importing-exporting
---


# Question
Title: How to offset an EntityFieldQuery when using pager?
Is there some way to easily offset an EntityFieldQuery when using `pager()`, i.e. skip the first 3 nodes? `range(3, NULL)` doesn't work as the second value must be set, and `range()` also doesn't work when also using `pager()` which is a requirement.

Is there a substitute for something similar to this:

```
$query
  ->range(3, NULL) // <- Wishful thinking..
  ->pager(10)
;

```

Thanks,

# Answer
> 2 votes
First question, you've asked if you can offset the results, without having to set the limit for the total results. Logically it would make sense to be able to set `$limit = FALSE`, to return all results. But I believe `range($offset, $limit)` requires you to enter both the offset and limit. A workaround is to enter `range(3,9999999999);`.

Second question, you've mentioned that the `-range()` is not working when `-pager()` is set. It's a known limitation. I would assume you can run a separate query to create a pager, but that would require additional SQL requests.

---
Tags: paging, database
---


title: Passing arguments to a block

text:
# Question
Title: Passing arguments to a block
I am working on trying to understand the secrets of custom-developed blocks. Namely, I have a use case where a block need to pull content via EntityFieldQuery (this could be done with Views, but I like a challenge) and the contents loaded need to adjust based on a URL argument.

Right now my running assumption is that since the page that will deliver these results is run through Context, my best bet for getting values from the URL are through arg() when the block is generated inside its referencing callback from `hook_block_view()`. I just want to be sure this is the best approach to actually load values that must be passed in through this approach, and i'm not missing a more reasonable design pattern.

Code example is below.

```
/**
 * Implements hook_menu
 */
function widgets_and_springs_menu() {
  $items['springs/%'] = array(
    'title' => t('All Springs for Category'),
    'page callback' => 'widgets_and_stone_blank_page', //Returns theme of '', enough for Context to catch
    'type' => MENU_LOCAL_TASK,
    'page arguments' => array(1),
  );

  return $items;
}

/**
 * Implements hook_block_info()
 */
function widgets_and_springs_block_info() {
  $block['springs_listing'] = array(
    'info' => t('All Springs Per Category'),
    'cache' => DRUPAL_CACHE_PER_ROLE,
  );

  return $block;
}

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

  switch($block) {
    case "springs_listing":
      $block['subject'] = "";
      $block['content'] = widgets_and_springs_get_results_by_uri_arg();
  }
}

/**
 * Returns arguments by URL. First item MUST contain a TID argument.
 */
widgets_and_springs_get_results_by_uri_arg() {
  $searchTid = arg(1);
  //Other stuff & Return of results within theme()...
}

```

# Answer
> 0 votes
It's not uncommon to customize block contents based on URL arguments. I don't see any reason to not do that.

However, since your block contents can change based on the URL, you need to use either no cache at all or `DRUPAL_CACHE_PER_PAGE`.

If your block contains any Ajax elements, note that `arg()` will return the ajax path.

---
Tags: 7, blocks
---


# Question
Title: Feeds for the module information of drupal.org
http://simplytest.me/ has a nifty autocomplete option for the module suggestions. Screenshot attached.

I did a little digging and figured it out that ajax call being made is to the following url.

> http://simplytest.me/simplytest/projects/autocomplete?string=views

I could be use the same end point but I need to get the permission and also the data available is not sufficient for my use case. I wanted to know if Drupal.org provides any authentic feeds of modules so that I will be able to list other details, say the download url for the tarball file.

# Answer
The official Drupal.org feeds available can be found at https://www.drupal.org/api/rss. There is a feed for projects, but to get the information about releases you'll need to parse the JSON of an API request like https://www.drupal.org/api-d7/node.json?field\_project\_machine\_name=media

You can read more about the APIs available and how to use them at https://www.drupal.org/api

UPDATE: If the goal is to a list of all projects and pull their releases, this cannot be done with just an official "feed". It requires scraping the list of projects from Drupal.org and writing code to get the release into, but the code to do that already exists. Lin Clark's ScraperWiki code still works (http://lin-clark.com/blog/2011/07/22/writing-scripts-clone-contrib-projects-gitdrupalorg/). Export the scrapper output as SQL, import that into a custom table, write some code to loop those the projects calling Drupal.org's API to get the release information you are looking for, and save that response. Not as easy as just pulling the information from a feed provided by Drupal.org, but it can be done.
> 2 votes

# Answer
The URL used when creating a new issue https://www.drupal.org/node/add/project-issue requires a project name in it's first step.

This is https://www.drupal.org/project/autocomplete/issue/project so issuing https://www.drupal.org/project/autocomplete/issue/project/gra gives a list of the first 10 items in json format.
> 0 votes

# Answer
There's over 9,000 d7 modules up on drupal.org, and I'm not sure if they put out an rss feed that provides every single module there is. I know drush does a fairly good job of keeping track of modules, so you might want to have a look at that.

There's also an internal function called module\_list, not sure how much use that would be to you.
> -1 votes

# Answer
Well, good question.

I wonder why there is no elegant and easy way to get machine-readable list of all Drupal modules and their data.

What i have found so far for humans are:

1. Modules search on Drupal.org
2. Modules search on Drupalmodules.com
3. Modules index on Drupal.org
4. Index of Drupal.org git repositories

But non of them provides rss or json out of the box.

If you need just a list of all Drupal modules - i would suggest you to parse Modules index on Drupal.org \- there are titles and links of all the modules on one page - quite handy.

But if you need more detailed list which you want continuously keep up-to-date - the only solution so far is to parse on your own this page: Modules search on Drupal.org.

For example do it with import.io service and then integrate into your site with Feeds module - here is a good tutorial: "Scraping websites into Drupal using Feeds and Import.io"
> -1 votes

---
Tags: 7
---


# Question
Title: Creating search pages for specific content types
I am currently in the process of implementing different search pages, with distinct layouts/templates and behaviors for specific content types (a search for "blog" nodes, one for "video" nodes, etc), and I am confused as to what the best approach is for this. I've read that the Facet API module may help implement this behavior. I'm already using Apache Solr for the searching component, is this the best approach and what's the path of least resistance if using Facet API?

# Answer
> 1 votes
The best method for me is Search API:

> This module provides a framework for easily creating searches on any entity known to Drupal, using any kind of search engine.

Uses multiple backends (solr, database, elastic search), is fully integrated with views, etc.

---
Tags: 7, search
---


title: Assign location from Profile2 to a node

text:
# Question
Title: Assign location from Profile2 to a node
I would like to allow user when creating new content (an event) to assign (from drop down) one of the locations defined in his profile (Profile2)... Is there a module which could help? If not any hint how to solve it in custom module?
Im thinking entity reference field could do if it was possible to create list of location for each user...
Maybe it is simple but beyond my drupal skills... ;)
Locations are nodes referenced with entity reference but not necessarily created by the same user

# Answer
> 1 votes
Install the references module, once you done that, you can enable the `node_reference` submodule and attach a "Node Reference" field to your "event" content type. Choose the "select list" widget and the user will be able to link any location to the event.

If you want to let the user choose only from locations he created, here's a way:

On the field configuration page, you can see a fieldset called "Views - Nodes that can be referenced". It says that options from the dropdown can be filtered based on a view using the "References" display type.

Just create a view listing location nodes and select the correct "display type" as shown below:

And display nodes from the current logged-in user by adding a contextual filter "Content: Author uid"

Save all that and refresh the field configuration page. Select the view from the dropdown list that just appeared and you should be good to go ;).

---
Tags: entities
---


# Question
Title: jQuery events are lost after form reload
First I thought that this would not be a Drupal specific problem, but jQuery specific solutions didn't solved it. I hope you have some advices.

I have a form with lots of fieldsets. To find the right fieldset I've implemented a textfield as a filter with jQuery to show just the fieldset I want to see:

```
$(document).ready(function(){
    $(document).on('keyup','#textfield-filter', {} ,function(e){

        if($(this).val()) {
            var val = $(this).val()
            $('#myform fieldset').each(function() {
                if($(this).attr('id').indexOf(val) >= 0){
                    $(this).show();
                }
                else {
                    $(this).hide();
                }
            });
        }
        else {
            $('#myform fieldset').each(function() {
                $(this).show();
            });
        }

    });
});

```

That works on page load. But I also have a Drop Down Select Menu to select a complete different set of fieldsets. With a click on a button the entiry page is refreshed with the set of fieldsets, which was selected in the Drop Down Menu. But unfortunately, the 'keyup' event of my textfield is not fired after refreshing the page with the button. As I said, I thought about a jQuery specific problem first, but the only solution I found was to attach the event handler for now and for the future, what I already did with `$(document).on('keyup','#textfield-filter', {} ,function(e)`.

The form is rendered with the Form API. If necessary I can -of cause- give you my php code.

I would welcome very advice.

Many thanks!

Daniel

# Answer
> 4 votes
You need to use the drupal behaviors: if you run your code on ready function when the form is rebuilded on an ajax action all the handlers you have active will disapear because the item fields are replaced by the new ones.

This is the basic drupal behaviors template:

```
(function ($) {
  Drupal.behaviors.mymodulecustombehavior = {
    attach: function (context, settings) {

      // Execute your code

    }
  };
})(jQuery);

```

This way after a ajax, all you code inside this behaviour will be called again.

Maybe you will want to add `.once()` property to avoid execute some parts of your code twice.

Documentation: https://www.drupal.org/node/756722

---
Tags: 7, forms, javascript
---


# Question
Title: Undefined property error in custom module
I am getting errors on specific pages of my drupal site pointing specifically to this line..

```
if (is_object($argument) && in_array($router_item['page_arguments'][$key]->type, array('article', 'page'))) {

```

what could be the problem? Here's the complete error and function.

Notice: Undefined property: stdClass::$type in custommodule\_menu\_local\_tasks\_alter().

```
function custommodule_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  foreach ($router_item['page_arguments'] as $key => $argument) {
    if (is_object($argument) && in_array($router_item['page_arguments'][$key]->type, array('article', 'page'))) {
      foreach ($data['tabs'][0]['output'] as $key => $value) {
        if (($value['#link']['path'] == 'node/%/edit'||'node/%/view') && (!user_access('administer nodes'))){
          unset($data['tabs'][0]['output'][$key]);
        }
      }
    }
  }
}

```

Edit: There are similar error in following line..

```
foreach ($data['tabs'][0]['output'] as $key => $value) {

```

--Notice: Undefined offset: 0 in custommodule\_menu\_local\_tasks\_alter() (line 59 of...) --Warning: Invalid argument supplied for foreach() in custommodule\_menu\_local\_tasks\_alter() (line 59 of ...).

# Answer
> 0 votes
Most likely **$router\_item\['page\_arguments'\]\[$key\]-\>type** is undefined.

Try with :

```
if (is_object($argument) && isset($router_item['page_arguments'][$key]->type) && in_array($router_item['page_arguments'][$key]->type, array('article', 'page'))) {

```

Same thing for that foreach loop. Just add an if isset() before that loop and you'll be ok.

```
if (isset($data['tabs'][0]['output']) ) {
    foreach ($data['tabs'][0]['output'] as $key => $value) {
        ....

```

---
Tags: 7
---


title: Clean URL not working

text:
# Question
Title: Clean URL not working
I have downloaded Drupal 8.x-dev at https://drupal.org/node/572834 to test on my local PC (Xubuntu 14.04 Beta 1).

I have successfully installed but when I try to access Admin menu is giving me "Not Found" pages, though on a simplytest.me sandbox it working ok.

What am I doing wrong?

# Answer
> 19 votes
**SOLUTION:**

Thanks to @tenken for giving me a hint this was related to "clean urls" issue.

I got this working with the following steps:

1. Run `sudo a2enmod rewrite` \# Enabling "rewrite" module
2. In `/etc/apache2/apache2.conf` and look at the block `<Directory /var/www/>` changed from `AllowOverride None` to `AllowOverride All`
3. Run `sudo service apache2 restart`

This reference was helpful https://drupal.org/getting-started/clean-urls

# Answer
> 1 votes
I'm not sure the paged you linked is actually a `-dev` release from like 2013.

A page that lists the recent releases can be found here: https://drupal.org/node/3060/release

I recommend installing the:

drupal 8.0-alpha9, Posted by catch on February 19, 2014 at 2:29am

Keep in mind that Drupal8 prior to I believe any `Beta` release is not officially supported by any upgrade path (to my knowledge). If you're a programmer and not a casual site administrator or user; code you write may be affected/break as Drupal8 matures to a release candidate.

Somebody please correct me if I got the `Supported` version wrong (even for just developers from an API standpoint; I know like the new Migrate API is still unstable).

**EDIT:**

After commentary, it turns out ModRewrite needed to be enabled on Apache for these paths to work without a querystring parameter.

# Answer
> 0 votes
I was having the problem where I would go to my-site.com/admin/what-ever-page, I would get an error.

I made sure that the AllowOverride All was set.

Also made sure that the rewrite module was installed and enabled.

Still had the issue.

What I found was that cURL had not been installed. Once that was in place and the server was restarted, the */admin/* pages started working.

---
Tags: 8
---


title: access node title in field.tpl.php

text:
# Question
Title: access node title in field.tpl.php
I would like to access the title of the node a field belongs to in a `field.tpl.php` file. My goal is to transform the field into a `mailto` link that would use the node title as the subject field.
Is it possible to access that information at this point?

# Answer
> 5 votes
You could get the node values from: `$element['#object']`: The entity to which the field is attached.

So in this case if the field is a node field the $element\['#object'\] is the node object.

```
print $element['#object']->title;

```

Documentation: https://api.drupal.org/api/drupal/modules!field!theme!field.tpl.php/7

---
Tags: theming
---


title: Domain Access And Subfolders

text:
# Question
Title: Domain Access And Subfolders
This has indeed been asked somewhere but still no answer. Is there a way to have domain access provide links like example.com/site1 instead of side1.example.com Thank you

# Answer
> 0 votes
I am sure you are looking for the Subfolders Domain module.

> Create and configuring easily the hierarchy Subdirectory multi-site for your Drupal multi site from one installation and a single shared database. This module allows you to add new subdomains directories or management of subdomains directories without changing/adding any file configuration (such .htaccess, sites.php, Alias in Apache config file, ...)

---
Tags: domain-access, subsites
---


# Question
Title: Drilldown search with Search API and Facets
I have a type 'projects' referencing two other types ('kustomer','products') via entity reference. Now I want to implement a drilldown search. I therefore use search API with facete api. I build a index and a view for Type 'project'. The filtering works well on this view. I have facetes for types 'customer' and 'product' and can filter.

The target is a workflow where you start at a list of 'products'. When you select one you will get a list of 'customers' where a 'project' exists that contains that 'product'. After that you select a 'customer' and you get a List of all 'project's having that 'product' and 'customer' preselected as facetes.

Can someone point out a module or configuration that does that? Thanks in advance Clemens

# Answer
I use CER, "Corresponding Entity References" to achieve similar results, but not with Search\_API.. for that, I just tell the search-page to render the "teaser", and modify the teaser display to include the entity\_reference list of associated entities as links, that way, if you search for a "Kustomer", it will show you a list of Kustomers and each project will also appear as a list of links underneath the title, or visaversa, you can also use Facets to filter by taxonomy etc.. handy!
> 0 votes

---
Tags: entities, search
---


title: How can I use cookies on Webform?

text:
# Question
Title: How can I use cookies on Webform?
I'm using Drupal 7 and Webform and I want, remember input texts on next submissions for registered users.

How can I do it?

# Answer
Try the Webform Field Repeat module

> The Webform Field Repeat module enables the webform to remember selected field entries from current submission for up to an hour. It uses the $\_SESSION to do so. If the session is active, the form will be populated with selected entries from remembered submission when opened again.
> 1 votes

---
Tags: 7, webforms, javascript, cookies
---


title: Cannot start Drupal

text:
# Question
Title: Cannot start Drupal
I am getting this error from drush:

```
Fatal error: Call to undefined function ctools_include() in          /home/upgrade6/democratsabroad/drupal/sites/all/modules/contrib/message_notify/message_not ify.module on line 167

Call Stack:
    0.0005     169008   1. {main}() /usr/share/php/drush/drush.php:0
    0.0257    4517736   2. drush_main() /usr/share/php/drush/drush.php:14
    0.0879   11100240   3. _drush_bootstrap_and_dispatch()    /usr/share/php/drush/drush.php:59
    0.1089   11108144   4. drush_bootstrap_to_phase() /usr/share/php/drush/drush.php:79
    0.5435   73935888   5. drush_bootstrap() /usr/share/php/drush/includes/bootstrap.inc:308
0.5440   73939144   6. _drush_bootstrap_drupal_login() /usr/share/php/drush/includes/bootstrap.inc:185
0.5442   73939560   7. drush_drupal_login() /usr/share/php/drush/includes/bootstrap.inc:945
0.5442   73939824   8. user_load() /usr/share/php/drush/includes/drupal.inc:138
0.5442   73940880   9. user_load_multiple() /home/upgrade6/democratsabroad/drupal/modules/user/user.module:366
0.5442   73941400  10. entity_load() /home/upgrade6/democratsabroad/drupal/modules/user/user.module:291
0.5442   73941928  11. entity_get_controller() /home/upgrade6/democratsabroad/drupal/includes/common.inc:7804
0.5442   73943096  12. entity_get_info() /home/upgrade6/democratsabroad/drupal/includes/common.inc:7835
0.5576   75414672  13. drupal_alter() /home/upgrade6/democratsabroad/drupal/includes/common.inc:7674
0.5596   75472128  14. message_notify_entity_info_alter() /home/upgrade6/democratsabroad/drupal/includes/module.inc:1101
0.5596   75472264  15. message_notify_get_notifiers() /home/upgrade6/democratsabroad/drupal/sites/all/modules/contrib/message_notify/message_notify.module:73

```

I tried reinstalling ctools but cannot enable it.

# Answer
> -1 votes
It seems that you have updated your site from previous version and this module was not included in this update. Please follow **`this`** link to get possible solutions.

---
Tags: drush, chaos-tool-suite
---


# Question
Title: Can I access node ID of the parent node of a field collection field in field-collection-item--FIELD_NAME.tpl.php
I am just hoping to get the node ID of the parent node in a `field-collection-item--name.tpl.php` template file.

So if my parent node name is mypage in which I have child fields of field-collection-item--name.tpl.php, I just want to access the Node ID of the parent page (mypage) in field-collection-item--name.tpl.php.

Is it possible?

Apparently somewhat yes. If I do this, I get details on the parent node. The only problem is that that data is protected. The output of this line is pasted below. All I want is **\[vid\]** value (i.e. 120)

```
  $var = $content["field_image_title"]["#object"];
  print_r ($var);

```

## Output of above line

```
FieldCollectionItemEntity Object
(
    [fieldInfo:protected] =>
    [hostEntity:protected] => stdClass Object
        (
            [vid] => 120
            [uid] => 1
            [title] => My Parent Page Name
            [log] =>
            [status] => 1
            [comment] => 1
            [promote] => 0
            [sticky] => 0
            [vuuid] => f3c2f63d-5d86-4d94-98f3-8a1ba76ce1f9
            [nid] => 120
            [type] => subpage
            [language] => und
            [created] => 1408623334
            [changed] => 1408640101
            [tnid] => 0
            [translate] => 0
            [uuid] => 486dead0-4f72-45a3-988c-64512e6b91de
            [revision_timestamp] => 1408640101
            [revision_uid] => 1

```

Any help on how I can get this vid value in this protected array?

Thanks.

# Answer
Load the field collection using entity\_load by passing the entity id. It gives you object where you can get the Host entity of the loaded entity. example profile2 will have user entity as host entity, or commerce line item will have commerce order as host entity.

```
$entity = entity_load('field_collection_item', $your_file_collection_id);
$host_entity = $entity->hostEntity();
echo $host_entity->nid;

```
> 8 votes

# Answer
I know this question is kind of old but I wanted to just give a quick answer because I had the same problem and stumbled upon here and the existing answers didn't satisfy me (though I'm not saying they don't work, I just found a simpler way to solve my problem). I just hope it may help anyone else finding this thread.

Anyway my solution is to just use the `hostEntity()` method of the field-collection entity. Simple example:

```
$var = $content["field_image_title"]["#object"];
$parent_node = $var->hostEntity();
$nid = $parent_node->nid; // for the node id, similarily for other values of the node.

```
> 4 votes

# Answer
You can access that information using a *Preprocess function* on the field from your themes `template.php`

Something along the lines of http://dropbucket.org/node/764

```
function MYTHEME_preprocess_field(&$vars) {
  // you need to know the name of your field collection here.
  // dpm($vars) by using the Devel module may help you figure that out.
  if($vars['element']['#field_name'] == "field_your_fc_field") {
    $fcs = array();
    foreach (element_children($vars['element']) as $key) {
      $fcs[] = array_pop($vars['element'][$key]['entity']['field_collection_item']);
    }
    // now you have all your fcs pulled out of that nasty array
    foreach ($fcs as $fc) {
      # code ...
      # Can access the VID or NID you want
      # $nid = $fc->nid;
      # $vid = $fc->vid;
    }

    // I would recommend overrideing items markup for whatever black magic you desire
    $vars['items'] = array(
      '#markup' => "Whatever you need to render",
    );
  }
}

```
> 0 votes

# Answer
All I needed was the nid of the parent, so I wound up going with:

```
$parent_node = menu_get_object();

```

This gave me access to the full node info, and I could use what was needed. It's not quite as elegant as the solution above, but I wanted to keep it simple.
> -1 votes

---
Tags: entities
---


title: Views aggregation?

text:
# Question
Title: Views aggregation?
I have a view that lists users. These users have skills. Two users are listed multiple times; one user three times; twice with "no skill" and once with the skill they have; another one twice, once with "no skill" and once with the skill they have. If I enable aggregation, skills are gone; if I don't, I get duplicate results. I have tried distinct as well, to no avail. Please see the screenshot below.

What can I do to eliminate this issue?

K.

# Answer
It seems that some profiles were not showing because their "skills" were missing. When I completed a profile in a way that they have a "skill", it also showed up.
> 0 votes

# Answer
If the skills come from taxonomy terms, you can do as follows.

Choose 'group results' for both title and the taxonomy terms. Then in the taxonomy terms dialog it should show a dropdown to group by 'entity id' or 'taxonomy id'. Choose 'entity id'.

No need to check the boxes.

https://www.dropbox.com/s/sooau5vccardovy/Screenshot\_2014-12-26-13-06-12\_1.jpg?dl=0

(cant embed the image on phone...)
> 1 votes

---
Tags: views
---


# Question
Title: How to set domain based search using search_api_solr?
I am using Domain and Search API Solr module in my project. On all domains, searching for a content gets result(content) from all domains. I would like to get search results according to the domain.
For example, if a user is on domain *a.domain.com*, then the search should return content which is published on *a.example.com* only and not on any other domains or sub-domains.

# Answer
> 1 votes
You could take a look at Search API Domain Access sandbox project: https://www.drupal.org/sandbox/raf/2244229

I did a work around based on that code that worked for me:

```
<?php
/**
 * Implements hook_entity_property_info_alter().
 *
 * Adds an entity property for the domain access of the node.
 *
 * @TODO this is just a workaround @see https://www.drupal.org/sandbox/raf/2244229
 */
function my_module_entity_property_info_alter(&$info) {
  $properties = &$info['node']['properties'];
  $properties['my_module_domain_access'] = array(
    'label' => t('My Domain Access Information'),
    'description' => t('The domains to which the node is published.'),
    'type' => 'list<integer>',
    'getter callback' => 'my_module_get_domain_info',
  );
}

/**
 * Custom getter callback for the domains in
 *
 * @param $data
 * @param array $options
 * @param $name
 * @param $type
 * @param $info
 * @return null
 */
function my_module_get_domain_info($data, array $options, $name, $type, $info) {
  return (!empty($data->domains) ? $data->domains : NULL);
}

/**
 * Implements hook_search_api_query_alter().
 *
 * Adds a filter for the current domain.
 */
function my_module_search_api_query_alter(SearchApiQueryInterface $query) {
  $domain = domain_get_domain();
  $query->condition('my_module_domain_access', $domain['domain_id']);
}

```

Now, you will be able to choose the field for indexing under "admin/config/search/search\_api/index/your\_index/fields" and in query time this code will filter out data based on current domain, not many more things.

Hope it helps, but notice that this code it is not fully tested (nodes that have been published in more than one domain... etc).

# Answer
> 0 votes
In your Search View set the use current domain as a View filter.

---
Tags: 7, search
---


# Question
Title: Change Quantity of multiple products and add it to cart
I've been looking a while for a good solution to add 2 products with the same quantity to the cart with rules. In my case a customer can buy a basic product and if he wants an additional product he can get it only with the same quantity. Is this possible with rules? I didn't find any dynamic solution for this.

# Answer
> 1 votes
This should be possible. What I would do (from the bottom of my head, other alternatives can be easily implemented) is described below.

**Assumptions:**

**Method:**

* Create a rule on event 'add an item to the cart'
* Condition: the added item has reference to 'additional' products (so this is not an additional product).
* Redirect to a view page which presents all products that are relevant to the current user's cart items (a view on order items entities).
* The view should have an add to cart button without quantity
* Create a rule on the same event 'add to cart'
* Condition: the added item has no reference.
* Loop through all cart items and call a rules component.
* Create a rules component with 2 arguments (item added, item from loop) and 1 condition: if item from loop has reference to the item added), return the quantity.
* Set the item quantity to the one returned by the component.
* Optionally redirect to somewhere else.

Mind that the condition needs a bit of care. Alternatively, you can avoid Rules altogether and create a custom module which will use the Drupal Commerce API.

---
Tags: commerce, rules
---


title: Five star ratings and reviews

text:
# Question
Title: Five star ratings and reviews
I have tournament details. I want to rate and review each of tournament details. Here I displayed all details of tournament and I have installed vote and five star rating module. But I could not connect with tournament details. How to make it so that when clicking "tournament details", it will move to a new page with rate and review option?

I am using custom module for displaying tournament details.

# Answer
If you want to display comment in separate page, then you need to configure comment form be display in new page.

Comment setting for the Content type:

* Go to Administration -\> Structure -\> Content type
* Edit your content type.
* Unchecked check-box "Show reply form on the same page as comments" under "Comment settings" section and save the form.

Now, you can add `www.example.com/comment/reply/[nid]#comment-form` link in your code to link comment in separate page.

Kindly see that `[nid]` is your node id.

If you have added "Rating" to comment, then it will also display in same page.

**Update:**

Adding Rating(five star) field to comment section:

* Go to `Administration -> Structure -> Content types`
* Click on `Manage fields` link in row of your content type and it will redirect you to `fields` settings page for your content type.
* Click on `comments fields` link in top of page and you can manage the field for comment section.
* Add new field of `fivestar rating` field type in comment.
* `Voting target` should be `parent node` in field configuration for your `fivestar rating` field.
> 1 votes

# Answer
Setting Up the Content Type (node-type)

```
Go to the admin/config/content/fivestar
Create a new Tag called "Rating" (e.g. vote, Rating).
Go to your content type.
Add a new Fivestar Field, called "Rating".
Select Widget type: Stars (rated while viewing).
Save Field.
Select Tag: Rating.
Save field Settings
Select 'Number of stars' (Make sure it will be the same on both the content type and the comments
Be sure to check "Allow users to vote on their own content" otherwise you won't be able to test it working on your own content
Make any other customizations
Save Settings
Go to your content type's display settings.
Click the settings button (gear icon on the right side) for the "Rating" field.
Make sure Value to display as stars is set to 'Average Vote'
Make any other customizations.
Click 'update'
Save your content type

```

Setting Up the Comments/Ratings

```
Go to the comment field settings for the content type we just added our field to.
Use 'Add existing field' and add the same 'Rating' field you used on the content type.
Widget: "Stars (rated while editing)".
Save Field.
Select 'Number of stars' (Make sure it is the same as the content type you created above.).
Select Voting Tag: Rating.
Voting target: **Parent Node**.

Voting Target
Make any other customizations.
Save settings.
Go to the comment display settings.
Click the settings button (gear icon on the right side) for the "Rating" field.
Change Value to display as stars: User's Vote.
Change Text to display under the stars: User's vote
Make any other customizations.
Click update.
Click save.
Voila!
P.S. If you use 7x-2.x version of fivestar module, please, first check out this issue to make it work according to new voting api changes. NOTE: The whole setup works just fine with Fivestar 7.x-2.x-dev from 2014-Mar-24 and Voting API 7.x-2.12

```
> 1 votes

---
Tags: 7, entities, rating, database
---


# Question
Title: Arrange formatted fields in Views row using a template
I want to render the rows of my “Recent content” Views page using a template in order to

* subdivide the rows into multiple divs,
* freely move around the rendered fields within these divs, and
* apply some custom PHP where needed.

**Idea A (fails):** I could achieve this by creating a new Display Suite layout for nodes and using this layout to render my view set to display format “Content”. However, I need to group the rows by a specific field, and grouping by fields is not available in the “Content” display format – for this, I would need to chose the display format “Fields”.

**Idea B (fails):** When displaying fields (say, as an unformatted list), I can make use a copy of

* views-view.tpl.php to adjust the coarse layout of the view, e.g., put an additional div around the whole content block;
* views-view-fields.tpl.php to adjust how a single field should be rendered;
* views-view-unformatted.tpl.php to adjust the coarse layout of rows, e.g. put an additional div around the whole row. However, here the $row variable is not an array of rendered fields but rather a string containing the full html markup of the row, so I cannot access single fields and move them around within the row as I wish.

**Idea C (works, but isn't it extremely inefficient?):** I could display an unformatted list of fields, but render only the Node-ID-field. Then, in views-view-unformatted.tpl.php I can load the whole node corresponding to the current row via $node = node\_load($row); and access all fields attached to it via $node-\>field\_whatever. These I can then move around as I wish, wrap in divs, and apply custom PHP.

Idea C seems to work, but it also seems highly inefficient, as I will have to load the full node for every row. Also, I want to leverage the many views display formatters that my fields come equipped with, which I would have to re-build manually.

**Question:** Is there a way to specify formats for specific fields within the Views UI, submit only these to a template (and not the whole node), and move them around freely within the row as explained above?

# Answer
I had a similar issue recently and this is what I did.

Let's say for the sake of argument that we have 6 fields: A to F. I wanted to wrap A-C in a layer eg "col-1" and D-F in a second layer eg "col-2". I overrided the field templates (`views-view-fields--field-*.tpl.php`) for A, C, D, F as such:

* Added a `<div class="col-1">` element in A, **without a matching closing tag** `</div>`.
* Added a `<div class="col-2">` element in D, **without a matching closing tag** `</div>`.
* Added the respective closing tags `</div>` i n **C and F**.

This may show some error or warning in your IDE, but the rendered HTML should be ok **as long as the order of the fields in the views allows it** (eg don't re-arrange D to be above C).
> 0 votes

---
Tags: 7, views, entities
---