# Question
Title: Share users database from one Drupal database with other Drupal Installs (separate databases, not just prefixed tables in the same db)
I have several Drupal databases and core sites currently. What I want to have is several Drupal databases that share a common users database under one core site source. The reason I want this is so that I can restore a sites database from any date I choose without rolling back the other sites content as well. I have looked into prefixing but it sounds like all sites have to be under the same database, the same seems to be true of domain access.

# Answer
> 2 votes
Instead of using table prefixes, you can use a reference to another database as a prefix. For example, `core` database holds the shared users / permissions, `drupal_website` database is your actual website.

```
$databases['default']['default'] = array(
    'driver' => 'mysql',
    'database' => 'drupal_website',
    'username' => 'db_username',
    'password' => 'db_password,
    'host' => 'ip_db_server',
    'prefix' => array(
         'default' => '',
         'users' => 'core.',
         'users_roles' => 'core.',
         'sessions' => 'core.',
         'role' => 'core.',
         'role_permission' => 'core.',
         'authmap' => 'core.',
    ),
);

```

Minor drawback, your database needs to be stored on the same mysql server and each database uses the same credentials (username / password) for the connection.

# Answer
> 1 votes
If you install multiple Drupal instances inside the same database you will need to use a different prefix for each different Drupal site, so as far as I understand you cannot share the users table between them. And trying to sync that table yourself doesn't sound like a proper solution.

And as you say, using Drupal as a multi-site CMS alonside the Domain Access module is only possible for one single Drupal installation, in a single shared database.

If you need different Drupal sites installed in different databases, you could achieve what you want managing the user authentication outside Drupal. There are some Drupal modules already there, for example the Lightweight Directory Access Protocol (LDAP) module; or you could create your own authentication module, which is something not very difficult.

# Answer
> 0 votes
Try CAS module. Read the files README.txt and README\_SERVER.txt for instructions on how to install and configure it.

---
Tags: 7, database
---


title: Creating New Region In Impulse Theme

text:
# Question
Title: Creating New Region In Impulse Theme
Hey guys I am just looking for help with my page tpl file.... I understand after researching that I need to add code to a specific region in the file I am unsure of what to exactly implement (code) wise and am wondering if someone can show me where and what to put in.

What I am trying to do is create a new region in the menu bar region as my theme does not currently have a block in my desired region. I need to create this region because I am using the "Mega Menu" module and this for obvious reasons needs to be placed on the menu bar location.. right now I just kind of have it in a different region which looks awful because there are two menu bars ( default menu & mega menu)

I am a drupal newbie and am looking very forward to completing my website but am unfortunately am pretty slow as I'm still exploring and having to watch a lot of youtube videos to learn properly... but I am learning! last time I tried to youtube it and look for info online my site ended up looking like a hurricane went through.

Below I will include the code of my file for you guys to view.. if you can kindly look at it for me and explain to me where to put the new code it would be much appreciated.

div id="page-wrapper"\>

"\>

```
<?php if ($logo): ?>
  <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo">
    <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />
  </a>
<?php endif; ?>

<?php if ($site_name || $site_slogan): ?>
  <div id="name-and-slogan"<?php if ($hide_site_name && $hide_site_slogan) { print ' class="element-invisible"'; } ?>>

    <?php if ($site_name): ?>
      <?php if ($title): ?>
        <div id="site-name"<?php if ($hide_site_name) { print ' class="element-invisible"'; } ?>>
          <strong>
            <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home"><span><?php print $site_name; ?></span></a>
          </strong>
        </div>
      <?php else: /* Use h1 when the content title is empty */ ?>
        <h1 id="site-name"<?php if ($hide_site_name) { print ' class="element-invisible"'; } ?>>
          <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home"><span><?php print $site_name; ?></span></a>
        </h1>
      <?php endif; ?>
    <?php endif; ?>

    <?php if ($site_slogan): ?>
      <div id="site-slogan"<?php if ($hide_site_slogan) { print ' class="element-invisible"'; } ?>>
        <?php print $site_slogan; ?>
      </div>
    <?php endif; ?>

  </div> <!-- /#name-and-slogan -->
<?php endif; ?>

<?php print render($page['header']); ?>

<?php if ($main_menu): ?>
  <div id="main-menu" class="navigation">
    <?php print theme('links__system_main_menu', array(
      'links' => $main_menu,
      'attributes' => array(
        'id' => 'main-menu-links',
        'class' => array('links', 'clearfix'),
      ),
      'heading' => array(
        'text' => t('Main menu'),
        'level' => 'h2',
        'class' => array('element-invisible'),
      ),
    )); ?>
  </div> <!-- /#main-menu -->
<?php endif; ?>

<?php if ($secondary_menu): ?>
  <div id="secondary-menu" class="navigation">
    <?php print theme('links__system_secondary_menu', array(
      'links' => $secondary_menu,
      'attributes' => array(
        'id' => 'secondary-menu-links',
        'class' => array('links', 'inline', 'clearfix'),
      ),
      'heading' => array(
        'text' => t('Secondary menu'),
        'level' => 'h2',
        'class' => array('element-invisible'),
      ),
    )); ?>
  </div> <!-- /#secondary-menu -->
<?php endif; ?>

```

```
<?php if ($breadcrumb): ?>
  <div id="breadcrumb"><?php print $breadcrumb; ?></div>
<?php endif; ?>

<?php if ($page['sidebar_first']): ?>
  <div id="sidebar-first" class="column sidebar"><div class="section">
    <?php print render($page['sidebar_first']); ?>
  </div></div> <!-- /.section, /#sidebar-first -->
<?php endif; ?>

<div id="content" class="column"><div class="section">
  <?php if ($page['highlighted']): ?><div id="highlighted"><?php print render($page['highlighted']); ?></div><?php endif; ?>
  <a id="main-content"></a>
  <?php print render($title_prefix); ?>
  <?php if ($title): ?>
    <h1 class="title" id="page-title">
      <?php print $title; ?>
    </h1>
  <?php endif; ?>
  <?php print render($title_suffix); ?>
  <?php if ($tabs): ?>
    <div class="tabs">
      <?php print render($tabs); ?>
    </div>
  <?php endif; ?>
  <?php print render($page['help']); ?>
  <?php if ($action_links): ?>
    <ul class="action-links">
      <?php print render($action_links); ?>
    </ul>
  <?php endif; ?>
  <?php print render($page['content']); ?>
  <?php print $feed_icons; ?>

</div></div> <!-- /.section, /#content -->

<?php if ($page['sidebar_second']): ?>
  <div id="sidebar-second" class="column sidebar"><div class="section">
    <?php print render($page['sidebar_second']); ?>
  </div></div> <!-- /.section, /#sidebar-second -->
<?php endif; ?>

```

```
<?php if ($page['footer_firstcolumn'] || $page['footer_secondcolumn'] || $page['footer_thirdcolumn'] || $page['footer_fourthcolumn']): ?>
  <div id="footer-columns" class="clearfix">
    <?php print render($page['footer_firstcolumn']); ?>
    <?php print render($page['footer_secondcolumn']); ?>
    <?php print render($page['footer_thirdcolumn']); ?>
    <?php print render($page['footer_fourthcolumn']); ?>
  </div> <!-- /#footer-columns -->
<?php endif; ?>

<?php if ($page['footer']): ?>
  <div id="footer" class="clearfix">
    <?php print render($page['footer']); ?>
  </div> <!-- /#footer -->
<?php endif; ?>

```

# Answer
> 0 votes
```
Create Region in theme .info file like this:-

regions[mega_menu]  = Mega Menu

now clear the cache of your site

After that checkout your menu block in structure blocks.
As Drupal automatically creates the blocks for menus And then assign  that menu block to the region  'Mega Menu'.

After assigning render in on page.tpl.php file like this :-

<?php if ($page['mega_menu']): ?>
    <?php print render($page['mega_menu']); ?>
<?php endif; ?>

```

---
Tags: blocks, theming
---


title: Page not found with new content

text:
# Question
Title: Page not found with new content
I just create a new content type and add a couple of nodes but I get 'The requested page could not be found.' message with anonymous users, apparently the nodes of this new content type require admin permissions, I've been searching on user management and enable access content but for this particular content type still need admin permission, any idea?

# Answer
I believe this is a caching issue.

'The requested page could not be found.' is not the same as 'You are not authorized to access this page.'

Because you can see the page as the admin account but not as an anonymous user, I believe you can fix this issue by flushing your Drupal caches.

The admin account doesn't show cached content by default but the anonymous users do.

There are several ways to Clear Drupal's Cache but the simplest is likely to go to admin/config/development/performance.

If you use drush, simply run 'drush cc all'
> 0 votes

# Answer
Check out the following things:-

Firslty when we creating a node of particular content type:-

Check that node is published or not.

and then

Checkout the permissions and give permissions to those roles that can view the node.

If you have given permission to anonymous user then any one can view the node.

Node can now be shown to anonymous users if it is not viewing then one time clear the cahe and then check.
> 0 votes

---
Tags: users
---


title: How to style the default upload button?

text:
# Question
Title: How to style the default upload button?
**Problem**

I want to style the default upload buttons. How should I go about doing this?

# Answer
Since this was a bit of pain to work through I thought I'd post a solution for everyone.

The base of the solution comes from this post:

http://geniuscarrier.com/how-to-style-a-html-file-upload-button-in-pure-css/

There are is another solution to CSS only styling for upload buttons, but it involves wrapping the input element in a label, which is difficult with how Drupal handles the markup.

**1. Add CSS**

First we add the following two chunks to our CSS file, you can read through the explanation at the post above basically we're making the file input button transparent and styling the area behind it.

Then when you try to click on the area behind it, you actually click on the invisible input button.

```
.form-type-managed-file {
  position: relative;
  overflow: hidden;
}

input.form-file {
  position: absolute;
    top: 25px;
    right: 0;
    margin: 0;
    padding: 0;
    font-size: 20px;
    cursor: pointer;
    opacity: 0;
    filter: alpha(opacity=0);
}

```

