title: Pass info from page link to form

text:
# Question
Title: Pass info from page link to form
I am trying to build a custom module that uses a theme page to display a list of items withing a table. Each item has a unique ID. and I would like to have links within this table so that my users can preform actions using the uid. The link works and takes you to the form but it doesn't carry over the uid.

Here is the code from my theme file.

```
<?php

/**
 * @file
 * definition of uc-bitcoin-account-outgoing-escrows.tpl.php.
 */
$user = user_load($variables['uid']);

global $base_url;

$transactions = db_query("SELECT * FROM {uc_btc_escrow_payment} WHERE from_account='$user->uid'");

$header = array(t('Escrow ID'), t('Amount'), t('Payment'), t('Allocated to'), t('Release'), t('Dispiute'), t('Date'));

$rows = array();

foreach ($transactions as $transaction) {
  $rows[] = array(
      $transaction->escrow_id, $transaction->amount, $transaction->status , $transaction->to_user, '<a href="' . $base_url . '/user/orders/release-escrow/' . $transaction->escrow_id . '">Release Payment</a>', '<a href="' . $base_url . '/user/funds/dispute-escrow/' . $transaction->escrow_id . '">Dispute Payment</a>', date('d/m/Y   g:i:s A', $transaction->created)
  );
}

print t('<h2>Outgoing Escrows</h2>');

print theme('table', array('header' => $header, 'rows' => $rows));
?>

```

When the user clicks on the Release Payment link it will take them to the form I created but it has a few errors. And Doesn't work. Here is the code for that function.

```
function uc_escrow_release_payment($form, &$form_state, $escrow_id) {

  $form['#$escrow_id'] = $escrow_id;

  $transaction = db_query("SELECT * FROM {uc_btc_escrow_payment} WHERE escrow_id= :escrow_id", array(':escrow_id' => $escrow_id))->fetchAssoc();

  $user = user_load($transaction['reference']);
  $to_user = $transaction->to_user;
  return confirm_form($form, check_plain('Release Escrow Payment?'), 'user/orders', check_plain('Are you sure you want to release this payment and send the funds to ' . $to_user . '?'), check_plain('Yes'));
}

```

The errors I am getting are because the information isn't getting passed from one page to the other.

```
Notice: Undefined index: reference in uc_escrow_release_payment()
Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load()
Notice: Trying to get property of non-object in uc_escrow_release_payment()

```

I think I am missing something small. Thank you for the help.

# Answer
I thought it easier if I just mark up the code a bit, I've tried to notate where I made changes. Can you run this and tell us what it does, if it doesn't solve your problem?

```
<?php

  /**
   * @file
   * definition of uc-bitcoin-account-outgoing-escrows.tpl.php.
   */

  /** clr use $account instead of $user in case global $user is already in scope **/
  $account = user_load($variables['uid']);
  /* also, loading the user seems extraneous if you're not checking
   * anything else (is user valid, is user in a certain role, etc.)
   * if so, you should include an additional check.  If not, just
   *  do your query using $variables['uid']
   */
  global $base_url;

  /** clr drupalized the query **/
  $transactions = db_query("SELECT * FROM {uc_btc_escrow_payment} WHERE from_account=:user_id", array(':user_id' => $account->uid));

  $header = array(t('Escrow ID'), t('Amount'), t('Payment'), t('Allocated to'), t('Release'), t('Dispiute'), t('Date'));

  $rows = array();

  /** clr adding a check here **/
  if (!$transactions) {
    die('No Transactions were found');
  }
  /** clr clean up the anchor tags **/
  foreach ($transactions as $transaction) {
    $release_href = $base_url . '/user/orders/release-escrow/' . $transaction->escrow_id;
    $dispute_href = $base_url . '/user/funds/dispute-escrow/' . $transaction->escrow_id;
  $rows[] = array(
    $transaction->escrow_id,
    $transaction->amount, $transaction->status , $transaction->to_user,
    l('Release Payment', $release_href),
    l('Dispute Payment', $dispute_href),
    date('d/m/Y   g:i:s A', $transaction->created)
  );
}

print t('<h2>Outgoing Escrows</h2>');

print theme('table', array('header' => $header, 'rows' => $rows));
?>

```

And then your function:

```
function uc_escrow_release_payment($form, &$form_state, $escrow_id) {

/** check $escrow_id **/
if (!$escrow_id || $escrow_id == '') {
  die('Do something here, because you don\'t have everything you need');
}

/** clr not sure why '$' is used in $form key? */
$form['#$escrow_id'] = $escrow_id;

/** clr changed to fetch object **/
$transaction = db_query("SELECT * FROM {uc_btc_escrow_payment} WHERE escrow_id=:escrow_id", array(':escrow_id' => $escrow_id))->fetchObject();
/** check transaction **/
if (!$transaction) {
  die('No transaction was found; In ' . __FUNCTION__);
}
/** clr don't use $user for same reason above **/
$account = user_load($transaction->reference);
$to_user = $transaction->to_user;
/** check_plain() is only necessary when you're dealing with user supplied text.
 *  that being said, I guess it never hurt to be over cautios */
return confirm_form($form, check_plain('Release Escrow Payment?'), 'user/orders', check_plain('Are you sure you want to release this payment and send the funds to ' . $to_user . '?'), check_plain('Yes'));
}

```
> 0 votes

# Answer
Thank you Chris Rockwell for that valuable information. Unfortunately when I tried to process the form the escrow\_id didn't carry over. So I decided to keep the code you gave me and use session variables to make it the rest of the way.

```
function uc_escrow_release_payment($form, &$form_state, $escrow_id) {
global $user;
if (!$escrow_id || $escrow_id == '') {
  die('Do something here, because you don\'t have everything you need');
}
$form['#$escrow_id'] = $escrow_id;
$transaction = db_query("SELECT * FROM {uc_btc_escrow_payment} WHERE from_account=$user->uid AND escrow_id=:escrow_id", array(':escrow_id' => $escrow_id))->fetchObject();
if (!$transaction) {
  die('We did not find that transaction or you are not the buyer from that transaction!');
}
  $_SESSION['escrow']['#$escrow_id'] = $escrow_id;
  $form = array();
  $form['escrow-message'] = array(
  '#markup' => t('<p><strong>Are You Sure?</strong></p><p>This will release ' . $transaction->amount . ' of bitcoins to ' . $transaction->to_user . '?<p></p>'),
  );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Yes'),
        '#submit' => array('uc_bitcoin_escrow_release_payment_submit'),
    );

  $form['cancel'] = array(
    '#type' => 'submit',
    '#value' => t('No'),
    '#submit' => array('ubercart_escrow_get_user_escrow_payments'),
  );
  return $form;

```

This allowed me to call escrow\_id in the form submit section.

```
function uc_bitcoin_escrow_release_payment_submit($form, &$form_state) {
global $user;
$escrow_id = $_SESSION['escrow']['#$escrow_id'];
if (!$escrow_id || $escrow_id == '') {
  die('Do something here, because you don\'t have everything you need');
}

/** clr not sure why '$' is used in $form key? */
$form['#$escrow_id'] = $escrow_id;

/** clr changed to fetch object **/
$transaction = db_query("SELECT * FROM {uc_btc_escrow_payment} WHERE from_account=$user->uid AND escrow_id=:escrow_id", array(':escrow_id' => $escrow_id))->fetchObject();
/** check transaction **/
if (!$transaction) {
  die('We did not find that transaction or you are not the buyer from that transaction!');
}

```

Thank You once again for your help
> 0 votes

---
Tags: forms, database, datetime
---


# Question
Title: How to Apply Panelizer on already created nodes of a particular node type?
I've got a content type Article with created nodes of that content type

Then I decided I want to use Panelizer, but i discovered I have to manually modify each node to apply panelizer

*-I enabled the "Node template" display in the Pages admin (admin/structure/pages). \- I have tried Display Suite, but I want to use Panelizer*

Its like the node will have its own Panelizer isolated from global Panelizer settings.

# Answer
The module's lead maintainer, merlinofchaos, responded to this on drupal.org; in short, it's only possible if using the IPE, there's an option to make the changes global i.e. affect the default configuration, otherwise the changes have to be made via the entity's Panelizer tab, e.g. admin/structure/types/page/panelizer.
> 1 votes

---
Tags: panels
---


title: Drupal 7 multisite setup white screen

text:
# Question
Title: Drupal 7 multisite setup white screen
I have attempted to set up a Drupal 7 multi site set-up. I followed the instructions online and have one site (site1) that is setup like a regular single install Drupal site and a second site (site2) set up in the sites/sites2 directory. The sites use separate databases.

The issue I am having is that while site1 displays and operates normally, site2 only displays a white screen. When I executed the install.php script for site2, everything seemed to go normally until I actually try to view the site. Any ideas as to what the issue could be? I am sure that settings.php file in both installations is set up correctly so I am a bit lost.

Thanks.

# Answer
It is impossible to tell you exactly what is wrong with the information that is given. I run several multi-sites using separate databases, and they work as advertised when I set them up following the standard instructions.

The White Screen of Death is usually caused by some error in the PHP. To see the error message, you need to turn on PHP error reporting. To do this, add the following to the `settings.php`, just below the initial `<?php`:

```
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```

This will usually show an error message that tells you where you've left out a semicolon or some other trivial PHP-error.

See also: https://drupal.org/node/1056468 and https://drupal.org/node/158043
> 2 votes

---
Tags: 7, multi-sites, debugging, wsod
---


# Question
Title: In a Views template, how can I mimic the effect of "Link this field to its taxonomy term page"?
I have a view of taxonomy terms that displays **Fields**, including **Taxonomy term: name** and **Taxonomy term: Term ID**.

I am attempting to use a views template to customize the output of this view.

In the Views UI, if I click **Taxonomy term: name**, I can get an option to *Link this field to its taxonomy term page*.

I would like to use the link generated by this option in my views template output.

However, when I `dpm($row)`, only the term name and term ID are returned. How does Views create the link to the taxonomy term, and how can I mimic this in my template file?

# Answer
One easy-ish way to do that within the Views UI is with the option:

"Rewrite the output of this field"

1. Add term id field Check "Exclude from display"
2. Order the field so it's above the other fields
3. Edit the field you want to convert into a link
4. Check "Rewrite the output of this field"

e.g

```
<a href="/taxonomy/term/[tid]">[name]</a>

```

to create a link.

You can also add a global "Custom text" to add arbitrary text using the replacement tokens there as well.

In that way, tokens from your view fields can be made available as replacement pattern options in your View.
> 2 votes