Now you may have noticed that we want to style the area behind it. To that we're going to need to add an HTML element to the managed file output which we can then style:

**2. Change HTML output**

Copy the image file function into our template file (for this example we'll be changing the image upload style) and then add two divs after `<div class="image-widget-data">`

```
function MY_THEME_image_widget($variables) {
  $element = $variables['element'];
  $output = '';
  $output .= '<div class="image-widget form-managed-file clearfix">';

  if (isset($element['preview'])) {
    $output .= '<div class="image-preview">';
    $output .= drupal_render($element['preview']);
    $output .= '</div>';
  }

  $output .= '<div class="image-widget-data"><div class="bold file-button">Choose File</div>
  <div class="file-name file-button margin_10_top_bot">No File Selected</div>';
  if ($element['fid']['#value'] != 0) {
    $element['filename']['#markup'] .= ' <span class="file-size">(' . format_size($element['#file']->filesize) . ')</span> ';
  }
  $output .= drupal_render_children($element);
  $output .= '</div>';
  $output .= '</div>';

  return $output;
}

```

If you don't care about the filename of the uploaded file remove the second div and you're done. (You'll need to alter the CSS to make the invisible button sit above your added upload div.)

However if you want the name of the file then leave it in and we move onto a little JS.

**3. Add JS**

It's impossible the get the name of the file without JS so we add a quick JS script to get it to run, first we call it in the template file:

```
function MY_THEME_preprocess_page (&$vars) {
    drupal_add_js('sites/all/themes/MY_THEME/js/file_upload.js', 'file');
}

```

Then we add the following script:

```
(function ($) {
  Drupal.behaviors.uploadfunctionAddClass = {
    attach: function (context, settings) {
      $(":file").change(function(){
        $(this).prev().text($(this).val().replace(/C:\\fakepath\\/i, ''));
      });
    }
  };
})(jQuery);

```

It looks for any changes to elements of type file, which in the output for a drupal managed file field is one.

Grabs the element directly before it (the second div we added in step 2) and changes the text in it to it's new value. The path will have C:\fakepath\ added to it, so we remove that as well.

The reason we use Drupal Behaviors rather than document ready, is because we need the script to apply after an AJAX call. If someone uploads a picture, removes it and adds a different one then the script won't have applied to the new elements because they've been added with AJAX. The Drupal Behaviors wrapper causes them to be called every time.

Congrats we're all done.
> 3 votes

# Answer
Hey You can do this as i have did on my site like this:-

```
1.Like i have file field

        $form['title']=array(
          '#title'=>'file',
          '#type'=>'file',
          '#attributes'=>array('class'=>(array('file_button'))),
        );
$form['markup']=array(
'#type'=>'markup',
'#markup'=>'<span class="file_span" onclick="click_file()">File</span>'
)

2.in css do this
.file_button{visibility:hidden;width:1px;}
.file_span{backgrounf:#4e0056;color:#ffffff;padding:4px 16px}

3. in javascript add this function
 function click_file()
    {
        jQuery('.file_button').click();
    }

```

and get value like

$\_FILES\['files'\]\['name'\]\['title'\]

it contains file value.

Hope this will work for you.
> 1 votes

---
Tags: 7, files, theming
---


title: Import a node with its path alias

text:
# Question
Title: Import a node with its path alias
I'm using ne-impot and ne-export with drush for importing and exporting nodes. When exporting, as part of the uuid module, the URL alias is included with the export. However, when importing a node, the alias is not kept. I have tried using another custom module (https://github.com/kapasoft-config-scripts/designssquare\_alias\_path) that I found from this site: http://margotskapacs.com/2014/04/solving-menu-import-issue-when-featuring-sample-data-in-drupal, but that doesn't seem to be working either. Does anyone know of a way to import and export a URL alias along with the node from the command line? Thanks!

# Answer
> 0 votes
Try the Pathauto module to do this. I found it helpful for auto-aliasing URLs in bulk, and you can also customize it by using

```
function MyModule_pathauto_alias_alter(&$alias, array &$context) {

}

```

it works pretty well.

---
Tags: 7, path-aliases
---


# Question
Title: Permission option for unblock the selected users not listed
I have created a user & assingned it role 'superuser'.I want to give only two permissions to superuser, block the selected user account & unblock the selected user account.I have given 'block selected user' permission from admin-\>people-\>permission but the option for 'unblock the selected user account' permission is not listed in admin-\>people-\>permission.How can i give this permission to superuser?

# Answer
You can create a view and give access to superuser role.

Below links will help you.

http://blog.safwan.in/post/69263954822/add-unblock-user-action-to-views-bulk-operation-vbo

http://dropbucket.org/node/486
> 0 votes

# Answer
I have followed the same links and created the module at some extent it is working fine that is there is an option "Unblock the user" is appearing in views bulk operation and permissions. But the problem, is it is not Unblocking the user in actual.
> 0 votes

---
Tags: users
---


# Question
Title: When adding a new product variation type no catalog options appear
I have installed the Commerce Kickstart installation profile and I am currently experimenting with it. The main problem I face is when adding a new product variation type and trying to create a new product using it, the vertical TAB where you select the product catalog, instead of this :

I get this :

So far I have tried reindexing and checking the views filters without finding the root cause of this.

# Answer
Turns out that when adding a new *Product Variation*, a new content type linked to this variation is automagically created with the corresponding representations.

All I had to do is adding the Catalog term reference to the linked content type.
> 1 votes

# Answer
You have to again add a new term references field to your new content type on which you have added new product variations. In this way you will see the product catalog for your content.
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: What's the best way to create a content type with multiple fields that link to an external URL?
I have a content type named "News Clip" that has four fields; Title, Description, Image, URL.

In my display, I want the Title and Image to link to the URL value.

Drupal has the concept of linking these fields to "Content", but that means the node itself. I want them to link to the URL.

I use Display Suite for my other content types and would like to avoid having to use a field template.

Is this possible? How?

Thank you.

# Answer
I usually set the fields to "hidden" under the "manage display" tab, and then print the fields however you like with a block view.

Just place that block view to appear on that content type only, and with a contextual filter to get content ID from URL.

You can also use the Title module to replace the title from the content type, which you can then hide and display in the same block view.
> 0 votes

# Answer
You can use view "rewrite results" option.

Create a view and add all the fields you want to display. Then choose "exclude from display" option.

click on "rewrite results" section and select "Rewrite the output of this field" and write html code, use "SHOWREPLACEMENT PATTERNS".
> 0 votes

---
Tags: entities, display-suite
---


# Question
Title: Remove disabled menu links from menu settings
I have a multilingual site, and when adding content theres an option to add a menu link. Both languages show up in the drop down selection, my goal is to hide/remove the links that are "disabled" (NOT in the current language).

So only the current language links should be visible in the dropdown.

# Answer
Never solved this, finally i deleted the drupal site and rewrote the site with dogescript.
> 1 votes

---
Tags: routes, hooks, forms, navigation
---


# Question
Title: Domain relationship module for drupal 7?
I want to create parent/child relationship in domain access module. My use case is:

Parent Domain: -\>child Domain

When I add a node to the child Domain it should also be automatically created on the parent Domain with an administrator approval required on the parent domain.

Means when I created a node on child domain it should be published and visible to the users on the child domain but it should not be visible to the user on the parent domain unless the administrator approve it.

I looked at the domain relationship module but it is only for drupal 6. Is there any alternative for domain relationship module for drupal 7?

# Answer
> 0 votes
I don't think you need another module. Just use Domain Access.

You can let users choose to which domain this node will be published. Make sure that the user that needs to approve the node has the following permissions:

* **Publish content to any assigned domain**
* **Set domain access status for all content**.

---
Tags: 7, domain-access
---


# Question
Title: how to have conditional required fields through hook_form_alter?
Here is basically what I'm trying to do. If the draft field is present I would like to make the name field not required.

```
if($form_state['values']['field_draft']['und'][0]['value']){
  $form['field_name']['und']['#required'] = FALSE; }

```

Is this even possible? I tried after\_build but it doesn't work. If not, is there a better way to add draft functionality through hook\_form\_alter.

Thanks!

# Answer
> 2 votes
In Drupal 7, I would use the following code.

```
/*
 * Implements hook_form_alter().
 */
function test_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'your_form_id':
      $lang = $form['name_field']['#language'];//get field language
      if(isset($form_state['values']['field_draft'][$lang][0]['value'])){
        $form['name_field'][$lang][0]['value']['#required'] = FALSE;
      }
      break;
  }
}

```

Note: Never use **und** try to get the language for multilingual sites. If site is not multilingual, then best to use the constant **LANGUAGE\_NONE** and not the string `'und'`.

# Answer
> 0 votes
please try it in hook\_form\_alter

```
$form['field_name']['#required'] = isset($form_state['values']['field_draft'][LANGUAGE_NONE][0]['value']) ? FALSE : TRUE;

```

---
Tags: 7, entities, hooks
---


# Question
Title: Can't save custom field data: form submit function doesn't fire
I've added custom "markup" field to the commerce\_product table, next I've implemented hook\_form\_FORM-ID\_alter, but submit function doesn't executed.

# Answer
If you add the custom field through hook\_form\_alter. You need to store the data manually in your custom table by using your custom submit handler.. Otherwise you could use the below code in your \*.install file

```
function MYMODULE_enable() {
  // Check if our field is not already created.
  if (!field_info_field('field_myField')) {

    // Create the field base.
    $field = array(
      'field_name' => 'field_myField',
      'type' => 'text',
    );
    field_create_field($field);

    // Create the field instance on the bundle.
    $instance = array(
      'field_name' => 'field_myField',
      'entity_type' => 'user',
      'label' => 'My Field Name',
      'bundle' => 'user',
      // If you don't set the "required" property then the field wont be required by default.
      'required' => TRUE,
      'settings' => array(
        // Here you inform either or not you want this field showing up on the registration form.
        'user_register_form' => 1,
      ),
      'widget' => array(
        'type' => 'textfield',
      ),
    );
    field_create_instance($instance);
  }
}

```
> 1 votes

---
Tags: forms
---


# Question
Title: How to get the highest value of a specific field in a multivalue field collection
How to get the highest value of a specific field in a multivalue field collection, USING PHP?

This is about displaying the right discount for a marketplace product.

There is a node type Product with two field collection fields: (1) field\_discount which contains: \- a field for the minimum quantity required for the discount \- a field for the discount percentage (2) field\_price which contains: \- a field for the base price \- a field for the discounted price

The reason why (2) is also a field collection, is because I want to allow the marketplace sellers to show multiple price options. This might be relevant information because it seems that the views reference filter module does not work with field collections. Using that module would have made this issue a lot easier. Instead, this question focuses on using PHP, unless someone has another solution that does not require or requires less PHP coding.

The discount price needs to be built on the fly when a product node is displayed, using the raw quantity value from the URL and calculating the discount. My solution was to use a jump menu view with numbers 1 to 1000, which adds the quantity to the URL, like http://xxxx.com/node/100/5 in which the "5" as product quantity is inserted by using the jump menu. However, this might not be the most efficient method in the context of this issue. You are free to suggest another approach if that serves a more efficient solution to this issue.

STORING DISCOUNT AS VARIABLE Only after the customer sees the discount price and clicks ORDER (a flag button), the transaction values are stored in transaction entity fields. Therefore, the transaction values need to be available as variables.

Using PHP code in Global NULL, Session variables. My current approach is to use a Global Null as views contextual filter, default value PHP code, in order to fetch field values and calculate discount, and to store the values as SESSION variables. Since no transaction entity is created yet, I can't see another way to store these values for further use in the (possible) transaction.

My experience with php and metadata wrappers etc is insufficient, especially with regard to fieldcollections.

WANTED: the discount percentage, corresponding with the quantity chosen by the buyer. The discount percentage must be within the range of quantities specified by the product owner. Solutions with either other Drupal modules, or custom php are both welcome. As mentioned above I tried the views reference filter, using an exposed filter referencing quantity values of the field collection, but I couldn't get that to work.

# Answer
Try the Computed Field module

Computed Field is a very powerful field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of fields. So start cooking up your PHP based values!
> 0 votes

---
Tags: entities
---


# Question
Title: Creating a userlist in Views (including custom user fields)
I've encountered an issue using Views 3 in Drupal 7. I want to create a user list with a bunch of fields I added to the user profile (using Drupal's core user fields). I need a list of **all** users, and right now I keep getting the currently created content and its author (with the appropriate user fields). Not all users have created content.

I've created a relationship "Content: Author" to get access to the custom user fields, but that's not the reason I keep getting the content with its author. I get the same result when I remove the relationship and custom user fields.

In Drupal 6 with views2 I made the same page and had no issues. Could this perhaps be a bug in Views 3, or am I missing something?

# Answer
> 8 votes
Your question makes it sound like you've created a node view, listing content. If you create a view listing *users*, you should be able to accomplish what you're trying here.

# Answer
> 0 votes
You can now get a better administrative users list by installing the Administrative Views module.

---
Tags: views, users
---


# Question
Title: hook_views_data Join by multiple value field
I need retrive data from a custom table in drupal db by a colum that match with a drupal field in a content type.

I have this table:
**equipages<br>id\_equipage|description|price|status**

The *id\_equipage* is a varchar and is unique.
**records example**:
cliowave123abs|ABS of my Renault Clio|150|1
cliowave123oth|Some other option of my Renault Clio|10|1
cliowave123air|Air cond of my Renault Clio|250|1
meganeliveabs|ABS of my Renault Megane|310|1
Now I have a content type called *car* whit a text field *equipages* (table field\_data\_equipages) with unlimited values.
In this field I add all the id\_equipage of the car.
So for example I have a node (nid: 5) like this:
Title: Clio Wave 2013
equipages:
1. cliowave123abs
2. cliowave123air

Now, When I read the node (nid: 5), I want retrive the 2 records from my custom table
cliowave123abs|ABS of my Renault Clio|150|1
cliowave123air|Air cond of my Renault Clio|250|1

Can I do this whit the hook\_views\_data()??

Can you help me?!

Thanks!

# Answer
> 2 votes
I believe this https://www.drupal.org/node/810932#comment-3020000 comment describes exactly what you need which is the `extra` field in a join description:

```
$data['node']['table']['join'] = array(
  // this explains how the 'node' table (named in the line above)
  // links toward the node_revision table.
  'node_revision' => array(
    'left_field' => 'nid',
    'field' => 'nid',
    'extra' => array(array('field' => 'fieldname', 'value' => 'value', 'operator' => '='))
 ),

```

);

---
Tags: views
---


title: Subscription to User-saved searches

text:
# Question
Title: Subscription to User-saved searches
Required functionality:

* User can filter nodes based on certain relevant custom fields.
* User can save filter criteria as a named set.
* User can view and edit these sets of filter criteria.
* User can "subscribe" to changes based on his saved sets of filter criteria and get email notifications containing links to only the newly matching nodes.

Can I build such subscriptions with mostly out-of-the-box functionality of Rules and related modules?

Subscriptions depending addressfield field is a related question, but the poor lad did not get an answer.

# Answer
Conceptually the business logic you want to complete is possible using Drupal. Finding a way to make this scale to a very large website -- I leave as a project for you.

Start by looking at Saved Searches and Views Saved Search or Views Save. These modules let you save a search with a simple name for later re-use. Some of these modules allow per-user saved searches.

You could then create a Queue using the Queue API in Drupal to periodically process the resultsets of these searches. Or even use the Relation module to store heuristics on these resultsets.

Create a cron task using `hook_cron` or Rules Scheduler to periodically process the resultsets and have Rules to send off emails about new changes in the saved searches. Functions like `views_get_results` (if you use views\_saved\_searches) can help you to get these results.

So in general yes it's possible with Drupal -- scaling all this to a very large amount of users is either an infrastructure problem or something (i think) "Drupal" shouldn't do in the long run ...
> 3 votes

---
Tags: 7, rules, notifications
---


# Question
Title: Multiple points openlayers geojson display only the last of it
I made a module retrieving data with geodata. The import feature allows to create a file in geojson. So, i'd like to display the points and the data without using Views, only openlayers module. I saw the layer example provided with the module : *Example GeoJSON, "Picture This"*, displaying a marker with the given raw geojson data provided. In the Layer section, I tried to use the URL field instead of the raw data field to provide a link to my datafile, but when i use it on a map, only the last point is displayed.

I saw that in the example :

```
  {
    "type": "Feature",
    "properties": {
      "name": "Picture This",
      "description": "Outside of the North Carolina Museum of Art."
    },
    "geometry": {
      "type": "Point",
      "coordinates": [
        -78.702798,
        35.809411
      ]
    },
    "crs": {
      "type": "name",
      "properties": {
          "name": "urn:ogc:def:crs:OGC:1.3:CRS84"
      }
    }
  }

```

but the "regular"geojson is a collection of such features :

```
{ "type": "FeatureCollection", "features": [
      {
        "type": "Feature",
        "properties": {"name": "point1", "description": "desc of 1"},
        "geometry": {"type": "Point", "coordinates": [-78, 35]
        }
      },
      {
        "type": "Feature",
        "properties": {"name": "point2", "description": "desc of 2"},
        "geometry": {"type": "Point", "coordinates": [-79, 34]
        }
      }
]}

```

So, since i have more than 1 point i used the second version, and i only get the last point showing when i use this overlay on a map.

Is there something special to do to display several point or shapes (from a layer) using that technique : i'd like to avoid using Views or any other plugins for this.

I've read https://www.drupal.org/node/1481374 and other generic openlayer Drupal 7 tutorials, but i haven't found any help for this kind of problem. Thanks in advance