---
Tags: views, theming
---


# Question
Title: Creating Select Fields in a module with Drupal 7
I am trying to write my own module to add a content type with the help of node\_example and this page. I made small tweaks and got it to work, yet I cannot find any example to create a select box as a field, and I failed in my each attempt. I have also checked the official documentation for field\_create\_field, still no clues.

Is there any documentation or sample you can guide me?

# Answer
Something like this should work:

```
// Create field definition
$field = field_info_field('field_my_select_field');
if (empty($field)) {
  $field = array(
    'active' => '1',
    'cardinality' => '1',
    'deleted' => '0',
    'entity_types' => array(),
    'field_name' => 'field_my_select_field',
    'foreign keys' => array(),
    'indexes' => array(
      'value' => array(
        0 => 'value',
      ),
    ),
    'module' => 'list',
    'settings' => array(
      'allowed_values' => array(
        'Yes' => 'Yes',
        'No' => 'No',
      ),
      'allowed_values_function' => '',
    ),
    'translatable' => '0',
    'type' => 'list_text',
  );

  $field = field_create_field($field);
  drupal_set_message('Created field_my_select_field');
}

// Create field instance on entity bundle
if(!field_info_instance('node', 'field_my_select_field', 'my_node_type')){
  $instance = array(
    'bundle' => 'terms',
    'default_value' => array(
      0 => array(
        'value' => 'Yes',
      ),
    ),
    'deleted' => '0',
    'description' => '',
    'display' => array(
      'default' => array(
        'label' => 'hidden',
        'module' => 'list',
        'settings' => array(),
        'type' => 'hidden',
        'weight' => '4',
      ),
    ),
    'entity_type' => 'node',
    'field_name' => 'field_my_select_field',
    'label' => 'My field label',
    'required' => 0,
    'settings' => array(),
    'widget' => array(
      'active' => 1,
      'module' => 'options',
      'settings' => array(),
      'type' => 'options_select',
      'weight' => '3',
    ),
  );
  field_create_instance($instance);
  drupal_set_message("Added field_my_select_field field to node");
}

```
> 2 votes

---
Tags: entities
---


# Question
Title: Create an autopath or a token using entity reference of entity reference
I have created a new node type "station". This node type has an entity reference to another node type "location", which in turn has an entity reference to a node type "prefecture".

I would be interested to have an autopath for the station, which would be of the form http://www.website.com/\[prefecture:name\]/\[station:name\]

The problem is that prefecture:name does not appear in the tokens for node 'station'. Any idea how to go further with this?

# Answer
Ok, that was easy. One has to enable the Entity Token module, which creates automatically nested tokens for all depths of entity references.
> 0 votes

---
Tags: entities, tokens
---


# Question
Title: Add Taxonomy Term automatically based on term from user's account
I have a vocab called "state of residence" with states in the form of TN, MS, AL, etc. Each user account has one of these references to show the state of residence. I can also place this taxonomy field on a forum post. But how can I make the post pull the "state of residence" term from the account of the user who has created it? I don't want the user to have to choose. I want the choice to be made automatically based on the user's account.

Or is there a better way than a vocab. Basically, I am trying to allow content to be sorted by the geography of the user who created the post. and I don't want the user to have to make the choice.

# Answer
> 2 votes
This sort of thing is generally handled through contextual filters in your view. Views, Panels and Page Manager work well together to manage passing contextual filters to a view for filtered output, but there is a bit of a learning curve involved.

I'm not generally one for video tutorials, but I found this one to be a good introduction to this methodology: http://drupalize.me/videos/overview-page-manager-series

If you want a quick-and-dirty way to achieve this, use the module views\_field\_view https://drupal.org/project/views\_field\_view and do something like this:

* in your forum posting view, set a contextual filter on your state term reference field tid
* create a new view based on users, and add a contextual filter on "User: Uid"
* on the contextual filter configuration page, under "when the filter value is not available" select "provide default value"
* under type, select user id from logged in user
* add a field for the state term reference field tid
* add a field Global:View ( provided by the views\_field\_view module ), with these settings:
* View: your forum postings view, as modified with contextual filter above
* Display: Master
* Contextual filter: \[tid\]

This should now display all forum postings whose state of residence matches the currently logged in user's state of residence.

note that if you are on a page URL that points to a profile of a different user, and you've set it up so the view is visible on this page, it will show all postings for THAT user, as the view will be able to grab a uid from the URL. ... so ... that may be a benefit or a drawback, depending on your intent.

Best'o'luck

disclaimer: written on short sleep. hope i got all the i's dotted and t's crossed

---
Tags: taxonomy-terms, location
---


# Question
Title: How to enable Node editing in full mode?
Is there a way to expose selected node fields so that they are directly editable when the node is being viewed?

I want visitors of my site to be able to type some context into a text area, select relevant taxonomy terms etc. In other words, to do what you would normally be able to do in node-edit mode.
My node is also a Commerce product display. I need the users to input their data, also select their relevant product information and submit all on the same page.

I installed the Edit module, but I couldn't find how to expose the fields for editing.

How can I achieve what I am trying to do?

# Answer
> 5 votes
Yes there is a module which can enable this functionality - Editablefields.

Module page says itself --

> This module allows CCK fields to be edited on a node's display (e.g. at node/123), not just on the node edit pages (e.g. node/123/edit). It also works within views etc. Anywhere a 'formatter' can be selected, you can select editable (or click to edit).

I have used this module for edit fields at views not at node, but I am sure you can achieve your requirement.

---
Tags: nodes
---


title: Add Dynamic Wrapper div to a Row

text:
# Question
Title: Add Dynamic Wrapper div to a Row
I have buttons below a slideshow I have created. I want them to be centered whether there be 1, 2, etc. I'm looking to have a wrapper div surrounding them with a class name of "button-count-x" (x being number of buttons). I've tried using a 'foreach' loop and counting the number of $row's, but that is not working.

Note: I am using the "Views Slideshow" module and am using the view's respective 'views-view.tpl.php' file.

```
<?php $count = 0; ?>

<?php foreach ($fields as $id => $field): ?>
<?php if (!empty($field->separator)): ?>
<?php $count ++; ?>
<?php print $field->separator; ?>

```

```
<div class = "test"><?php print $count; ?></div>

<?php print $field->wrapper_prefix; ?>
<?php print $field->label_html; ?>
<?php print $field->content; ?>
<?php print $field->wrapper_suffix; ?>
<?php endforeach; ?>

```

# Answer
> 0 votes
that's not much to go on, so I'll assume that the module generates one button per slide in the slideshow, and you want them centered underneath the image area ?

It's hard to know without the markup, but a couple of css selectors should do the trick.

for the containing div, if it has an id, or a uniquely addressable class, try something like this:

```
#container {
    width: 100%;
    text-align: center;
}

```

and if the button divs or whatever have no convenient id or class, address them something like this:

```
#container > div {
    display: inline-block;
}

```

I think you may be better off sticking to css. Post the relevant rendered html, and perhaps we can help.

---
Tags: theming
---


# Question
Title: Creating a Batch with multiple functions
i'm trying to optimise my setup of a Drupal Batch process.