# Answer
Finally, i found out that the problems (only the last point and that point wasn't at the right place) had nothing to do with my geojson file : i created a new layer and by default it had projection **EPSG:3857**, but i needed a projection with GPS coordinates =\> **EPSG:4326** see this . With that change, every point is now displayed. I guess with the wrong projection, all the points where somehow stacked, and then only the last one was displayable.

In Openlayer \> Layers

* Use Projection EPSG:4326 (instead of EPSG:3857)

In Openlayer \> Map Use

* Map Projection EPSG:3857 (Default)
* Display Projection EPSG:4326(Default)
> 0 votes

---
Tags: javascript, location
---


# Question
Title: Is there a way to upload files to the theme directory
I use the following code to upload images should be used in slideshow of the theme settings `theme-settings.php`:

```
for ($i = 0; $i < 7; $i++){
      $form['best_responsive_settings']['slideshow']['slideimages'][] = array(
        '#type' => 'managed_file',
        '#title' => t('Image').' #'.$i,
        '#upload_location' => file_default_scheme() . '://theme/backgrounds/',
    '#default_value' => theme_get_setting('background_file'),
    '#upload_validators' => array(
      'file_validate_extensions' => array('gif png jpg jpeg')),

      );
  }

```

Those files are uploaded to: `sites\default\files\theme\backgrounds` I want to change the uploading location to `sites\all\themes\best_responsive\images\backgrounds`. **How could I change `'#upload_location'` to do that?**

# Answer
> 3 votes
It doesn't look like the file module places any restriction on the upload path, so in theory it should be as simple as:

```
'#upload_location' => DRUPAL_ROOT . '/' . drupal_get_path('theme', 'MYTHEME') . '/images/backgrounds';

```

However, having your theme folder writable by the web server would usually indicate that permissions are not set correctly. It would be a better idea to fix those, and save your images in the proper location (i.e. sites/default/files); see Securing file permissions and ownership for full details.

---
Tags: 7, forms
---


# Question
Title: What is the easiest way to update thousands of users' "created date"?
I want to change all user created date. Is it possible use VBO for that? However, I don't see any option to change the user's created date there.

Originally the site is migrated from Joomla; I have thousands of users with a blank created date, and I want to set them to a week ago.
Can this be done with VBO?

# Answer
> 1 votes
This answer assumes that changing the created dates is a one-time action, and that other modules in your Drupal site do not need to react to the users being updated.

IMHO, if you're looking at modules to do this, you're making things way too complicated for yourself. A simple SQL query should to the job:

```
UPDATE users SET created = 1234567890 WHERE uid <> 0;

```

You can choose / calculate the timestamp yourself (where it says `1234567890` in my example). I'm excluding the record with user id 0 because this repesents the anonymous user who does not have a created date.

How to run this query:

* From a MySQL admin tool, like phpMyAdmin or HeidiSQL, whatever you have to access your database;
* From the command line using the mysql command (don't know if this works on Windows):

```
$ mysql -u user_name -p -e 'UPDATE users SET created = 1234567890 WHERE uid <> 0' database_name

```
* From the command line using Drush:

```
$ drush sql-query "UPDATE users SET created = 1234567890 WHERE uid <> 0"

```

---
Tags: users, views
---


# Question
Title: How to filter a view by the value of a global variable (as with the variable module)?
I have a global variable, which is the id of a node representing a current organic group that changes every year. I'd like to have a rules view that filters on members of that group. I've added the right relationships and a filter on the group id of the membership entity. But I can't enter a token or a variable value in the filter dialog. What can I do?

# Answer
> 2 votes
Use **contextual filter** and **Provide default value** = PHP Code

---
Tags: 7, views
---


# Question
Title: Showing a block in specific content types and URLs
I have a block I want to show in specific content types and some URLs.

I tried adding the following code.

```
  $match = FALSE;
  // block is visible on the content types entered here
  $types = array('story' => 1, 'page' => 1);
  $url = request_uri();
  if ((arg(0) == 'node') && is_numeric(arg(1))) {
    $node = node_load(arg(1));
    $match = isset($types[$node->type]);
  }
  // block is invisible on URLs entered here
  if (strpos($url, "edit")) {
    $match = TRUE;
  }
  // copy paste these for additional URLs
   if (strpos($url, "taxonomy/term/8")) {
    $match = TRUE;
  }
  return $match;

```

Is it possible to use wildcard or something to include all the child in this taxonomy, instead of using taxonomy/term/8?

# Answer
> 1 votes
If you want to check all children of specified term below code can help you

first load all children of it ,then check its term ids one by one

```
$tids=array_keys(taxonomy_get_children(8));
foreach($tids as $tid)
 if (strpos($url, "taxonomy/term/".$tid)) {
    $match = TRUE;
    break;
  }

```

---
Tags: views, blocks
---


# Question
Title: Removing a row from a view depending on the user currently logged in
I have a view which prints out a table of blog posts. There are 2 columns - `title` and `tags`.

If a post has a tag assigned to it called `core-team` then users with the role `non-core` shouldn't be able to see the post displayed in the table.

The view which is created displays every blog post so everyone can see them - but I can't figure out how to remove or not show a `row` from the view if the user logged in is `non-core` and the post has the tag `core-team`.

Any ideas?

# Answer
> 2 votes
This isn't a views' problem. I'm assuming that the non-core users should not have access to the content that has the core-team tag anywhere (not just in the specific view). That's because if you use a "hack" to remove the result from the view, someone entering the specific blog post's url directly in his browser would take him to the node.

What you actually need to do is use the Taxonomy Access Control module to restrict access to the "core-team" tag. When you do that, the non-core user will not have permission to view the content tagged as "core-team", so the view will not display these results either (assuming that in the access restrictions of the view you left the default value of: "Permission").

---
Tags: views, users
---


# Question
Title: Conditionally enable/disable #autocomplete from client side js
I have a custom search field which searches for a type of content depending on the radio box selected. I have applied autocomplete functionality to the field using hook\_form\_alter but only want the autocomplete functionality to be available for one of the search types.

Is it possible to conditionally detach the Drupal.behaviors.autocomplete from the text field using my own js?

Update: I have managed to disable the autocomplete functionality by unbinding the events, but I do not know how to add/bind it again:

```
// update search box text when search type is changed
$(SI_SEARCH.radio).change(function() {
  // get search type
  SI_SEARCH.search_type = $(this).val().trim();
  switch(SI_SEARCH.search_type) {
    case 'course' :

      break;
    case 'university' :
      // disable autocomplete
      $('#edit-search').unbind('keydown keyup blur');
      break;
  }
})

```

# Answer
> 0 votes
Ok I managed to achieve this after digging into misc/autocomplete.js

To disable the autocomplete you can do the following:

```
$('#edit-search').unbind('keydown keyup blur');
$('#[AUTOCOMPLETE-ELEMENT-ID]-autocomplete-aria-live').remove();
$('#[AUTOCOMPLETE-ELEMENT-ID]-autocomplete').removeClass('autocomplete-processed');

```

To enable the it again:

```
Drupal.behaviors.autocomplete.attach(document);

```

My js ended up as:..

```
// update search box text when search type is changed
$(SI_SEARCH.radio).change(function() {
  // get search type
  SI_SEARCH.search_type = $(this).val().trim();
  switch(SI_SEARCH.search_type) {
    case 'course' :
      // re-attach autocomplete
      Drupal.behaviors.autocomplete.attach(document);
      break;
    case 'university' :
      // disable autocomplete
      $(SI_SEARCH.search_form).next().removeClass('autocomplete-processed');
      $(SI_SEARCH.search_form).unbind('keydown keyup blur');
      $('#edit-search-autocomplete-aria-live').remove();
      break;
  }
})

```

---
Tags: ajax
---


# Question
Title: Create validation to input alphanumeric and with specified symbols for field type password in user module
In the user module for field type password input I want to avoid hazardous characters input so i added #required and '#element\_validate. But as i am new to drupal i dont know how to processed and also i am not sure if i am in right direction or not . Please help me

```
if (!$register) {
  $form['account']['pass'] = array(
  '#type' => 'password_confirm',
  '#size' => 25,
  '#description' => t('To change the current user password, enter the new password in both fields.'),
   //The below two lines are added by naveena.
  '#required' => TRUE,
  '#element_validate' => array('user_pass_element_validate'),

);

function user_pass_element_validate($element, &$form_state, $form) {
  if (!empty($element['#value'])) {
    form_error($element, t(''));
  }
}

```

# Answer
You should use `user_validate_current_pass()`.
> 0 votes

---
Tags: users
---


# Question
Title: Importing nodes with different field names from Drupal 6 to 7
I need to import certain nodes from a Drupal 6 site to a Drupal 7 one. I have a particular situation:

* I need to import only nodes of a certain type
* Node types have different names in the sites ("Question&Answer" in the drupal 6 site, "Answers" in the drupal 7 one)
* The 2 types have the same fields, but some fields have different names (The drupal 7 nodes have additional fields, but they are not required)
* I need to put the id of the drupal 6 nodes in a field called "orig\_id", the drupal 7 nodes need to have different IDs
* Nodes have 4 taxonomy relations: 2 use Hierarchical select, 1 (tags) can have new terms added when creating a new content (and the 2 sites have a different set of tags at the moment). Taxonomy vocabularies have different names, but (except for tags) contain the same terms.
* Node Authors are the same in both sites, but they have different IDs. Importing authors references is not a must, so it can be skipped

I am fairly new to Drupal, i have tried searching for some import modules and/or articles about importing, but i can't find a guide that suits all my needs.

# Answer
I have solved by checking which fields i needed, i made a table with those fields then made a custom boostrappable script to import them as new nodes
> 0 votes

---
Tags: nodes, migrations, importing-exporting
---


title: Multisite with i18n module enabled

text:
# Question
Title: Multisite with i18n module enabled
We have to build a multi lingual site(English and Spanish). There are 2 approaches to enable multi lingual site

1. Single site with i18n module
    * Content,Functionality and layout are almost same for both languages
2. Multi site (Parent English Site and Spanish sub site separate)
    * Content,Functionality and layout are mostly different for Spanish site
    * Parallel Enhancement needs to be done for both languages
    * English language site needs to be redesigned without affection Spanish language site

We are preferring to choose the second approach to build the multilingual site. Please feel free to recommend the Implementation approach using i18n module.

# Answer
> 0 votes
You should read Drupal 7's new multilingual systems compilation. There's even a full book about that matter: Drupal 7 Multilingual Sites.

When using a single Drupal instance to create a multilingual site, there are two different approaches: **Content Translation** and **Entity Translation** (Read: Node translation vs. Entity (field) translation). You may want a multi-site setup (With Domain Access or without it), especially if you require independent content to appear (not only translations). And the Internationalization suite of modules is a must, it provides the following modules:

* Path Translation
* String Translation
* Taxonomy Translation
* Block Translation
* Variable Translation

---
Tags: i18n-l10n
---


# Question
Title: How to give space between rows of a table
I have a view in Drupal and I want to give more space between elements rows. How do I do it?

# Answer
> 0 votes
That's a basic CSS question, just use `padding` or `margin` and the view row class as the selector.

Consider outputting the view as an HTML list instead, and not as an HTML table, because with standard HTML tables these things become a bit tricky to do (and it's not recommended)

---
Tags: views, theming
---


# Question
Title: Making entities under another entitytype
Suppose, I've created -name -machine\_name an entity\_type `myentity` with its schema as:

```
-name
-machine_name

```

Next, I want to create another entity `subentity` that will be grouped under `myentity`.

I've create both the entities, but somehow during the form making, I'm clueless how to retrieve the `myentity` data under which I'm creating the `subentity` and save it.

`subentiy` schema:

```
-name
-parent (parent == myentity->machine_name)

```

# Answer
I'm not sure if your case is closer to the typical bundle/config entity \> content entity use case (because you mention machine name, so that sounds like a config entity to me) or content entity \> content entity but the way this works is pretty much the same.

You need to define a route that contains the parent entity ID, then create your entity with the reference to that and then display the add form for it.

Examples for the first use case are for example node type/node or vocabulary/term, the second are comments. While the first is usually not seen as a hierarchy/grouping, it's essentially that.

Route from node.routing.yml:

```
node.add:
  path: '/node/add/{node_type}'
  defaults:
    _content: '\Drupal\node\Controller\NodeController::add'
    _title_callback: '\Drupal\node\Controller\NodeController::addPageTitle'
  requirements:
    _node_add_access: 'node:{node_type}'
  options:
    _node_operation_route: TRUE

```

NodeController::add

```
public function add(NodeTypeInterface $node_type) {
  $account = $this->currentUser();
  $langcode = $this->moduleHandler()->invoke('language', 'get_default_langcode', array('node', $node_type->type));

  $node = $this->entityManager()->getStorage('node')->create(array(
    'uid' => $account->id(),
    'name' => $account->getUsername() ? : '',
    'type' => $node_type->type,
    'langcode' => $langcode ? $langcode : $this->languageManager()->getCurrentLanguage()->id,
  ));

  $form = $this->entityFormBuilder()->getForm($node);

  return $form;
}

```

The only relevant part is passing through the entity reference value ($node\_type) to the new sub-entity. There are issues to make the uid/name and the langcode default value handling work by default.
> 1 votes

---
Tags: 8, entities
---


# Question
Title: Adding dynamic and multiple fields for user profile using profile2 module in Drupal 7
I am creating profile like linkedin. Where user can have multiple education fileds and he can add/modify dynamically. Is there any plugin which suits my requirements.

The nearest I found is profile2 which is promising but does not provide me multiple entry functionality.

Can Drupal help me out how to fix this problem?

Thanks in Advance. Yatendra

Edit : I want profile types like linkedin education wizard. i.e. if user had entered education detail one time then there should be two option first one for editing education detail and second one for adding more education detail.

# Answer
Old question, but I have to say that Ankit's comment was on the right track. Install and enable Field Collection, because you will use this to group each instance of your education details fields.

Depending on whether or not you use Profile 2, create a Field Collection-type field at `/admin/config/people/accounts/fields` or `/admin/structure/profiles/manage/<profile_type>/fields`. The number of values for the field collection field should be greater than one or unlimited. Finally, create your education details fields at `/admin/structure/field-collections/<field_collection>/fields`.
> 1 votes

# Answer
I'd probably go with a mixture of the Conditional Fields module and setting the various fields to 'Unlimited'. Here is an excerpt about it from the module's project page:

> ... allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.
>
> When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API. You can, for example, define a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked.
> 0 votes

---
Tags: 7, users
---


# Question
Title: Views Slideshow Stops Working Alongside Other Slideshows
I've made several thumbnail-sized cycle slideshows as block views, which display fields from nodes created via an HTML feed. Each slideshow is basically the same, but they all use a different taxonomy term as a filter on a single content type, and have a different XPath parsing structure.

The slideshows work perfectly on each view's preview page. Each also works separately when its block is displayed on the main page. I've managed to get 6 slideshows at once scrolling normally as blocks on the main page.

However, when I display a 7th slideshow in a block on the main page, only two slideshows work properly, with the rest not progressing via time or clicking on the controls. If I add an 8th slideshow block, 3 of them work, and the other 5 do not.

The 7th and 8th slideshows have slightly different field output, as the feed source is configured differently, but I don't think this is relevant, as the view-generated HTML looks the same.

I can get sporadic results by re-arranging the blocks in the block list, and by displaying them in different block areas. Some permutations allow all the slideshows to function, some only allow a few.

Is there a limit to the number of JQuery slideshows that can be running at once? Or, is there maybe some kind of naming convention that's causing these mixed results with different ordering?

Totally confused, and disappointed. :(

# Answer
> 0 votes
After some inspired messing around, I determined that the issue only stopped slideshows that were displayed after a certain slideshow. Using that information, I deleted the isolated block, and re-created it in the same form as the other slideshows.

This appears to have solved the problem. I guess something was corrupt with that particular view. It was the one I was originally using as a clone base for all the other slideshow blocks.

Hopefully this "fix" persists!

---
Tags: blocks, views
---


# Question
Title: No menus being displayed in SideBar First
Im using my own Omega 3 sub-theme and a new superfish menu (I created) to be displayed in the Sidebar First section of each page...no big deal. The menu displays as needed in while Im admin, but the entire sidebar is gone when viewed as anonymous. Thinking it may be an issue with Superfish I disabled the new menu and added the standard navigation menu in its place...same issue.

I kept debugging and noticed a weird issue Ive never seen: no menus are working as blocks in the first sidebar. I can add a static block with simple text or content in it and the sidebar is displayed as needed, but never functions if a menu is the only content in the section.

Any ideas?

Thanks in advance.

# Answer
First of all, Menu works on the sidebar.

For your case, it's definitely the 'Permission' issue.

Permission for menu items: For example, you have only 'Add Content' item in the Navigation Menu. When you are logged in as an admin you have that menu on the sidebar as you have the permission to add a content. To display this item to authenticated/anonymous users you have to configure permission from 'Admin Menu' \> 'People' \> 'Permission'. Please check the permission of your menu items and configure as required.

Permission for Blocks: By default menu blocks have no permission restriction. Please check your menu block's permission section from 'Admin Menu' \> 'Structure' \> 'Blocks' \> 'Edit' the specific block \> 'Permission' tab at the bottom.

I hope it will help you.
> 0 votes

---
Tags: theming
---


title: CKeditor does not show icons properly

text:
# Question
Title: CKeditor does not show icons properly
The exact problem is that the editor doesn't show all the Toolbar icons. also, these that it does show, are black and white icons. something works wrong there...

Tried to change fields - didn't help. tried to go through all the options and re-save them, didn't help either. ideas?

Thanks.

# Answer
> 2 votes
I am assuming you recently updated ckeditor. The new version uses a black and white skin. There is also a know issue with updates and is noted in the issue queue. You need to go a resave all of your ckeditor profiles and flush drupal's cache, as well as your browser's cache.

# Answer
> 0 votes
Not sure, this might be the problem/solution. What has happened is you have installed the CK editor library as part of the drupal 7 WYSIWYG module/project. This only allows you to see this black and white editor.

http://johnathanthwaites.info/sites/default/files/toolbar.png

if you want the full editor including colour text, spell check and insert flash object etc etc. then you actually need to install CK editor *as a module* not as a library for wysiwyg. Then you get this one;

(Url above but image is toolbar2.png)

Ive done a full explanation here;

http://johnathanthwaites.info/Ckeditor

---
Tags: entities, wysiwyg
---


title: How to make a specific post RTL?

text:
# Question
Title: How to make a specific post RTL?
I have a page where i post English articles by default. but sometimes I have a Persian article that should be posted inside this page. After posting, it shows left to right and is very bad looking. specially if there is bullet points included in the articles. I want to know if there is a module for this or a way to edit my theme files.

# Answer
> 1 votes
Basically what you want to do is conditionally add a class to the field that aligns text to the right. I was wrong in my comment about hook\_page\_alter, I don't believe it has access to everything you need.

* set up a new field, called field\_content\_persian, check boxes/radio buttons, valued English and Persian, default to English
* in Manage Display, hide the label, and move the new checkbox field ABOVE the body. It must render first for this method to work
* add CSS - ie. style.css

```
.align-text-right{
  text-align:right;
}

```
* to template.php add:

```
function THEMENAME_field__field_content_persian__CONTENT_TYPE_MACHINE_NAME($vars){

  if($vars['element']['#items'][0]['value'] == 1){
    drupal_static('isPersian', true);
  }
  return "<!-- empty -->";
}

function THEMENAME_field__body__CONTENT_TYPE_MACHINE_NAME($vars){

  if(drupal_static('isPersian'))
  {
    $vars['classes_array'][] = 'text-align-right';
    $vars['classes'] .= ' text-align-right';
  }
  return theme_field($vars);
}

```

If you have a theme named Bartik, and a content type named Article, they would look like this:

Bartik\_field\__field\_content\_persian\__Article() and

Bartik\_field\__body\__Article()

What this does:

* in the first function (field\_content\_persian), it checks for the value of the checkbox, and if it finds it is 1(persian if order of elements in checkbox is correct - modify as desired), it sets a temporary static variable. Then it returns an empty string so that the field itself doesn't display - NOTE: this function MUST return something, anything, or Drupal will bypass the function and call the default
* in the second function it checks for the variable, and if it finds it, adds the class to the body field.

---
Tags: theming
---


title: Make search page with Taxonomy

text:
# Question
Title: Make search page with Taxonomy
I am fairly new to Drupal and i'm working on a already existing site, so i'm facing a lot of issues. I need to make a page that shows nodes of a certain type, it has to contain the following features:

* It has to show a search form on top of the page (the site is using the Apache Solr module) to search only content of one type
* It has to show nodes grouped under their taxonomy fields. There are 3 vocabularies and nodes have to be listed for each vocabulary, for example:

Vocabulary 1

Term 1

Node 1

Node 2

Vocabulary 2

Term 2

Node 1

Node 3

Nodes can be shown more than once for each Taxonomy term

I know i'm asking a lot and probably the question is borderline with the stackexchange rules, but i have tried a lot of modules and solutions (for example using the Views module) but i just can't get what i want no matter how i try

# Answer
> 1 votes
* to reduce results by the content type, when you set up the view, filter by content-type, and select the appropriate content type. If it already exists, use a FILTER CRITERIA and use content-type (I believe this can also be accomplished through the search settings)
* to group: set format to fields, add the taxonomy term to the fields list to group by (you can hide from display if desired), click on Settings under FORMAT. There you can group by any field currently in the view
* for Solr, take a look at Apache Solr Views Module and the related documentation for implementing this functionality.

Apache Solr Views:

> This module provides a Views integration to the Apache Solr Search Integration project. It provides the views plugins and handlers needed to be able to create a view that fetches its results from Apachesolr index, without hitting the database.

---
Tags: views, taxonomy-terms, search
---


# Question
Title: Views proximity search by postal code show all when empty
I'm using proximity search in views 3.

The proximity search is by Postal Code.

When first loading the view page, it's showing all result. In my case this is not good because the postal code is required for filtering.

My question is.

Is there a way to not showing all the result when postal code search field is empty.

Here is a screen shot of my views Criteria.

In More Thanks a lot

# Answer
In the settings for the exposed search field, you should be able to change the behaviour: On Empty input, Show None. Show All is set by default
> 0 votes

---
Tags: views
---


# Question
Title: Search api autocomplete with commerce kickstart
i am using search api with commerce kickstart i have created a view and used it as an exposed form on the homepage, I have used the search api autocomplete module but its not working because the server is not supported. So I have made a custom module to do the autocomplete feature for my search filter block. This is the code

```
<?php

function ajaxforms_menu() {
$items['ajaxforms/autocomplete'] = array(
'page callback' => 'ajaxforms_products',
'access arguments' => array('access ajax autocomplete'),
'type' => MENU_CALLBACK
);
return $items;
}

function ajaxforms_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'views_exposed_form-display_products-page') {
$form['#submit'][] = 'ajaxforms_submit_funtion';
}
}
function ajaxforms_submit_function(&$form, &$form_state) {
$search_str = $form_state['values']['views-exposed-form-display-products-page'];
$form_state['rebuild'] = TRUE;
drupal_goto('path_to_your_search_view', array('query' => array('search_api_view_fulltext' => $search_str)));
}

function ajaxforms_products($string) {
$matches = array();

// DB table which holds products
$query = db_select('commerce_product', 'p');

// Select rows that match the string
$return = $query
->fields('p', array('title'))
->condition('p.title', '%' . db_like($string) . '%', 'LIKE')
->range(0, 10)
->execute();

// add matches to $matches
foreach ($return as $row) {
$matches[$row->title] = check_plain($row->title);
}

drupal_json_output($matches);
}

```

But its not working I dont know where I am wrong on this. Anyone have any idea on how to solve this ? I want the autocomplete in the block of the exposed filter search which I am using as a block

# Answer
> 1 votes
I got it working by using this example jQuery Autocomplete

If anyone else get stuck in this just ask me and I'll try to help out

---
Tags: views, search, commerce
---


title: How to put the menu above the content?

text:
# Question
Title: How to put the menu above the content?
I'm developing a website with drupal 7. I want to put the menu above the content. I use zen theme. How I does it?

# Answer
Each menu has a corresponding block that is managed on the **Blocks administration page** : admin/structure/block.

Look for your menu block and on the right dropdown, choose a region where to display it. The blocks are displayed from top to bottom in the same order than on the admin page.

The regions are displayed in `sites/all/themes/zen/templates/page.tpl.php` : i.e navigation region is rendered with `<?php print render($page['navigation']); ?>`

To see where are the regions, you can use also the link *Demonstrate block regions*, you 'll have something like :
> 0 votes

# Answer
```
#block-system-main-menu {
   float: left;
    top: 0;
    width: 100%;
}
#block-system-main-menu ul.menu
{
float: left; width: 100%;
}
#block-system-main-menu ul.menu li
{
float: left; width: 15%;
}

```

Use this css.it will help you

Simply put Your menu block above main page content block in same region and that menu will show above the rendered content or other option can be to change the order of the regions in the page.tpl.php file in your theme.
> 0 votes

---
Tags: theming
---


# Question
Title: How can I override an entity form with the same date?
I have an entity form that requires choosing from a date field. I wanted to override a submitted entity form if there is an existing submitted form with the same date. I was looking for a solution in the net, but I was not able to find anything useful. Thank you in advance for those who can help!

# Answer
When new entity created you need to implement check (if entity with certain date exists) in your FORM\_ID\_submit() function. If so, use entity\_load() to edit existing entity, if not, create new one. Also I recommend using EntityFieldQuery and Entity Metadata Wrappers to deal with entities.
> 0 votes

---
Tags: datetime, entities
---


# Question
Title: Is it possible to change the form submit handler from within a validate handler (need to redirect to another form depending on values entered)
I have an initial webform (based on 3.x of webform module/Drupal 7) that needs to redirect to a second form if yes is specified in a yes/no choice. Otherwise if No, the first form should submit normally (with a webform result).

Also, if yes is entered on the first form, on submitting the form, the webform result is not to be stored for this form, but the webform result will be stored on the second webform. Values entered in the first form are carried through to the second, to autofill, I use the PHP \_SESSION variable to do this.

I'm having difficulty getting this to work completely. It always seems that I can get one part of the above working, but not the other. I'm using the standard approach of hook\_form\_alter and within this trying various combinations of setting the validate array and submit array and the form redirect property to do the redirect from the first and second form.

My approach now is to have a validate handler function to change the submit handler if the yes is chosen (for proceeding to the second form). Submitted values on the first form are available to the validate handler. The submit handler can do the redirect to the 2nd form.

But when I change the submit handler from within the validate handler, I see that this change gets overwritten by Drupal itself and I don't know why.

I have also found that the submit handler - which I use to set the form redirect, for the 'yes' choice - will not work if other submit handlers are present in the submit handler array. I have to empty the array and have only my function in it.

I had wanted to deal with the yes/no choicepoint at this stage in my own submit handler, but if I had to 'throw away' the other submit handlers, then the 'No' path won't work - the webform result won't get submitted.

Another approach I tried, to counteract my deleting of the other existing default submit handlers, was to programmatically submit a form for the the first form for the 'No' path so that it would get saved. However doing this I got an error about the number of submissions possible, even though it was set to unlimited (-1) in the config. From that I concluded that it was due to that I had already started the first form as a visitor and somehow the webform system 'notes' that, so programmatically submitted form would exceed that supposed maximum.

Note: I can't upgrade to webform 4.x as there are other forms on the site which may be impacted unexpectedly.

# Answer
You don't need to rewrite form submit handler. You can implement drupal\_goto() for your first form with FORM\_ID\_submit() depending on user input. Pass $form\_state\['values'\] as url options and fetch them from $\_GET array as #default\_values in second form.
> 0 votes

---
Tags: 7, webforms, redirection, forms
---


# Question
Title: Import Users from D6 to D7 without directly accessing database
I have to import users from a drupal 6 site to a drupal 7 one. I'd use https://www.drupal.org/project/migrate\_d2d but i have several limitations on what i can do on the databases:

* I can't access the drupal 6 DB from the drupal 7 installation
* I don't have ssh access on the D7 server, i can interact with the database only from phpmyadmin
* I can't create new databases on the D7 DB (i can create new tables though), and i can import sql files only to a maximum of 10MB. I can't upload a file on the server then import it from local either. I have no limitations on the D6 database

In addition, user roles are different from the 2 sites so i need to map them before importing. I think the best solution is to export data from the D6 site in some format and the import it on the D7 site but i don't know how to do it

# Answer
Views data export module is perfectly capable of exporting your users to CSV file. You would use Views to define what you want to have exported, so you can export anything. You can also use Views GUI to define mappings, if you want. It is a powerful toolset, and VDO uses all that power.

When you will have your users in CSV, you can use User Import to import them. Pretty obvious, isn't it? For mapping, User Import can

> * Match CSV columns to account and profile fields

So if you didn't manage to do it on the Views level, you can always edit CSV when you'll have it locally, or try to do it on import... So many options, I'm sure at least one will work.

Last but not least, make sure your users will get mails with "new password required" explanation, as D6 and D7 stores passwords in incompatible ways.
> 1 votes

---
Tags: importing-exporting, migrations
---


title: Facebook Auto Post not working?

text:
# Question
Title: Facebook Auto Post not working?
I configure the facebook modules. I created facebook Apps and I gave facebook auth id and secret key and all. But I couldn't connect with facebook. I got this type of Error?

# Answer
> 1 votes
**You need to provide website URL on your app settings.**

Step 1. Navigate to your app settings

https://developers.facebook.com/apps/\[your-app-id\]/settings/

Step 2. Under website section provide your website URL.

check this answer for Reference

---
Tags: 7, social-network
---


# Question
Title: Javascript not loaded in loading ctools modal
I have a some modal forms, the link of those embedded in views result, link are somethings linke `share/nojs/2` , I register a menu in callback of the links, It work correctly for root user, but I test it with 2 authenticated user, It work correctly for one of them and in another when I click link instead open modal form redirect me to `/share/nojos/2` and tell me **Javascript required**,according to my codes,It means the javascript not load, I really confused what happening and what can be reason of this ?

my codes :

```
$items['share/%ctools_js/%'] = array(
    // 'page callback' => 'ym_alter_sharing_content',
    'page callback' => 'ym_alter_sharing_callback',
    'page arguments' => array(1),
    'access callback' => 'user_is_logged_in',
    'type' => MENU_CALLBACK,
);

function ym_alter_sharing_callback($js = FALSE) {
    global $user;
// If people aren't using javascript, then I just boot em. sorry. its 2011.
    if (!$js)
        return "Javascript required";
// Include your ctools crap here
    ctools_include('node.pages', 'node', '');
    ctools_include('modal');
    ctools_include('ajax');

// Create a blank node object here. You can also set values for your custom fields here as well.
    $node = (object) array(
                'uid' => $user->uid,
                'name' => (isset($user->name) ? $user->name : ''),
                'type' => 'share',
                'language' => LANGUAGE_NONE,
    );

    $form_state = array(
        'title' => t('sharing'),
        'ajax' => TRUE,
    );

    $form_state['build_info']['args'] = array($node);
// change this to your type node form
    $output = ctools_modal_form_wrapper('share_node_form', $form_state);

// This means the form has been exectued
    if (!empty($form_state['executed'])) {
        $output = array();
// Close the modal
        $output[] = ctools_modal_command_dismiss();
// I use this method a lot on pages that have views, so what I do is get the latest view content
// with the latest node and replace the current view. magic!
        /*
          $html = views_embed_view('my_view', 'my_display';
          $output[] = ajax_command_html('.view-display-id-my_display', $html);
         */
    }
    print ajax_render($output);
    exit;
}

```

# Answer
> 1 votes
this looks like a hook\_menu() implementation:

```
$items['share/%ctools_js/%'] = array(
// 'page callback' => 'ym_alter_sharing_content',
'page callback' => 'ym_alter_sharing_callback',
'page arguments' => array(1),
'access callback' => 'user_is_logged_in',
'type' => MENU_CALLBACK,

```

);

you should wrap it in a corresponding function and return menu items:

```
function your_module_name_menu() {
  $items['share/%ctools_js/%'] = array(
    // 'page callback' => 'ym_alter_sharing_content',
    'page callback' => 'ym_alter_sharing_callback',
    'page arguments' => array(1),
    'access callback' => 'user_is_logged_in',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

```

other code seems to be ok. Hope this helps someone.

---
Tags: javascript, chaos-tool-suite
---


# Question
Title: How to add a conditional billing field based in Country in "Commerce Kickstart"?
I added a new billing **mandatory** field called "NIN Number" at `admin/commerce/customer-profiles/types/billing/fields`

But I only need to show this new field only if the selected country is **United Kingdom**

How can I do this?

Will the https://drupal.org/project/conditional\_fields module be usefull to get it?

# Answer
I don't think you can use conditional fields because of the internal structure of the addressfield module, you need to use some custom code here, using the #states property and checking against the value of the country. Using hook\_form\_alter, you can edit that form, here's an example of #states coming from the examples module:

```
  $form['high_school'] = array(
    '#type' => 'fieldset',
    '#title' => t('High School Information'),
    // This #states rule says that the "high school" fieldset should only
    // be shown if the "student_type" form element is set to "High School".
    '#states' => array(
      'visible' => array(
        ':input[name="student_type"]' => array('value' => 'high_school'),
      ),
    ),
  );

```
> 1 votes

# Answer
Yes, you can use Conditional Fields module for that.

After installing the module, you need to create field dependency (e.g. by going to: Administration » Store » Customer profiles » Profile types » Billing information » Manage dependencies).

So dependent field is your NIN/VAT field, dependee is your Country/address field.

For standard fields (e.g. Countries) it should work straightforward.

If you're using Country as part of Address Field, then you can set input mode to Regular expression with value (e.g. `GB`, two `GB|US` and so on) and custom jQuery selector for dependee (e.g. `select.country`).

---

Eventually in form alter or for custom forms (as already suggested), something like:

```
// Show NIN field if user selected "United Kingdom" as a Country.
$form['account']['login']['field_profile_nin']['field_profile_nin'][LANGUAGE_NONE]['#states'] = array(
  'visible' => array(
    ':input[name="account[login][field_profile_country][field_profile_country][und]"]' => array('value' => 'GB'),
  ),
);

```
> 0 votes

---
Tags: commerce
---


# Question
Title: Save user selection after search in views
I am facing a problem with views. Is it possible somehow to save the user selection when a user is doing a search?

To get it clearer, I'm having a list of users. Let's say, I am searching for customer A via filters, then select the found customer, change my filter to find customer B and select him to. But every search, resets my selection. I'm looking for a possibility to save the selection and have A and B selected in the end.

# Answer
> 1 votes
Go to your views \>\> Exposed filter settings and check ***Remember the last selection*** checkbox

If you want to go further then try the Views Saved Searches module

> This module allows you to save your current configuration of exposed filters for later use. This can be especially useful for Views with a lot of exposed filters.
>
> Whenever a View is changed, all saved searches for that View are deleted, to prevent corruption. If the user has JavaScript enabled, the saving and deleting process happens through AHAH, and the new section is displayed below the exposed filters section. When JavaScript is disabled, the new section is displayed above the exposed filters section.

---
Tags: 7, views
---


# Question
Title: create chains of views joins so one view can 'see' across more than one join
Assuming the individual joins work can we join multiple times across columns like this?... (BTW I've checked this first query and it does indeed work correctly)

```
SELECT *
FROM a
LEFT JOIN b
ON a.a_id = b.references_a_id
LEFT JOIN c
ON b.references_c_id = c.c_id
LEFT JOIN d
ON c.references_d_id = d.d_id

```

As per the following table.column structure:

```
a.a_id
a.a_col

b.b_id
b.references_a_id
b.references_c_id
b.b_col

c.c_id
c.references_d_id
c.c_col

d.d_id
d.d_col

```

Is it possible to link these together in a view so that because we have the joins defined in hook\_views\_data\_alter() we can have the following:

**pseudo-description of the Views setup:**

```
(views setup)

"SHOW" 'a'

...

"FIELDS" > "add" > overlay menu "Add fields" >
    a: a_id
    a: a_col
    b: b_id
    b: references_a_id
    b: references_c_id
    b: b_col
    c: c_id
    c: references_d_id
    c: c_col
    d: d_id
    d: d_col

```

So because this is not working for me... in hook\_views\_data\_alter()

```
$data['b']['table']['join']['a']['left_field'] = 'a_id';
$data['b']['table']['join']['a']['left_table'] = 'a';
$data['b']['table']['join']['a']['field'] = 'references_a_id';
$data['b']['table']['join']['c']['left_field'] = 'c_id';
$data['b']['table']['join']['c']['left_table'] = 'c';
$data['b']['table']['join']['c']['field'] = 'references_c_id';
$data['c']['table']['join']['d']['left_field'] = 'd_id';
$data['c']['table']['join']['d']['left_table'] = 'd';
$data['c']['table']['join']['d']['field'] = 'references_d_id';

```

... I wonder if I should be doing something bizarre like this...

```
$data['b']['table']['join']['a']['left_field'] = 'a_id';
$data['b']['table']['join']['a']['left_table'] = 'a';
$data['b']['table']['join']['a']['field'] = 'references_a_id';
$data['b']['table']['join']['c']['left_field'] = 'c_id';
$data['b']['table']['join']['c']['left_table'] = 'c';
$data['b']['table']['join']['c']['field'] = 'references_c_id';
$data['b']['table']['join']['c']['left_table']['c']['join']['d']['left_field'] = 'd_id';
$data['b']['table']['join']['c']['left_table']['c']['join']['d']['left_table'] = 'd';
$data['b']['table']['join']['c']['left_table']['c']['join']['d']['field'] = 'references_d_id';

```

# Answer
> 0 votes
I added a relationship to the mix and that's opened up two extra sets of fields ('c' and 'd') I can't explain why, I think it's something to do with the joins that were already setup on these base tables. This then meant that when I bridged them with the relationship it opened it all up.

example:

```
$data['a']['a_id']['relationship']['handler'] = 'views_handler_relationship';
$data['a']['a_id']['relationship']['base'] = 'b';
$data['a']['a_id']['relationship']['base field'] = 'references_a_id';
    (... etc.)

```

---
Tags: views, entities
---


# Question
Title: Referencing/relating content between content types
I'm completely noob on Drupal, actualy I'm trying to find a way to build a website idea using it.

I want to let users/visitors to create travel tips, so at this site I'll have contents like: Countries, States, Cities, Places and tips.

A tip must be related with a Place, that is related to a City and a State Country. Also a tip must contain any number of images related to it.

The thing is, I' just can't find a way to do it with a fresh install on Drupal, neither find somewhere I can see an code example of it, if I need to really code it.

I thought in creating a Entity type, but didn't found how to do it without coding, and I also need a way to let users upload any number of images they want, and them show everything on a page (I believe this is the easiest part, after I get the other ones).

Anyone can help me with a quick way to figure this out? Maybe a few blog post links, a ebook, videocast, anything.

Thanks!

# Answer
Take a look at the Entity Reference Module:

> Provides a field type that can reference arbitrary entities:
>
> * A generic entity reference field
> * Four widgets:
>     + Two implemented on top of the Options module (Select and Radios/Checkboxes),
>     + Two autocomplete widgets (one with one text field per entry, one tag-style with comma-separated entries in the same text field)
> * Two formatters:
>     + A "Label" formatter, with optional link that displays the label of the referenced entity (the node title, the user name, etc.)
>     + A "Rendered entity" formatter, that renders the references entity using a configurable view mode
> * Integration with Views (for both forward and backward references)
> * Integration with Entity Metadata (and as a consequence with Search API and the like)
> * Integration with Devel generate
> * Integration with Feeds and Migrate (\>= 2.3) for painless data import

That should get you started.
> 1 votes

---
Tags: nodes
---


# Question
Title: Alternate links in a multilingual site Drupal 7
I have a multilingual website currently on localhost. I want to add the alternate links to each page like this: rel="alternate" hreflang="x". How do i do that? What about the canonical urls? I have already installed SEO suite module enabled.

# Answer
> 2 votes
You might want to try Menu attributes module.

> This simple module allows you to specify some additional attributes for menu items such as id, name, class, style, and rel.
> The module currently allows you to set the following attributes for each menu item:
> \- Id
> \- Name
> \- Target
> \- Rel
> \- Class
> \- Style
> \- Accesskey

# Answer
> 2 votes
You can use Meta Tags module for canonical links.

> The Meta tags module allows you to automatically provide structured metadata, aka "meta tags", about your website. In the context of search engine optimization, when people refer to meta tags, they are usually referring to the meta description tag and the meta keywords tag that may help improve the rankings and display of your site in search engine results.
>
> Meta tags have additional uses like the Open Graph Protocol used by Facebook, specifying the canonical location of content across multiple URLs or domains.

# Answer
> 1 votes
The Internationalization contributions module says that it adds the `rel="alternative"` `hreflang="x"` to multilingual pages:

> Internationalization contributions is a set of modules that are add ons for Internationalization module to provide compatibility with other contributed modules or some other features.

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


# Question
Title: Buttons get longer when pressed if using AJAX
I'm using Ajax Commerce Cart Cart with a custom Drupal 7 theme that I made with Artisteer, but the issue does not seem to just be related to the one module. Whenever AJAX is attached to a button, when the button is click it pretty much doubles in width while the AJAX process is taking place and then returns to it's original size.

I wasn't sure what code or information you'd need so please do ask if you need me to upload anything or provide further details. Does anyone know of any solutions to this problem?

Thanks in advance

# Answer
> 1 votes
I suspect it's the trobber, you know the little .gif image showing an ajax loading.

You can fix it via css, but to find out the class/id to edit, i had to break the ajax and force it to never complete the load, so i had time to inspect the markup with firebug.

check this discussion:

https://www.drupal.org/node/1059674

---
Tags: 7, ajax, theming
---


title: Lightbox2 doesn't show image

text:
# Question
Title: Lightbox2 doesn't show image
I have Lightbox2 installed on my Drupal Project. I am trying to use lightbox2 through links, for example:

`<a href="/absolute-path-to-image" rel="lightbox">
 Link
</a>`

It works only when I turn on the Lite version. How can I make it work on normal one? I have read that there is a possibility of wrong path. Already checked all of the possibilities and I can confirm it's not that. Is it possible that it collide with jQuery?

Thanks.

# Answer
I think.. It will help to u.. Use views module and add image fields and rewrite the image fields. Look this image nkana-\> database name.
> 2 votes

---
Tags: views, 7, javascript
---


title: Assign ID to Main Menu

text:
# Question
Title: Assign ID to Main Menu
I am working on Drupal 7 project (omega 4 subtheme) with panels and views. I need to assign ID an ID (id="nav") to a DIV that wraps main menu UL. It is a child of div.l-region--navigation. It's the second row of the example bellow.

```
<div class="l-region l-region--navigation">
<div class="panel-pane pane-block pane-system-main-menu">
    <ul class="menu">
        <li><a href="home">Home</a></li>
        <li><a href="home">Home</a></li>
    </ul>
</div>

```

Anyone knows how to do this? Is there a specific drupal way of doing this?

# Answer
```
function mytheme_links__system_main_menu($variables) {
$site_frontpage = variable_get('site_frontpage', 'node');
  $html = "<nav id='main-nav' class='animate'>\n";
  foreach ($variables['links'] as $link) {
      if($link['href'] == '<front>') {
        $html .= "<a class='1' href='" .$site_frontpage ."'>" .$link['title'] ."</a>";
      }
      else {
        $html .= "<a class='2' href='" .$link['href'] ."'>" .$link['title'] ."</a>";
      }
  }
  $html .= "</nav>\n";

  return $html;
}

```

The code can be used in template.php to override the output of the . However, the only variable it seems to accept is $tree, which prints out all the contents of a and so is not very helpful.
> 2 votes

# Answer
You can simply achieve that using the Menu attributes module

> This simple module allows you to specify some additional attributes for menu items such as id, name, class, style, and rel.
> 1 votes

---
Tags: routes
---


# Question
Title: Where is saved the value of the 'help text' of field of content type?
I know that you can set help text for any field in the content type, but where this text is saved in databese, because I want to access it in other way not only for tooltip?

Thanks

# Answer
> 1 votes
It's in the field instance settings (stored in the `field_config_instance` table). The preferred API method to use is `field_info_instance()`:

```
$info = field_info_instance('node', 'field_foo', 'article');
$help_text = $info['description'];

```

---
Tags: entities, database, tooltips
---


# Question
Title: Views 'Search terms' exposed filter not working as expected
I have a view that displays a list of people. I want to allow the list to be filtered by its search terms, so I've added a 'Search terms' exposed filter. I'm using hook\_form\_alter() to override this exposed filter so the user can select from a list of countries, so they can "Search by country". This just passes a country name in as the exposed filter value. I've added a second 'Search terms' exposed filter so a user can further filter by keyword.

This doesn't seem to work as expected. When I choose 'Australia' from the first filter, I get 39 results, which is correct. When I then enter 'Astronomy' into the second filter, I get no results. I expected to get back 1 result, a user whose node contains both 'Australia' and 'Astronomy'. If I leave one filter blank and enter 'Australia Astronomy' into the other, I get the correct user result.

Is there a way to make this work the way I want to? The first exposed filter has to be filtering on a node's indexed content (find country mentioned anywhere in the node), so I can't filter on a single field here. Thanks in advance!

# Answer
> 2 votes
The mistake comes from the WHERE conditions :

```
AND(( (search_index.type = 'node') AND( (search_index.word = 'australia') ))AND( (search_index.type = 'node') AND( (search_index.word = 'astronomy') ))))

```

This will always return empty result ! Not convinced? simply try

```
    SELECT * FROM `search_index` WHERE `word` = 'Australia' AND `word` = 'Astronomy'

```

So you'll need a subquery here : for the sake of example, let's say :

```
SELECT node.title AS node_title, node.nid AS nid
FROM node
LEFT JOIN search_index ON node.nid = search_index.sid
WHERE node.status = '1'
AND  search_index.word = 'Astronomy'
AND sid IN (
    SELECT sid FROM `search_index` WHERE `word` = 'Australia'
)
LIMIT 0 , 30

```

Now to get it I suggest that you implement hook\_views\_query\_alter(&$view, &$query). First, call Views API :

```
/**
 * Implementation of hook_views_api().
 */
function YOUR_MODULE_views_api() {
  return array(
    'api' => 3, //Views 3
    'path' => drupal_get_path('module', 'YOUR_MODULE'),
  );
}

```

And then the tricky part

```
function YOUR_MODULE_views_query_alter(&$view, &$query) {
  if($view->name == 'YOUR_VIEW' && (count($view->YOUR_EXPOSED_FIELD) > 1 ) )  {
    dpm($view); //OR dpm($query);
    //alter your query here ; you'll have to debug and tune the following lines
    //short one
    $query->where ... = ...
    //alternative one
    foreach($query->where as &$condition_group) {
      foreach($condition_group['conditions'] as &$condition) {
        //not sure from here, use `dpm ()` on your own objects
        if($condition['field'] == 'search_index.word') {
          $condition = array(
            'field' => 'search_index.sid',
            'value' => db_query('SELECT sid FROM `search_index` WHERE `word` = '.$view->YOUR_EXPOSED_FIELD),
            'operator' => 'IN',
          );
        }
      }
    }
  }
}

```

> This hook should be placed in MODULENAME.views.inc and it will be auto-loaded. MODULENAME.views.inc must be in the directory specified by the 'path' key returned by MODULENAME\_views\_api(), or the same directory as the .module file, if 'path' is unspecified.

**EDIT** : as per Vincent, used `add_where_expression` for the subquery and unset the original part of the query related to that search

```
$query->add_where_expression('3', "sid IN (SELECT sid FROM search_index WHERE search_index.word = '{$search_value}')");
//sthing like
unset($query->where[1]['conditions'][0]);

```

# Answer
> 0 votes
Apparently the Views Selective Filters module gets your "exposed filters to narrow each other down (to work as a facet search)."

# Answer
> 0 votes
I had a similar problem in another context with a custom entity. To avoid too much details I describe it with a common example: I needed to find nodes which referenced to node A AND node B. It was neccessary to get this by two exposed filters where the user was able to search for different search pairs like "show me nodes referencing to node B AND node A" or "referencing to node C and node E". The problem was the resulting query.

My solution was to use a second relationship (created in a custom module with `function MYMODULE_views_data_alter(&$data)`, getting it into the view and connecting it to the second filter. I am not quite sure if that really works in your case with the Drupal search filter but hopefully it gives you a hint in a direction of a solution

# Answer
> 0 votes
Hey You can yourself solve this by using function hook\_views\_query\_alter(&$view, &$query).

If i have to i will use it like in template.php of site theme:

```
function Yourthemename_views_query_alter(&$view, &$query)
  {
    //firstly get name by printing like print $view->name;
    //Now use condition like following
    if($view->name=='viewname')
    {
      //Now Print here $query like:-echo "<pre>"; print_r($query);
      //Their you got conditions that you have used as exposed filter in views.
      //After entering 'Australia Astronomy' in second filter checkout the condition that is printing using print_r;
      //Now Alter the condition their accoring to this.like:-

      Query->where[]='YOUR_Conditon';

    }
  }

```

You have to change condtions accoring to result you want.You have to try it yourself.we will solve it if we have you have provided exported view code.

---
Tags: views
---


title: Accessing unpublished group content

text:
# Question
Title: Accessing unpublished group content
I am using organic groups and I want the owner/reviewer of the group to be able to access an unpublished group content created by members of the group.

I know I can give "View any unpublished content" rights to a global user role, but this will be to strong (I have different reviewers for different groups and single reviewer should not have access to unpublished content of all the groups).

I want to give that right to the specific role in the group and "Organic groups global permissions" simply does not have that option.

I am familiar with hooks system but I am not sure how to approach the issue. Any ideas?

# Answer
Have a look at this example implementation which creates a new OG Permission **View unpublished content** and uses Node Grants to decide who can view unpublished nodes. You now can configure which OG Role in your groups are allowed to view unpublished nodes.

```
<?php
define('MY_MODULE_REALM_VIEW_UNPUBLISHED', 'my_module_view_unpublished');

/**
 * Implements hook_og_permission().
 */
function my_module_og_permission() {
  // Add OG permission to view unpublished nodes.
  return array(
    'view unpublished' => array(
      'title' => t('View unpublished content'),
      'description' => t("Allow user to see unpublished content within the group."),
      // Determine to which roles the permissions will be enabled by default.
      'default role' => array(OG_ADMINISTRATOR_ROLE),
    ),
  );
}

/**
 * Implements hook_node_grants().
 */
function my_module_node_grants($account, $op) {
  if ($op != 'view') {
    return;
  }

  $grants = array();

  // Handle access to unpublished nodes.
  // Get all OG Group IDs the user is allowed to view unpublished nodes in.
  $entities = og_get_entity_groups();
  foreach ($entities['node'] as $entity_id) {
    if (og_user_access('node', $entity_id, 'view unpublished')) {
      $grants[MY_MODULE_REALM_VIEW_UNPUBLISHED][] = $entity_id;
    }
  }

  return $grants;
}

/**
 * Implements hook_node_access_records().
 */
function my_module_node_access_records($node) {
  // Node is unpublished and belongs to a OG group.
  if (!(empty($node->status) && $groups = og_get_entity_groups('node', $node))) {
    return array();
  }

  foreach ($groups['node'] as $nid) {
    $grants[] = array(
      'realm' => MY_MODULE_REALM_VIEW_UNPUBLISHED,
      'gid' => $nid,
      'grant_view' => 1,
      'grant_update' => 0,
      'grant_delete' => 0,
      'priority' => 10,
    );
  }
  return $grants;
}

```
> 3 votes

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