I am reading in thousands of rows of data from an Excel spreadsheet, from multiple worksheets, and creating nodes from the Rows. My import functions work fine, and I can create a Batch, but at present I am creating a batch operation for each row. This means that my batch is very slow (because I'm having to bootstrap Drupal on every row).

What I can't seem to figure out is a way to setup my batch to deal with 'chunks' rather than individual rows.

An example of my import function (of which there are 18) is:

```
function governbim_coordinate($value){
    module_load_include('inc','phpexcel');
    global $user;
    $project = $_SESSION['governbim']['projnid'];
//Load the required worksheet from the excel file passed to the function as $value
    $result = phpexcel_import($value,TRUE,TRUE,array('setLoadSheetsOnly' => array('Coordinate')));
//Define some common values for our entity
    $values = array(
            'type' => 'coordinate',
            'uid' => $user->uid,
            'status' => 1,
            'comment' => 0,
            'promote' => 0,
            );
//step through each row in the worksheet
    foreach($result['Coordinate'] as $coordinate){
        $title = $coordinate['Name'];
//check to see if this is a new row or if we are updating an existing entity
        $action = governbim_node_actions_node_check('assembly',$title);
        switch($action['op']){
            case 'new':
                $e = entity_create('node',$values);
                $entity = entity_metadata_wrapper('node',$e);
                break;
            case 'update':
                 $e = entity_create('node',$values);
                   $entity = entity_metadata_wrapper('node',$action['nid']);
                break;
        }
//*** Here is where we write everything to the database with the entity values and $entity->save() ****/
    }
}

```

My batch is setup (currently) as:

```
function governbim_excel_import_batch(){
    drupal_set_message("Importing Data...");
    $path = 'public://imports/';
    $file = 'COBie-UK-2012-example1.xls';
    $datafile = $path.$file;

       $operations[]=array('governbim_coordinate',array($datafile));

        //another 17 $operations[] defined as above

    $batch = array(
        'operations' => $operations,
        'init_message' => t('Constructing batch operation...'),
        'progress_message' => t('Importing Excel data'),
        'finished' => 'governbim_excel_import_batch_finished',
        'error_message' => t('Importing of Excel data encountered an error.'),
        );
    return $batch;
}

```

I realise I need to get some $context stuff into the import function, but I can't seem to figure out how to setup that aspect properly.

Is anyone able to assist me in re-tuning things so that I can get the batch (with 18 function calls) to display progress of the overall batch and get the batch to execute (say) groups of iterations (as in $limit = 10)?

# Answer
I do one batch operation but with multiple entry.

```
/**
 * Batch start function.
 */
function mymodule_batch_start() {
  $batch = array(
    'title' => t('Importing Excel data'),
    'operations' => array(
      array('_mymodule_import', array()),
    ),
    'progress_message' => t('Importing Excel data. Operation @current out of @total.'),
    'error_message' => t('Error!'),
    'finished' => 'mymodule_batch_finished',
  );
  // Run batch in background
  batch_set($batch);

```

Here is the pattern fot the operation:

```
/**
 * Import operation.
 */

function _mymodule_import(&$context) {

  // Get your import data with some custom function.
  $import_data = _mymodule_get_import_data($context);

  // Get Count of items
  if (empty($context['sandbox']['progress'])) {
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['max'] = count($import_data);
    $context['results']['total_count'] = $context['sandbox']['max'];
  }
  // Create Iteration variable
  if (empty($context['sandbox']['iteration'])) {
    $context['sandbox']['iteration'] = 0;
  }

  // Check for the end of cycle
  if ($context['sandbox']['iteration'] < $context['sandbox']['max']) {

    // Count of operation in one butch step
    $limit = 10;
    // Counts completed operations in one butch step
    $counter = 0;
    if ($context['sandbox']['progress'] != 0) {
      $context['sandbox']['iteration'] = $context['sandbox']['iteration'] + $limit;
    }

    // Main loop of all import items
    for ($i = $context['sandbox']['iteration']; $i < $context['sandbox']['max'] && $counter < $limit; $i++) {

      // Do smth custom here with import data item $import_data[$i].
      _mymodule_handle_import_item($import_data[$i]);

      // Update Progress
      $context['sandbox']['progress']++;
      $counter++;
      // Messages
      $context['message'] = t('Item %progress of %count', array(
        '%progress' => $context['sandbox']['progress'],
        '%count' => $context['sandbox']['max'],
      ));
      $context['results']['processed'] = $context['sandbox']['progress'];
    }
  }

  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  }
}

```

P.S. Sometines I need to import data and then remove some old data. You can store some results of 1st operation in `$context` and then use it in other operation. I can do import in one batch with two operations:

```
'operations' => array(
  array('_mymodule_import', array()),
  array('_mymodule_remove_data_after_import', array()),
),

```
> 0 votes

---
Tags: batch-operations
---


# Question
Title: How to properly alter response from Solr Search Module
I'm working on `Drupal Version 7.22` and I'm trying to modify the results coming from Solr using the hook provided by the Solr Search Module.

The specific hook can be found here: http://drupalcontrib.org/api/drupal/contributions!search\_api\_solr!search\_api\_solr.api.php/function/hook\_search\_api\_solr\_search\_results\_alter/7

Here's how I implemented it from the module:

```
/**
 * Implements hook_search_api_solr_search_results_alter().
 */
function zen_search_api_solr_search_results_alter(array &$results, SearchApiQueryInterface $query, Apache_Solr_Response $response){

  $locations = array();

  $rest = $results['results'];
  foreach($rest as $r){

    $place = $r['fields']['field_business_name'];
    $postal_code =  urlencode($r['fields']['field_business_address:postal_code']);

    $api = 'http://maps.googleapis.com/maps/api/geocode/json?address=' .  $postal_code . '&sensor=false';
    $api_results = file_get_contents($api);
        $data = json_decode($api_results, true);

        if($data['status'] == 'OK'){
            $location = $data['results'][0]['geometry']['location'];

            $locations[] = array(
                'place' => $place,
                'lat' => $location['lat'],
                'lng' => $location['lng']
            );
        }

  }

    $data = array('zen' => array('locations' => $locations));
    drupal_add_js($data, 'setting');

}

```

So basically what I'm trying to do here is to add the coordinates that I get from the Google maps Geo-coding API using `drupal_add_js`.

But I'm getting the following error:

> Recoverable fatal error: Argument 3 passed to zen\_search\_api\_solr\_search\_results\_alter() must be an instance of Apache\_Solr\_Response, instance of stdClass given

Any ideas what's wrong here?

# Answer
The problem was this one:

```
function zen_search_api_solr_search_results_alter(array &$results, SearchApiQueryInterface $query, Apache_Solr_Response $response){
  ...
}

```

It should be this:

```
function zen_search_api_solr_search_results_alter(&$results, $query, $response){
  ...
}

```
> 3 votes

---
Tags: 7, search
---


# Question
Title: is Form api ajax attribute good in performance ? does it require an entire bootsrap?
Ajax is used for better user experience and also for better performance in a webapp ( change only the requested item instead of the entire page ).

In my case the form will require ajax functionality, interacting live with the Product Configuration Soap Service. The performance of this form will be important due to the fact that many users may be accessing it simultaneously.

But how #ajax works in Drupal ? Does It require an entire bootsrap ? If so, will drupal be a good solution in my case ?

# Answer
Whether or not the request method is AJAX has no bearing on whether a full bootstrap is performed - that's completely down to the behaviour of the *path* that's being requested. If your AJAX call requests '/js/my-page.js', and that menu path is somehow configured not to bootstrap fully, then you won't incur a bootstrap penalty.

To that end, I would highly recommend installing the High-performance JavaScript callback handler module.

> JavaScript callback handler is an interim solution for high-performance server requests including (but not limited to) AHAH, AJAX, JSON, XML, etc.
>
> This project targets module developers and provides a "bare bone" callback handler which is intended to be addressed by modules wanting to improve response times for specialized tasks.

It will allow you to define router items for which a full bootstrap will not run; in fact you can pick exactly which modules should be loaded, and which other files should be included, for your callback's requirements.

I've used it before with great success, and have seen very noticeable improvements when converting custom (and even core) AJAX callbacks to use this method. It's blindingly fast.

It also has integration with a bunch of other modules (SHS for example).

As to whether Drupal will be able to handle your project - that's not for us to say; have a look at the various options available (including this one), do some benchmarking and stress testing per your project/client-established requirements, and it'll become apparent whether or not Drupal will meet your needs.
> 3 votes

# Answer
Drupal AJAX calls require Drupal to be bootstrapped all right. You can access anything there is in Drupal when processing calls, so everything needs to be ready.

Basically, Drupal recreates form from scratch, using values provided, and then sends differences to browser. That way you may modify anything about your form to reflect user's actions.

It means AJAX call will not be significantly faster than normal page reload, except the far less amount of data transferred.

As always, custom solution tailored to your use case and gelded from everything you don't need will work faster. As always, developing, debugging and maintaining it will be more expensive.
> 1 votes

---
Tags: 7, forms, ajax
---


# Question
Title: Execute a file in the body of a specific content type
How to load the file, which contains css, javascript and html, in the body of a specific content type?

# Answer
Looks like you are looking for Code per Node module:

> Code per Node makes it possible to add custom CSS and Javascript per node, per content type, per block, and globally. The code is stored in the database, but served from the file system.
> 1 votes

# Answer
Insert is a utility that makes inserting images and links to files into text areas or WYSIWYGs much easier. It adds a simple JavaScript-based button to FileField and ImageField widgets.

You can insert files inserted into text areas with a specific Content type Option.
> 0 votes

---
Tags: javascript, theming, nodes
---


# Question
Title: Get information from a node that has just been saved to update a different node
I have 2 different content types "factory" and "measurement" that are related with an entity reference field. I am using a computed field to store the latest measurement as a field of the factory content type. The problem is that in order for the computed field to be "re-computed", the factory node that the measurement refers to, needs to be updated.

My first thought was to batch update all the factory nodes in predefined intervals. This has a very important downside: the factory information (and specifically the latest measurement that I'm interested in) will not be updated until the batch update is executed.

My next thought was that I could use a hook whenever a new measurement is created and update the corresponding (=the one that the entity reference points to) factory. The problem is that hook\_node\_insert will not give me the information that I want (i.e. the entity reference field that points to the factory) since in the hook's description it states clearly that:

> You should not rely on data in the database at this time as it is not updated yet.

Is there any other way to execute a piece of code whenever a new node of specific type (i.e. measurement) is saved/created and **have the node's fields available** in my code? How do Rules do it?

P.S: I thought about using Rules but it seems like an overkill for such a simple thing to install a pretty heavy module.

# Answer
> 1 votes
In `hook_node_insert($node)` you cannot reliably read saved node's data from database, but you can read data from `$node` object provided to that hook.

---
Tags: 7, nodes
---


# Question
Title: How can i find out when the next cron will run?
How can i find out programmatically when the next cron will run in order to present it to the author scheduling stuff?

i am using ultimate cron and an external cron process.

# Answer
> 3 votes
Basically, you cannot.

If you are using Drupal 7 built-in CRON triggering method, in Drupal 6 Poormanscron module, CRON run depends on the availability of visitor. If no one visits your page, CRON will not run. Drupal can't predict if or when visitor will appear, so the best you can know is when CRON will **not yet** run anyway, even if visitor is available.

If you are using external tools, Drupal has no way to predict if and how they will trigger it. It will accept all proper request, so you know even less than in the first case. Even if you know when it is supposed to run, you don't know time difference between servers, as it is subject to change slightly. You don't know the lag between a moment when CRON should happen and when it will, as practically no web servers are hosted on real time operating systems, so there are no guarantees about maximum time between action request and it's execution. In simpler words, server can postpone CRON task if it's to loaded, sometimes even skip it.

If you need predictable and reliable cron, go to http://example.com/admin/config/system/cron, find URL described as "To run cron from outside the site, go to". Then, mail your server administrator and ask him to add this to server's crontab:

```
*/5 * * * * wget -O - -q -t 1 http://www.example.com/cron.php?cron_key=yourcronkeyrandomstring

```

This will make your site's CRON run every 5 minutes, and you shouldn't need to know when exactly - it's ofthen enough for most tasks. If it's not, make it `*/2` to run it every 2 minutes, or just leave `*` at every position to get it triggered each and every minute. You can read more about system's CRON configuration on Wikipedia. Of course it will not allow Drupal to know, it will just free you from the need to know.

# Answer
> 3 votes
The easiest method here (though by no means a good, reliable one) is to set up the cron job to run at a known time (let's say hourly, on the hour) and then take that knowledge back to Drupal where you can do something low-tech like

```
$minutes_left_until_next_cron = 60 - date('i', REQUEST_TIME);

```

Of course this relies on things like the web server and external cron servers' system times being synced correctly, and isn't really an elegant solution. But, it'll do in a pinch.

---
Tags: 7, cron
---


title: Views3 and subqueries?

text:
# Question
Title: Views3 and subqueries?
I've got a view which generates a query that does multiple joins. This produces a cartesian join, and I need to "convert" the joins to subqueries.

I've looked through documentation, Google search results and other sources, but I am unable to find any decent description of how I can configure Views to do subqueries. I've used hook\_views\_data() to configure the relationships (which are now carried out as joins). Is it somehow possible to define subqueries through hook\_views\_data(), or do I need to take another approach?

Any advise appreciated!

# Answer
> 5 votes
I looked further, but could not really find any documentation describing this.

What I needed was a way to join the users table with two other tables holding data for the users. However, the two other tables are in a 'one-to-many' relationship with the users table, meaning that I'll end up with a Cartesian join if I attempt to join the users table with both of these tables at the same time. However, since all I need is to count the number of records in the two other tables associated with any given user, a subquery should be able to do the trick. However, I couldn't find any documentation on Views and subqueries - so here is what I did.

1. Created two dummy fields

I created two dummy fields (which I'll call 'downloads' and 'listens') through hook\_views\_data(). The definition of the field are listed below.

```
function hook_views_data() {

  $data['users'] = array(
    'downloads' => array(
      'title' => t('Downloads'),
      'field' => array(
        'handler' => 'views_handler_field_numeric',
        'click sortable' => TRUE,
      ),
      'filter' => array(
        'handler' => 'views_handler_filter_numeric',
      ),
      'sort' => array(
        'handler' => 'views_handler_sort',
      ),
    ),
    'listens' => array(
      'title' => t('Listens'),
      'field' => array(
        'handler' => 'views_handler_field_numeric',
        'click sortable' => TRUE,
      ),
      'filter' => array(
        'handler' => 'views_handler_filter_numeric',
      ),
      'sort' => array(
        'handler' => 'views_handler_sort',
      ),
    )
  ),
);

```

Now, when you configure a view for users, the fields 'Downloads' and 'Listens' will appear. However, attempting to run a query now will result in an error as the dummy fields after all are dummy fields. They do not exist. The only purpose of these fields is to signal to to our implementation of hook\_views\_query\_alter() that it needs to do a few replacemenets.

1. Implement hook\_views\_query\_alter()

The trick here is to check wether the given query includes the 'Downloads' or 'Listens' fields. If it does, we'll remove the fields from the query and replace them with subqueries. The implementation of this function goes as below.

```
function mta_views_query_alter(&$view, &$query) {

  foreach ($query->fields as $field_key => &$field_values) {
    if ($field_values['table'] == 'users') {

      switch ($field_values['field']) {
        case 'downloads':
          unset($query->fields[$field_key]);
          $query->add_field(null, "(SELECT COUNT(*) FROM {fileusage} fu WHERE fu.externaluser = {users}.uid AND fu.action = 0)", $field_key);
          break;
        case 'listens':
          unset($query->fields[$field_key]);
          $query->add_field(null, "(SELECT COUNT(*) FROM {fileusage} fu WHERE fu.externaluser = {users}.uid AND fu.action = 1)", $field_key);
          break;
      }
    }
  }
}

```

Note that we're reusing the alias of the removed field for the subquery. That way, Views will think that the value returned from the subquery actually comes from the dummy field (which after all does not exist).

That's is. We're not getting a Cartesian join and both 'downloads' and 'listens' are counted correctly.

# Answer
> 4 votes
I used sbrattla's solution until I needed to have the subquery inherit filter values. I now use the views\_field\_view module to embed a separate view that performs the count query. I can pass context filter values to that embedded view via the views\_filterfield module (which I wrote) that makes filter values available as view fields (and thus tokens).

The count query now works and inherits the exposed filters on the main query.

---
Tags: views, database
---


# Question
Title: og membership role is not displayed in views
I'm using organic group module and I have 3 og membership types:

* 'member'
* 'non-member'
* 'visitor'.

I created an view which shows me all user group listing under one group which includes users role also but it is not displayed.

In view I added an Relationships as 'OG membership: OG membership from User ' and added filed for the same.

# Answer
To work with user-roles in a view, you also need the relationship "OG membership: OG Roles from membership", where you have to set the relationship to your previously added "OG membership from user"-relation.

After that you are able to display the user's role or filter by user-roles. Hopefully this information was helpful for you.
> 2 votes

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


# Question
Title: D7 : Upload to a folder outside of "files" folder?
Specifically outside of the Drupal installation folder...

I have a folder in my WWW folder that I'd like place files into through Drupal. However, it looks like, by default Drupal prefers to only upload into the "files" folder.

Has anyone encountered something like this?

I have tried making a custom upload field point to "/var/www/uploads" and the FilePath module, but neither work.

Any suggestions. Is this a case of creating a custom module that points to that folder? If anyone has come across a tutorial regarding custom upload paths that would be awesome.

Thanks for any help.

# Answer
It is impossible by design, for security reasons. Imagine your users being able to overwrite your `/etc/password` or `apache.conf` \- horror.

If you need outside storage, you need to use operating system methods, like:

* hard links
* symbolic links
* `mount -o bind`
* junctions
* and probably many other
> 1 votes

---
Tags: entities, files
---


# Question
Title: Email filter in default admin users/people search form
I would like an additional filter (email-text input) in the drupal7 default admin users/people search form. Is there any module as I can't find one for drupal7? I found that another way is the use of views but I want the default search form with additional input filter.

# Answer
Looks like this module achieve what you need.
> 0 votes

---
Tags: 7, users, search, forms, emails
---


# Question
Title: How to use views hooks - specifically hook_view_data()?
I am looking for details on the api to define my own view data, such as what values I can provide for the table I am defining, what values are available for the fields etc.

I have found a tutorial that gives me the basic info, but now I need more specific info.

I have found this page

https://api.drupal.org/api/views/views.api.php/7

but when I click on the link to

```
hook_views_data

```

I go to a page with virtually no information with one link which takes me back to the listing page I started at.

Is there somewhere I can find out information about what `hook_views_data` should define?

# Answer
Views does have complete documentation for that hook, but it's not in the most obvious place.

If you install the Advanced Help module and go to http://mysite.com/help/views/api-tables you'll find the *Describing tables to Views* help page which contains extensive documentation and code samples.

You can also find the full Views' API docs at http://mysite.com/help/views/api with that module installed.

On top of that, the list of functions that implement `hook_views_data()` would also be worth a look. The aggregator, book and node module implementations look to be well commented at first glance.
> 3 votes

---
Tags: 7, views, hooks
---


# Question
Title: Is it possible to automatically create a .install file for a module?
I have a content type that I want to install as part of a module or install profile. Is there anyway to automatically create all the `field_create_field` and `field_create_instances` code that would go in `hook_install` or do I have to do all that manually?

Is there any other way to capture the settings of a content type so I can migrate it and include it in an install profile?

# Answer
> 3 votes
If it's just the field and field instances that you want converted ready for an install file (i.e. if Features is too overkill for you or you don't want the extra dependency), then Field Inspector will give you all the code you need for creating your fields in code.

> Field inspector provides an administrative user interface for the Field Info API. This allows users to select what information, formatting, and fields they would like to see, and provides output in a manner that can be copied into a module, or install profile into a hook\_install, or hook\_update\_N function.

# Answer
> 2 votes
It seems you are looking for Features module:

> The features module enables the capture and management of features in Drupal. A feature is a collection of Drupal entities which taken together satisfy a certain use-case.
>
> Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it declares its components (e.g. views, contexts, CCK fields, etc.) in its .info file so that it can be checked, updated, or reverted programmatically.

---
Tags: 7, installation
---


# Question
Title: List of template suggestion used for a node
I'm building a module that return you an HTML styled node via ajax but I have a question. I want to add a node suggestion only for this module. How?

So drupal have to check: Exist \[in active theme\] ajaxnode.tpl? And ajaxnode--nodetype.tpl? If they don't exist choice the normal drupal suggestion template and render the node.

How can i do this correctly?

# Answer
I'd go and get the Theme developer module. Simply get the element you want to theme and click on it - then you'll get a list of any template files and/or theme functions that were called in the processing of the element you clicked.

> Firebug for Drupal themeing. See the screenshot and screencast. Note that this module injects markers into the DOM to do its magic. This may cause some themes to behave erratically and less capable browsers may make it worse (especially IE)/. Enable it when needed, and disable it afterwards.
> 1 votes

---
Tags: 7, nodes, theming
---


# Question
Title: How to replace the $title of one single page with a taxonomy term?
My setting here is like this:

I have a huge Druapl site here, and there's one single page that contains a views block displaying uploaded files with their taxonomy terms in a table. Title of this page is "Uploaded files".

Clicking on of these taxonomy terms calls the URL plus an additional query `?tid=123` applying a filter for that term on the table. So now only content of taxonomy tid 123 is displayed in the table and the URL ends with `?tid=123`.

In that situation I want the title "Uploaded files" to be replaced by "Files of the taxonomy term 123", where 123 stands for the actual term connected to the tid 123. Let it be "To-Do-List".

Inside my theme's template folder I created a template file for that single page called `page--node--nid.tpl.php`, where nid stands for the actual node id of that page. I'm quite well able to manipulate the title of that page now when clicked on a term. At the place where the title is printed I can say `<?php print $_GET['tid'] ?>` and of course instead of "Uploaded files" it now prints the tid, here in my example: 123.

But how do I get the template to print the term instead of the id?

I know that there's a function called taxonomy\_term\_load to load the term connected with an id. But where would I call that function? And how do I pass maybe newly created `$taxonomy_title` into my `page--node--nid.tp.php`? Do I have to call some preprocess functions within the tags at the top of my `page--node--nid.tpl.php`?

To make matters even more difficult, there are terms from different vocabularies. In my example it sets the query to `?tid=123`, but when I click on a term from another vocabulary it sets the query to `?tid_1=234`

I came so far on my own, but do really very much appreciate a helping explanation on how and where to use that function...

# Answer
You can achievie that with contextual filters as well.

**contextual filter: Content: Has taxonomy term ID**

**When the filter value is NOT available:**

* provide default value -\> type: Taxonomy term ID from URL
* Load default filter from node page, that's good for related taxonomy blocks
* check the vocabulary which you want to use

**When the filter value IS available or a default is provided:**

Specify validation criteria -\> PHP Code

```
$term = taxonomy_term_load($argument);
drupal_set_title($term->name);
return $argument;

```

It's done!
> 2 votes

# Answer
As I see, you want to change your node title, which is comes from `page.tpl.php` not `node.tpl.php`. So you need to make separate `page.tpl.php` for your content type.

You can make custom page.tpl for your content type by copying `page.tpl.php` and naming it like - p`age--CONTENT-TYPE.tpl.php`

Then you need to workaround your `template.php` file. Follow nest steps.

You will have to get this term ID in template file at MYTHEME\_preprocess\_page() function at first. Do something like this --

```
function MYTHEME_preprocess_page(&$vars){
  if ($node = menu_get_object()){
        if($node->type == 'CONTENT_TYPE'){
            $vars['node'] = $node;

            //Get term ID or Term name, which ever is available. Yu can see the available values by doing dsm($node) here.
            //I don't have output of your $node object here, otherwise I can suggest exact.
            $term_id = $node->field_TERM_REFERENCE[LANGUAGE_NONE][0]['term_id'];

            //If you have term ID then get term name.
            $term_name = taxonomy_term_load($term_id);

            //Prepare new title.
            $final_title = "Files of the taxonomy term ".$term_name;

            //Declare the new title variable to use at page.tpl.php.
             $vars['final_title'] = $final_title ;
        }
    }
}

```

Now go to your newly created `page--CONTENT-TYPE.tpl.php` & find `$title` output in that, it would be something like --

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

```

Replace it with --

```
<?php if ($final_title) : ?>
   <h1 class="title">
        <?php print $final_title; ?>
   </h1>
<?php endif; ?>

```

You are done I guess. Clear your cache & see if it change or not. If it doesn't work then comment, but be prepare to give me output of your `$node` object by `dsm($node)`.
> 1 votes

# Answer
Thanks to all who helped (also to Matt there -\> http://mattwad.wordpress.com/2011/10/12/drupal-theming-change-a-page-title-in-template-php/).

I finally managed to do everything in the template.php's preprocess\_page function (without any extra `page-or-node.tpl.php`), though I had to dpm first inside the process\_page function to access all $vars.

```
function MYTHEMENAME_preprocess_page(&$vars) {
  if ($_GET['q'] == 'node/338' && isset($_GET['tid'])) {

      $tid_term = $_GET['tid'];
      $term = taxonomy_term_load($tid_term);
      $vars['title'] = $term->name;
    }
}

```

With `$vars['title']` I finally set the actual page title to the tid's term after I took the tid from the URL with `$_GET['tid']`
> 0 votes

---
Tags: 7, taxonomy-terms, theming
---


# Question
Title: How to relate the user table with the fboauth table to show up who's logged in through fb?
I have created a view which shows up the user details like username, email, active(user), accepted challenges in a tabular format. Now i want to include a column to it which shows up the users who uses their fb account to login to the website.I have used fboauth module to allow users to login to the website through their fb account and i am unable to add a relationship which relates the users table and the fboauth table. Can anyone suggest me a way to resolve this?

I am using drupal 7

# Answer
You have two options.

1. First is that you can add a field to the USER, named as fb\_user(Keep the default value as "no"). Now look into the fbouth code where a user is being created. Write a sql query there using Database API to update the field fb\_user as "yes". Now you can easily add the field in views to find out FB users.
2. Create a custom module. Inside that write a hooks\_views\_query\_alter:-https://api.drupal.org/api/views/views.api.php/function/hook\_views\_query\_alter/7 Custom query in Views?
> 0 votes

---
Tags: social-network
---


# Question
Title: How to move block functions into .inc file?
I have a module that is getting pretty large and I want to move the functions that define blocks into another file to better organize my module.

I did this:

1. Moved those functions ( `_block_configure`, `_block_info`, `_block_view`, etc) to `includes/blocks.inc` in my module.
2. Put `files[] = includes/blocks.inc` in my .info file

This doesn't work though - the blocks disappear when I do this. What am I doing wrong?

# Answer
The files directive is used to include files containing classes, check documentation. You could include the file in the .module file.

```
require_once __DIR__ . '/includes/blocks.inc';

```

**Edit**: Included the other solutions added by @Beebee and @Jimajamma in the answer:

```
require_once  drupal_get_path('module', 'mymodulename') . '/includes/blocks.inc';
module_load_include('inc', 'MY_MODULE', 'FILE_NAME');
// This method is including a file residing in the module folder not in a subdirectory.

```
> 6 votes

# Answer
All you need is hook\_hook\_info.

> Normally hooks do not need to be explicitly defined. However, by declaring a hook explicitly, a module may define a "group" for it. Modules that implement a hook may then place their implementation in either $module.module or in $module.$group.inc. If the hook is located in $module.$group.inc, then that file will be automatically loaded when needed. In general, hooks that are rarely invoked and/or are very large should be placed in a separate include file, while hooks that are very short or very frequently called should be left in the main module file so that they are always available.

In your case it should be,

```
/**
* Implements hook_hook_info().
*/
function mymodule_hook_info() {
  $hooks['block_info'] = array(
    'group' => 'block',
  );
  $hooks['block_configure'] = array(
    'group' => 'block',
  );
  $hooks['block_view'] = array(
    'group' => 'block',
  );
  return $hooks;
}

```

Then you should place those hook functions into a file called mymodule.block.inc and the same file should be available in the module directory.

For more info/caveats on this hook go here.
> 2 votes

---
Tags: 7, blocks
---


# Question
Title: db_delete on click on a link in module contents display
I've made a module displaying a set of fields from the database. I would like to add a "delete" link at the end of each row be able to delete the row in the database on click. I made it in my module with the following code :

The tests.module code :

```
<?php

function tests_menu(){
$items = array();

$items['tests'] = array(
    'title' => 'Tests',
    'page callback' => 'tests_contents',
    'access callback' => TRUE
);

$items['tests/delete/%'] = array(
    'title' => 'Delete',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('tests_delete_form', 1),
    'file' => 'tests_form.inc',
);
return $items;
}

function tests_contents(){
$delete_path = current_path();

$query = db_select('form', 'f');
$result = $query
        ->fields('f')
        ->execute()
        ->fetchAll();

foreach($result as $key){
    $output .= $key->id;
    $output .= $key->name;
    $output .= '<a href="'.$path.'/'.$key->id.'">download</a>';
    $output .= '<a href="'.$delete_path.'/delete/'.$key->id.'">delete</a>';
}
return $output;
}

```

And the tests\_form.inc code :

```
<?php

function tests_menu(){
$items = array();

$items['tests/delete/%'] = array(
'title' => 'Delete',
'page callback' => 'drupal_get_form',
'page arguments' => array('tests_delete_form'),
'access callback' => TRUE
);
return $items;
}

function tests_delete_form_submit($form, &$form_state) {
$path = current_path();
$rest = substr($path, 13);

$query = db_select('form', 'f');
$result = $query
  ->condition('f.id', $rest, '=')
  ->fields('f')
  ->execute();

$testid = $result->fetchField();

db_query("DELETE FROM {form} WHERE id = %testid", $testid);
}

```

How can I make this db\_delete function on click in my module ?

# Answer
Add path to delete your elements to `hook_menu()`.

```
$items['something/%/delete'] = array(
  'title' => 'Delete',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('mymodule_delete_form', 1),
);

```

In `mymodule_delete_form()`, use confirm\_form(). It will generate "are you sure?" form for you. Then, just write `mymodule_delete_form_submit()` to perform actual deletion.
> 2 votes

---
Tags: 7, database
---


# Question
Title: is installing a module on a live site ill advised?
I am trying to install Code Per Node on my website.

All i have to do is ad content types that would accept HTML5 webgames.

There would be theming involved.

Is this a no go?

# Answer
> 3 votes
I successfully installed modules on sites with thousands hits a day. Maybe even an hour. And I must tell it's not wise, from the point of my experience. Sometimes you have no choice (installing captcha on the spam wave when client forbids technical break), but way to many things can go wrong. If your site has any significant number of visitors and you care about your reputation, either:

* Install module on a copy of your site
* Put your site in maintenance mode
* Add `.htaccess` "maintenance mode" screen
* Sync files
* Sync data

Or simplier, but with longer break:

* Put your site in maintenance mode
* Add `.htaccess` "maintenance mode" screen
* Install module

That way if your site dies, visitors will see nice static html screen saying "Sorry, technical break" and you will be able to revert from backups.

# Answer
> 2 votes
There is no rule against installing a module on a live site. However, it is advised to test it out on a test server before deploying it to a live site.

---
Tags: 7, theming
---


# Question
Title: How to create complex conditional clauses / queries?
I've been reading the documentatoin on conditional clauses and also studied the api description for db\_and() and db\_or() but I fail to create a `$query` with 3 `->condition`s:

* select all between 0 and 100
* but exclude 23, 48 and 97
* select also 107, 123, 126 and 128

That's what I have tried so far:

```
$query->db_or()
  ->condition('my_field', array(107, 123, 126, 128), 'IN')
  ->condition(db_and()->condition('my_field', array(0, 100), 'BETWEEN')
                      ->condition('my_field', array(23, 48, 97), 'NOT IN'));

```

But I get the following error:

```
PHP Fatal error:  Call to undefined method SelectQuery::db_or() in [... first line]

```

I've tried to play around with the syntax like that:

```
$query->condition(->db_or()
  ->condition('my_field', array(107, 123, 126, 128), 'IN')
  ->condition(db_and()->condition('my_field', array(0, 100), 'BETWEEN')
                      ->condition('my_field', array(23, 48, 97), 'NOT IN')));

```

But again getting errors like that:

```
PHP Parse error:  syntax error, unexpected T_OBJECT_OPERATOR, expecting ')' in [... first line]

```

I also tried working with variables:

```
$cond01 = array('my_field', array(107, 123, 126, 128), 'IN');
$cond02 = array('my_field', array(0, 100), 'BETWEEN');
$cond03 = array('my_field', array(23, 48, 97), 'NOT IN');
$db_and = db_and();
$db_and->condition($cond02);
$db_and->condition($cond03);
$db_or = db_or();
$db_or->condition($cond01);
$db_or->condition($db_and);
$query->condition($db_or);

```

But this again yields drupal errors like that:

```
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Array' in 'where clause'

```

How to create a complex conditional database query with both AND and OR statements?

# Answer
Actually your final method is a right way, however the condition function is expecting 2 or 3 arguments(else only one **DatabaseCondition** instance as Molot said) and if you're not passing **DatabaseCondition** instance then your first argument should be the table column name. But you're passing an Array as the first argument. That's why you got unknown column 'Array' error.

So you should revise it like below,

```
$db_and = db_and();
$db_and->condition('my_field', array(0, 100), 'BETWEEN');
$db_and->condition('my_field', array(23, 48, 97), 'NOT IN');
$db_or = db_or();
$db_or->condition('my_field', array(107, 123, 126, 128), 'IN');
$db_or->condition($db_and);
$query->condition($db_or);

```

Further note your second approach is also right, however you put a extra -\> before calling the db\_or() function. So you should write it in the following way,

```
$query->condition(db_or()
  ->condition('my_field', array(107, 123, 126, 128), 'IN')
  ->condition(db_and()->condition('my_field', array(0, 100), 'BETWEEN')
                      ->condition('my_field', array(23, 48, 97), 'NOT IN')));

```
> 4 votes

# Answer
Drupal is not cleanly OO, and is not cleanly procedural. `db_or()` is **not** a method. It's a function. This function returns `DatabaseCondition` object you can use to attach other conditions to it, like:

```
$or = db_or()->condition('tid1', 5)->condition('tid2', 6);
db_delete('term_relation')->condition($or)->execute();

```

Note that you cannot just put arrays into `condition` method. It accepts either `DatabaseCondition` instance, or 3 parameters. 3 element arrays are **not** equivalent of 3 parameters in PHP.
> 1 votes

---
Tags: database
---


title: Images from ipad not rotating properly

text:
# Question
Title: Images from ipad not rotating properly
I have noticed that users who upload their images from iPad or iPhone have their images sometimes rotated in odd directions. I am not a Drupal guru and I generally find that documentation on drupal "how to" is ..well.. scarce,,

I have spent some time looking into this and did not find anything that would effectively help me.

What I would like to accomplish seems simple in principle but I need help.

Rather then forcing users to rotate images *(they find that to be clunky and awkward I have an average user who is interested solely to have things happen simply and without hassle)* I would like to have ALL my images on the site checked for orientation and have them automatically display the images in proper orientation.

I came across a module called Imagecache Actions and it is supposed to have Autorotate capability but I have no clue on how to use it for what I need.

ALL help would be greatly appreciated!

# Answer
> 0 votes
The -auto-orient operator is part of the ImageMagick image processing toolkit, to select the correct orientation of an image based on its EXIF data. Have a look at How to detect shot angle of photo ... for a more complete explanation.

The ImageMagick module integrates this function in Drupal, but they are still having an issue with autorotation. A recent patch is available there.

Your best bet is to try it out and see if it corrects your problem.

---
Tags: media
---


# Question
Title: Managing user accounts on remote drupal website? (Dev team all needs access)
My company makes lots of Drupal websites and the biggest annoyance I've seen is having to add each other as a user to each site whenever someone else wants to work on it. We all have the same email address domains as we use google docs.

We currently use openId and login with our google accounts but we have to make everyone a user on each site and they have to activate it.

Is there some type of module that would allow us to all have access to any site if said module was installed? Or that it would allow us to create an admin account because we have and can verify our domain in our email through google apps?

Thanks!

# Answer
> 0 votes
maybe User Import and keep a running cvs file of users to add to new sites on an as needed basis (?)

---
Tags: 7, users
---


# Question
Title: Creating slightly different sites using same code base
We are looking to create templated sites that have the same basic structure with the following differences. We would want to look up which site is being created based on domain/subdomain.

* Same navigation, but links to different node. ex: About Page has different content
* Different logo/header throughout the site.

Is there a module or suggested approach to do this?

NOTE: We want to use the same codebase and database.

# Answer
> 2 votes
The standard way of doing this is called a "multi-site". It allows you to use the same codebase for multiple sites. Each site in a multi-site has its own `settings.php`, so you may use different databases or the same database (this is controlled by the database settings in `settings.php`.

To use a different logo, just go to `appearance > settings` and upload a different image for the logo.

Here is a link to my tutorial about setting up a multi-site: http://wikihandbooks.com/drupal7/intro\_multisite.html

There is also instructions at Drupal.org: https://www.drupal.org/docs/7/multisite/multi-site-sharing-the-same-code-base

# Answer
> 0 votes
As per my understanding you want to use the same drupal instance to make another site.

Yes you can do all these which you have asked. You will have to copy the instance & set at different location(where ever you want, either at your local or sub-domain).

To change the logo, you will have to go to appearance-\>theme-\>setting & upload new image for logo.

You can go to your content list & edit the content of ABOUT US to change the page content of your about us link.

Other things like site name can be changed from site setting in configuration area of the site.

---
Tags: multi-sites
---


# Question
Title: Dynamic form building - cleanest way to substitute tags with form elements?
I have a string with tags, and form elements with elements corresponding to that tags:

```
$line = "This module contains [quantity] items of type [type]."
$elements = array(
  'quantity' => array (
    '#type' => 'textfield',
    //other settings
  ),
  'type' =>  array (
    '#type' => 'select',
    //other settings
  ),
}

```

Now, I have:

I want to generate:

What's the most standard Drupal way to do this? Elements and string will be taken from database. I assume it should happen in hook\_theme, but how to pass all values to it?

# Answer
As I understand what you need to do is:

1. Remove `div` around form elements and `label` next to from elements.
2. Put form elements in a right place.

I don't think there is a "one true way" of doing those. But here is how I would do it.

To do first use a #theme\_wrappers setting of a form element to override default one.

```
$form['quantity'] = array (
  '#type' => 'textfield',
  '#theme_wrappers' => array('custom_form_element')
  //other settings
);
$form['type'] = array (
  '#type' => 'select',
  '#theme_wrappers' => array('custom_form_element')
);

```

You the will need to implement `hook_theme` in your module to define `theme_custom_form_element` themer function.

```
function mymodule_theme() {
  return array(
    'custom_form_element' => array(
      'render element' => 'element'
    )
  );
}

```

Then you will need to implement the actual themer function. Look at `function theme_form_element($variables)` in `includes/form.inc` for reference. Yours should be much simplier, something like:

```
function theme_custom_form_element($vars) {
  return $variables['element']['#children'];
}

```

That should output only `<input />` html tags without surrounding divs - perfect for inline layout.

To put form elements into right places in the string I would suggest having another form element to store a string like that:

```
$string = db_query ... something ...

$form['tagged_str'] = array(
  '#type' => 'value',
  '#value' => $string
);

```

Also in form constructor provide a themer for the whole form like that:

```
$form['#theme'] = 'inline_elements_form';

```

(Name `inline_elements_form` is a result of my poor ability to come up with good names, you can name it anyway you want.)

You will then have to make changes to `hook_theme` implementation to register a new themer

```
function mymodule_theme() {
  return array(
    'custom_form_element' => array(
      'render element' => 'element'
    ),
    'inline_elements_form' => array(
      'render element' => 'form'
    )
  );
}

```

Now when you will be implementing theme function for the form you will have all from elements available to you.

```
function theme_inline_elements_form($vars) {
  $string = $vars['form']['tagged_str']['#value'];
  $quantity = drupal_render($vars['form']['quantity']);
  $type = drupal_render($vars['form']['type']);

  $output = str_replace(
    array('[quantity]', '[type]'),
    array($quantity, $type),
    $string);

  return $output . drupal_render_children($vars['form']);
  //NOTE: calling drupal_render_children is important to have the form working correctly
}

```

This is not quite as extensible as you might want. But I was aiming to give an idea of how you can customize forms an form elements.
> 1 votes

# Answer
If the tags are not dynamic you can have an array of possible form elements and then just foreach over them with matches from a regex. Then just have your mymodule\_form call a builder function that would look something like:

```
<?php
function my_dynamic_forms_dynamic_form($form, &$form_state, $id) {
  $string = my_dynamic_forms_db_call_for_strings($id);

  $elements = my_dyanmic_forms_get_array_elements();

  $form = array();

  $reg = '/\[(.*?)\]/is';

  if($c = preg_match_all($reg, $string, $matches))
  {
    foreach($matches[1] as $match) {
      $form[$match] = $elements[$match];
    }
  }

  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit Form',
  );

  return $form;
}

function my_dyanmic_forms_get_array_elements() {
  $elements = array(
  'quantity' => array (
    '#type' => 'textfield',
    //other settings
  ),
  'type' =>  array (
    '#type' => 'select',
    //other settings
  ));

  return $elements;
}

function my_dynamic_forms_db_call_for_strings($id) {
  $sql = 'SELECT string s from my_dynamic_form_strings_table s WHERE id = :id';

  $result = db_query($sql, array(':id', $id));

  return $result->fetchField();
}
?>

```
> 1 votes

# Answer
You want to use either a custom form function or hook\_forms() to create a custom form builder function that outputs a FAPI array.

Then in your function you simply build each form item, it looks something like this. I do some extra stuff like include a confirmation page for my form submission -- I'm yanking this out of existing code and trimming out some private info.

I'm not showing you the code to tear apart the string to get the form elements -- this is how to build a `$form` from database data like what you have and get a valid usable `$form` in Drupal.

```
/**
 * implementation of hook_forms().
 *
 * Normally drupal looks for a function of the form FORM_ID_form to build a
 * $form. In this case we are essentially using the custom form generator to build
 * each form more-or-less the same, but we still want each form to have a
 * unique $form_id. So, we use hook_forms() to build a kind of form factory
 * where each $form_id ultimately maps to 1 builder function.
 *
 * Drupal takes care of caching forms its previously built. Drupal also uses
 * this building knowledge to test that a submitted form "validates" as
 * un-tampered upon form submittal (this is seperate from custom form
 * validation).
 *
 * We can call this like:
 *   $form = drupal_get_form('mymodule_custom_form_2345');
 *   or
 *   $form = drupal_get_form('mymodule_custom_form_2346778');
 *
 * Each form is unique, built by our rules below.
 */
function mymodule_forms($form_id, $args) {
  $forms = array();
  if (strpos($form_id,'mymodule_custom_') === 0) {
    $forms[$form_id] = array(
      'callback' => 'mymodule_custom_form',
      // From API.docs the 'callback arguments' always contain $args. They are
      // always passed along to the form_builder().
    );

    return $forms;
  }
}

/**
 * This is our custom generic form builder function used to build all unique
 * $form_id Survey forms. By default drupal looks for a similarly named
 * function with _submit appended to it to handle form submission.
 */
function mymodule_custom_form($form_id, &$form_state, $args) {

  $args = func_get_args();
  // Eg, /some/path/23432432
  // because on this site all these customs forms use this type of path.
  $survey_id = $args[2];

  if (!isset($form_state['storage']['confirm'])) {
    $form = array();
    $form = _mymodule_build_fapi_array($survey_id);
    //
    // Add extra form elements here, such as to our custom submit and validation
    // handlers.

    // http://drupal.org/node/751826
    return $form;
  }
  else
  {

    #
    # Show a confirmation form.
    #

    $title = _mymodule_get_form_title($survey_id);
    return confirm_form(
        array(),
        'Are you sure you want to submit this form?',
        'site/my-surveys',
        "You are about to submit your answers for $title.<br><br>You will no longer be able to access or edit the survey you are about to submit as survey responses are anonymous. Are you sure you want to submit this survey?",
        'Yes, Submit the survey',
        'No, discard my answers and Start Over');
  }
}

  function _mymodule_build_fapi_array($survey_id) {
    $form = array();

    $form_items = db_query('SELECT question FROM {your_questions_table} WHERE id = :id', array(':id', $survey_id)->fetchAll());

    // These functions just generate individual FAPI elements.
    foreach ($form_items as $Q) {
      switch (strtolower($Q->question_type)) {
        case 'scalar':
          $form[$Q->item_number]= _generate_scalar_question($Q);
          break;
        case 'text':
          $form[$Q->item_number]= _generate_text_question($Q);
          break;
        case 'header':
          $form[$Q->item_number]= _generate_header_question($Q);
      }
    }
    return $form;
  }

```
> 0 votes

---
Tags: theming, forms
---


title: Display suite 7.x-2.4, Drupal 7.22

text:
# Question
Title: Display suite 7.x-2.4, Drupal 7.22
I am a newbie to Drupal.

I have just installed display suite to increase layout control. I am now getting a lot of notices like this:

> Notice: Undefined index: title\_value in link\_field\_update\_instance() (line 1305 of /var/www/vhosts/viovia.org/httpdocs/sites/all/modules/link/link.module).

What is even more of a nusiance is that I can configure customs fields for blocks and dynamic fields, but they will not display on my screen.

Can anyone tell me if this is linked to the index problem above, or is it anohter problem entirely?

# Answer
> 1 votes
The error message you quote has nothing to do with Display Suite. It is caused by a bug in the Link module (as should be obvious from the error message you quote).

Here is a link to the relevant issue ticket. If you read through the long list of messages, you'll see that the fix for this bug was commited to the dev branch of the Link module on May 23 2013. It is not in the "recommended" release. The "recommended" release of the Link module is from February 9 2013, so it is quite old.

Try to install the dev branch of the Link module, and see if things improve.

---
Tags: display-suite
---


# Question
Title: views replacing ul li within a large block of html text
I have a odd issue. I am using Views 3 and Drupal 6, when I create content with ul and li tags, Views strips out the list tags and replaces them with the following:

```
nbsp;
     .nbsp;nbsp;nbsp;nbsp;content
     .nbsp;nbsp;nbsp;nbsp;content
     .nbsp;nbsp;nbsp;nbsp;content
     .nbsp;nbsp;nbsp;nbsp;content
nbsp;

```

instead of:

```
<ul>
      <li>content</li>
      <li>content</li>
      <li>content</li>
      <li>content</li>
</ul>

```

The content appears correctly in the database, but in display and preview from Views the rewrite happens.

I have the following options: add default classes rewrite output (this was the first thing I checked and is displaying this behavior regardless of this rewrite) hide contents if empty.

thanks

# Answer
I would suggest installing the Theme developer module and tracking down the template that might be rendering that output.
> 0 votes

---
Tags: views, 6
---


# Question
Title: How to lock in the Sort Order for view display?
I've got a View of 10 images displaying inline, the first and last images are different (have rounded corners), and it is really important that the order for all 10 images is locked in. Is there a way to do this, without having to edit all the nodes in order to get them displaying in the correct order?

# Answer
You want the Nodequeue module.

You can make a queue and add nodes to it an arbitrary order. All queues have an associated view that gets created, and can be used anywhere you use a view.
> 0 votes

---
Tags: views
---


# Question
Title: How to create an image gallery in Drupal 7
I would like to create image galleries in my Drupal 7 site. Ideally the gallery should be easy to create and themable. What is the best way to do this?

# Answer
It seems like Taxonomy, Colorbox, Views, and the Image field in D7 would be the best way to do it.

1. Create a taxonomy for gallery
2. Create a content type for image
3. Create a View to display the gallery taxonomy
4. Create a View to display the images in the gallery taxonomy term

I say that is the best approach because it gives you the most flexibility, and will only take you about 30 minutes to set up. Anything else for a gallery (in my experience) tends to be overkill unless you're an actual photo sharing website.
> 3 votes

# Answer
Media Gallery is your friend.
> 3 votes

# Answer
The best way to create gallery is to use Views module.

Simply create a new content type (name it as gallery\_image) with a CCK image field.

Define image styles (presents) for thumbnail and preview sizes. (example.com/admin/config/media/image-styles)

Create a view of type node, filter item with respect to type gallery\_image and status published.

Use Views' templates to override each image and whole views layout.

---

For multiple galleries.

Create a content type and name it as gallery.

Add a CCK image field (For mega upload use Image FUpload)

While settings the CCK image field, set number of upload items as unlimited or more than 1 as you like.

Create image style (pre-sets) for thumbnail and preview sizes.

Setup your node--content-type.tpl.php template to customise gallery layout.
> 1 votes

# Answer
The Fancybox module is a very good one for creating your own gallery, and it is very simple to use as well.

> Provides the Fancybox jQuery plugin for displaying images (HTML content and multimedia support will come) in an elegant box.
>
> This module requires Fancybox 1.3+ (1.3.1 is recommended).
> 0 votes

# Answer
The Views Galleriffic module is fantastic.

> This is a views integration for the Galleriffic JQuery plugin.
>
> It allows you to make Views with image fields to create a galleries. These galleries can be attached to nodes themselves or act as stand-alone galleries. Because it uses Views this module is extremely flexible.
> -1 votes

---
Tags: 7, theming, media
---


# Question
Title: Linking to jQuery in block breaks Gallery formatter
At the top of my block, is this line:

```
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

```

This is the reason why the Gallery formatter does not display correctly.

The entire block contains the following:

```
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>
<script type="text/javascript" src="http://localhost/nes/sites/all/themes/nesvesti/js/facebook/fb-traffic-pop.min.js"></script>

<script type="text/javascript">

$(document).ready(function(){
    $().facebookTrafficPop({
        timeout: 10,
        delay: 0,
        title: "Support Us...",
        message: 'Like the page...',
        url: "http://google.com",
        closeable: false,
        opacity: 90
    });

});

</script>

```

My question is, is there any way to resolve this conflict?

# Answer
There's a few issues there. Drupal ships with jQuery so no need to include it twice. If you need a later version, use the jquery\_update module. Also, JavaScript in D7 should be wrapped in a jQuery namespace as per the documentation here https://drupal.org/node/756722
> 2 votes

# Answer
If you take your jquery code out of the block, and add it in at the theme level as a drupal behavior, you can guarantee that the code will run regardless of when the content is added to the page.

Content can be inserted after the document.ready has fired, in which case your code will never run.

If you put the code in its own .js file, or a file you use for your utility functions, and add it to your theme.info like so:

```
scripts[] = js/myscripts.js

```

Then you can add the code using a proper jquery closure, and within a behavior, like so:

```
(function ($, Drupal, window, document, undefined) {

Drupal.behaviors.myUtilityHandlers = {

    attach: function( context, settings ) {

            $().facebookTrafficPop({
                timeout: 10,
                delay: 0,
                title: "Support Us...",
                message: 'Like the page...',
                url: "http://google.com",
                closeable: false,
                opacity: 90
            });
        });

})(jQuery, Drupal, this, this.document);

```

It may look like clumsy overkill, but it will ensure your code plays nicely with everything else. I don't know what happens if you use the .once() function on the plain jquery object like that, but normally you'd wrap your code in the once() function so it won't run every time content is added to the page.

this is covered here: https://drupal.org/node/171213
> 0 votes

---
Tags: javascript
---


# Question
Title: How do I theme Views Slideshow inside a Panels pane?
I'm new to theming, so please bear with me. I have a Views Slideshow which I am displaying inside a Panels pane. The slideshow functions, but all the images are left aligned. I would like to either center or right-align the images, but nothing I've tried so far seems to work. It's difficult to discover who controls what, because, between Views and Panels, there are about 10 levels of divs before reaching the actual image tag, and each div has a large number of very long classnames!

I have a local css file in my theme folder, specified in my .info file, and have classnames/ids inside which should match what's appearing in Firebug. However, my CSS doesn't seem to be applied. The "style.css" that came with the theme (I made a sub-theme of Business Responsive) seems to always trump my local css file. My file is declared after "style.css" in the .info file, so it should win out in a CSS specificity battle.

Am I missing something obvious? Your sage advice is appreciated. :)

# Answer
> 0 votes
If your CSS styles are being *stomped*, this is due to CSS specificity standards. Basically, the more detailed the path in your CSS statement is, the higher its specificity is.

For example, suppose you have the following.

```
<div id="outer" class="outer">
    <div id="inner" class="inner">
    </div>
</div>

```

CSS styles specified on div will be trumped by div.outer; this in turn is trumped by div#outer. div.inner will be trumped by div.outer div.inner.

To have your CSS styles override the default ones, they need to have a higher specificity.

Keep in mind that:

* Inline styles trump everything
* Next come classes
* Then ids
* Nested paths are considered more specific than non nested paths

For example, suppose you have the following CSS styles.

```
div.outer div.inner { width: 80px; }
div#outer div.inner { width: 90px; }
div#outer div#inner { width: 100px; }
div.inner { width: 70px; }

```

You'll end up with a width of 100 pixels.

If you can add a CSS class easily at any point in the hierarchy, do that and include it in your CSS selector; you should be golden.

---
Tags: panels, theming, views
---


title: Resize images automatically

text:
# Question
Title: Resize images automatically
When I insert an image into content area it's usually larger than the content area and the pasted image overlaps with neighbouring blocks. I have to edit HTML and set `width` and `height` CSS properties.

Is it possible to configure Drupal for automatic image resizing (shrinking), so the creator of the article will only upload the image of arbitrary size?

thank you

# Answer
> 10 votes
If you attach an image field to the content type, you can define Image Styles at `admin/config/media/image-styles`. It is the core continuation of the Imagecache module.

This may be able to be made to work for inline images using the Media module, but YMMV.

# Answer
> 1 votes
I'm not completely sure what exactly you mean, but the Image resize filter module might be what you're looking for.

# Answer
> 1 votes
Go to configuration-\> media -\> image Styles add a new image style and set resize/crop/scale option you want for the image size.

Go to manage display of that content type and for the field image set the image style you created. Your image will be using the same image style while viewing the content node.

---
Tags: 7, media
---


# Question
Title: adding yet another domain to multi-site but this time symlink not working
Have no idea what's going on here. I'm trying to add another new domain to my multi-site but keeps directing to apache test page - not install.php.

Have many subdomains installed now and one new domain added to root one but this next one is giving me problems for some reason. Everything has been done same way. Set up in server to point to IP; separate database created; name of domain in sites folder created with default.settings.php copied to it as settings.php and chmod 644 then a symlink from the /var/www/html folder to the sites one but as I say just keep getting apache test page. Not found if try going to install.php. This is happened to me before but don't have a thorough understanding why...i am suspecting has something to do with database- not sure.

# Answer
> 5 votes
This has nothing to do with your database. At this point you have probably a problem completely unrelated to Drupal. Instead your Apache is not aware of your Drupal installation.

Here is a list of things you should check:

* Is that domain we're talking about pointing to your server (or do you see the test page of a different one): compare IP by `ping yourserver.com`
    + If it's a "testdomain" you might want to add an entry to `/etc/hosts`
* Is your virtual host configured correctly?
    + Did you set a `ServerName` or a `ServerAlias`
    + If you were setting up a new VHost, did you enable it (`sudo a2ensite yourhost` for instance)
    + Did you restart Apache/reload configuration after doing this (`sudo service apache2 reload`)?
    + Did you configure your VHost/your root directory to follow symlinks?
    + Have you set `NameVirtualHosts`?
* Are your symlinks pointing to the right folder?
    + Do you get the contents of your settings.php by typing `cat /var/www/html/sites/symlink/settings.php` in a terminal or an error?

As an example:

```
<VirtualHost *:80>
  ServerName yourdomain.com
  ServerAlias sub1.yourdomain.com sub2.yourdomain.com # etc ...
  DirectoryIndex index.php
  DocumentRoot /var/www/html
  <Directory /var/www/html>
    AllowOverride All
    Options -Indexes FollowSymLinks Multiviews
    Order allow,deny
    Allow from all
  </Directory>
</VirtualHost>

```

Again, it's most probably not Drupal related. It would be if you'd see a different one of your multisites or Drupal complaining about something but since you got the Apache test page you might want to ask on a different board (serverfault) and provide some more information (OS, directory structure, current host configuration and so on) if my checklist didn't help you.

# Answer
> -2 votes
I just worked it out but thank yu for above important list of reminders.

Was symlinking to sites folder instead of drupal folder- knew it was something simple.

So logical and yet totally passed over my head ;o

---
Tags: multi-sites
---


# Question
Title: How to display default value of disabled form elements after failed validation?
I have a form with some disabled form elements. When the form fails validation and is sent back to the user, the disabled fields are empty. How can I make the disabled fields display the default values that were originally defined in the form?

```
function foo_form(&$form_state) {
  return array(
    'foo' => array(
      '#type' => 'textfield',
      '#default_value' => 'foo',
      '#disabled' => true,
    ),
    'submit' => array(
      '#type' => 'submit',
      '#value' => 'Submit',
    )
  );
}

function foo_form_validate($form, &$form_state) {
  form_set_error('submit', 'You cannot submit this form');
}

```

In this example, when the user presses the Submit button, the expected warning is displayed, but the text field is empty. This is most disturbing for the user, he does not know that all relevant information to process the form are still present.

`$form_state['values']['foo']` is empty, but that's expected because disabled HTML elements are not included in the HTTP request that submits the form. Setting `$form_state['values']['foo']` to the desired value in the validation function does not help.

# Answer
The function that builds the form array isn't expecting any params unless you set a param in your `hook_menu` for instance. Instead you could try to grab the `$form` variable in the validation handler by reference and setting the value.

```
function foo_form() {
  return array(
    'foo' => array(
      '#type' => 'textfield',
      '#default_value' => 'foo',
      '#disabled' => true,
    ),
    'submit' => array(
      '#type' => 'submit',
      '#value' => 'Submit',
    )
  );
}

function foo_form_validate(&$form, &$form_state) {
  $form['foo']['#value'] = 'bar';
  form_set_error('submit', 'You cannot submit this form');
}

```

This is untested as I have no running Drupal 6 instance at the moment. But I was able to do so using Drupal 7.

Another approach would be to use `#value` instead of `#default_value` since you already got your custom validation handler to put some extra logic in (get rid of the form\_state value).
> 2 votes

---
Tags: 6, forms
---


# Question
Title: How to display different image on hover and content in pop-up?
I am displaying a list of images using Views. I would like a different image to display on hover, and then text/content to be displayed in the pop-up. I am trying to use Colorbox module, but can't figure out how to display a different image on hover, or how to display text/content in the pop-up.

Any help would be greatly appreciated.

This is the html that the Colorbox trigger field (set to Image) produces with "Enable Colorbox load" and "Enable Colorbox inline" options both UNTICKED:

```
<a class="colorbox-node init-colorbox-node-processed-processed" title="Italian" href="http://myshite/content/italian?width=500&height=500"><img width="92" height="77" alt="" src="http://mysite/sites/default/files/italian.jpg" typeof="foaf:Image"></a>

```

What am I missing/doing wrong? The popup is still not working.

# Answer
if I understand correctly, you want to swap in another image on hover, and when you click, you want the text to pop up in an overlay ?

Since you've already added the second hover image to the content type, if you set a class on the row, like .image-swap, add a class on the image field you want as the main image, like .image-main , and a class on the hover swap in image, like .image-hover

so your views output for the row ( without the extraneous stuff ) will look like

```
<div class="views-row image-swap">
    <span class="views-field image-main"><img ... /></span>
    <span class="views-field image-hover"><img ... /></span>
</div>

```

to handle the hover swap, you'd need css like this:

```
.image-swap .image-hover {
    display: none;
}
.image-swap.hovered .image-hover {
    display: inherit;
}
.image-swap.hovered .image-main {
    display: none;
}

```

and a js snippet of

```
$(".image-swap").hover(
    function () { $(this).addClass("hovered"); } ,
    function () { $(this).removeClass("hovered"); }
);

```

That should handle your image hover problem.

Now you can set up a colorbox trigger on the image-hover field to display the desired content in a colorbox overlay.
> 1 votes

# Answer
The Beautytips module provides ballon-help style tooltips for any page element and you can also use it in views.

Currently i am using this module with views to display the text(for field) in bottom of my page , when mouse hover of image. For more information check this video

> It provides an API for adding custom beautytips as well as some built-in features. Admins can enable rollover balloon-help style tooltips for text fields within forms. It also supplies hover tips for Drupal help links and advanced help links.
> 1 votes

# Answer
Add a new image field to your content type.

In Views, select the fields for title, description, image, hover\_image, and colorbox trigger.

Exclude description & hover\_image from display.

Set the colorbox trigger field to image, and the popup field to

```
<div class="description">[description]</div>
[field_hover_image]

```

You'd also need to add js to listen for the hover event and trigger colorbox, i.e.

```
jQuery(function($){
$('.image-class').hover(function(){
$(this).colorbox();
}, function(){
$(this).colorbox.close();
});
})();

```
> 1 votes

# Answer
Hover Preview for ImageCache this module will do image hover popup and even you can set the different styles and also able to use in views. See the demo

> The implementation of this module goes a bit further than just a javascript hover. It allows for hovering from any defined ImageCache preset to any other ImageCache preset. Since this is provided as a series of formatters, it is supported both in views and at the theme output layer.
> 0 votes

---
Tags: views, javascript
---


# Question
Title: How do you position a custom search box in the main menu?
I'm using the Drupal 7 Mayo theme for my site. The theme comes with a search box that you can place in the header but no where else, so I made a custom search box block, which I would like to place to the right of the main menu bar, which has a horizontal list of dropdown menu links. When I try to move the search block to the main menu, however, it either pushes the links to a line below or appears on a line below the links depending on how I set the weight. I can't get them to match up. Is there a way to fix this?

# Answer
Menu Inject Block module was built exactly for the same purpose.

> This module allows you to inject blocks as menu items. It facilitates easier use of JavaScript based dropdowns and panel like navigation. Most users employ this module to create dropdown panels using other modules to handle the dropdowns and this module to inject the blocks as needed.

To use this module:

1. Enable the module
2. Create or Edit your menu item (/admin/build/menu)
3. Enter in for the Path
4. Give your menu item a Title
5. Select a Block from the "BLOCK TO INJECT:" drop down (in your case the search block).
6. Save your menu item

You don't need to create a separate search block in case you use the module. You can place the default search block that Drupal provides, into step 5 mentioned above.
> 5 votes

---
Tags: routes, search
---


# Question
Title: Sub level menu in sidebar (but in specific pages)
How can i display sub level menus in sidebar?

For example: I have a Menu 1 (M1) with SubMenus (SubPage 1, SubPage 2, SubPage 3, SubPage 4) and I want that submenus displaying in sidebar just when clicked in Menu 1 (M1) and other submenu associated with menu 1.

And, when clicked in Menu 2 (M2), I want to display just the Submenus associated to Menu 2

Example image

:

Thank you in advance

# Answer
> 5 votes
This is exactly what Menu block does. You can set up blocks showing menu items according to the start level and depth you desire/configure. Those blocks show only up when there are menu items in that range so you even don't need to configure your blocks to only show up on certain pages. See the documentation for further information.

To be more concrete, your menu (main\_menu for instance) should looks like:

* Page 1
    + Subpage 1.1
    + Subpage 1.2
    + ...
* Page 2
    + Subpage 2.1
    + Subpage 2.2
    + ...
* Page 3

Set up a menu block that shows the second level and configure that block to show up in second sidebar. With this configured you'll see a menu showing Subpage 1.x when on Page 1 or on one of its subpages. The same counts for Page 2. When on Page 3 you won't see the menu in the second sidebar.

---
Tags: theming, routes
---


# Question
Title: How can I call hook_user_presave() only when an account is updated, not created?
I want to call hook\_user\_presave() only when an account is updated, not created. However, the API docs state:

> A user account is about to be created or updated.

Is there a way to check whether I am getting a new account or an update to an existing account?

# Answer
> 4 votes
On creation `$account` will have `is_new` set to true. And other minor differences, like it'll not have `created` property set yet.

```
object(stdClass)#92 (18) {
  ["uid"]=>
  int(0)
  ["hostname"]=>
  string(3) "::1"
  ["roles"]=>
  array(3) {
    [2]=>
    bool(true)
    [3]=>
    int(0)
    [4]=>
    int(0)
  }
  ["cache"]=>
  int(0)
  ["administer_users"]=>
  bool(true)
  ["name"]=>
  string(7) "test"
  ["mail"]=>
  string(14) "test@example.com"
  ["pass"]=>
  string(3) "aaa"
  ["status"]=>
  string(1) "1"
  ["notify"]=>
  int(0)
  ["timezone"]=>
  string(13) "Europe/Warsaw"
  ["signature"]=>
  string(0) ""
  ["picture"]=>
  NULL
  ["picture_delete"]=>
  int(0)
  ["picture_upload"]=>
  string(0) ""
  ["signature_format"]=>
  string(13) "filtered_html"
  ["init"]=>
  string(14) "test@example.com"
  ["is_new"]=>
  bool(true)
}

```

# Answer
> 2 votes
While creating the new user $account-\>uid will be 0 within this hook.

So you can use something below,

```
function mymodule_user_presave(&$edit, $account, $category) {
  if ($account->uid) {
    // DO your operations.
  }
}

```

---
Tags: hooks
---