# Question
Title: Bookings API versus existing spaghetti code
I'm working on an appointment booking system that allows registered users to book an outcall with an agent.

I've only come across Bookings API and Public Bookings, which seems more for things like library work rooms than it is for service industry people -- and even then, nothing about it looks at all pretty (Not a knock to the devs; it just isn't at the point comparable software is at on other CMSes.). My client has an existent system coded in some pretty funky PHP -- nothing OO, all logic code is in the same file as the design code (which is in, get this -- tables. Everything. In tables.) -- and I'm currently thinking about porting it to Drupal.

My questions are thus:

a. Are there any alternatives to Bookings API for appointment booking?

b. If not -- and considering I don't have a ton of Drupal programming experience -- would it be more worthwhile to update the existing spaghetti code appointment booking system to function as a Drupal module, or more worthwhile to just make Bookings API function more eloquently in this usage case (considering it has a lot more functionality, hooks, etc. than I could probably program into a new module in a short time)?

Thank you!

# Answer
> 2 votes
In answer to part (a) there is the Resource Conflict module, which appears to be similar in goal to the modules you mention above.

As for part (b) I'd argue that it is typically better to update or replace custom spaghetti code in such a way to work with existing modules--doing so will greatly ease the work of future maintainers of your code, and allow it to benefit from future enhancements to the Bookings API.

# Answer
> 2 votes
Check the Booking Time Slots module, or see Comparison of Booking System modules.

> Module provides Time Slots Booking functionality.
>
> For example:
>
> * Users can go to Calendar and book specified time slots
> * You can configure how many time slots are available and how long are the events, so after that time slot will be released
> * You can configure hourly and half-hourly time lots (in calendar view)

---
Tags: migrations, bookings
---


title: User registration and login problem

text:
# Question
Title: User registration and login problem
When I visit the registration page, or the login page, it says that I do not have access to that page. Do you have any idea why this happens?

# Answer
You're probably logged in to the site.

The user login and registration pages are not available for authenticated users, as it doesn't really make sense for a logged in user to login again or register.
> 2 votes

# Answer
Additional to the cause suggested by @Clive assuming that you are using the normal registration option provided by core:

1. What is the registration mode set in User Settings in **Administer \>\> User Management \>\> User Settings** (admin/user/settings). If Only site administrators can create new accounts then it's possible that I reckon you wouldn't be able to register (I'm not completeley sure about it as I haven't tried it out myself), but however you should still be able to login.
2. Is there any custom code that modifies the menu path for login (user/login) and registration (user/register) for which the `access callback` might return `FALSE` not letting anyone visit that URL giving the message that you are not authorized to view that page.

Also any new menu path with these previously registered menu path that might have recently been added unwillingly could sometimes case confusions such way. You could try clearing the cache or even `cache_menu` table specifically as a long shot. Also try disabling any suspicious modules that were recently enabled following which this issue might have been encountered.
> 2 votes

---
Tags: users
---


# Question
Title: Saving Custom Registration Form Drupal 7 Using FAPI
Good Day.

I created a custom registration form in Drupal 7 using FAPI.

I managed to add validation and it works great. Now my problem is when saving it to the database. I can't save my custom data/fields(e.g first Name, Last Name, Birthday, etc) to my db. I don't know how to do it. I followed all the tuts here http://drupal.org/node/1063598 but it seems my blob data is 0 byte. Did i miss something wrong? here is my code. Any replies are much appreciated.

```
function drupal_onrevue1_form_user_register_submit($form, $form_state){

   $edit = array(
          'name' => $form_state['values']['name'],
          'pass' => $form_state['values']['current_pass'],
          'field_first_name' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_first_name']))),
          'field_last_name' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_last_name']))),
          'field_middle_name' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_middle_name']))),
          'field_year_select' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_year_select']))),
          'field_month_select' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_month_select']))),
          'field_date_select' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_date_select']))),
          'field_gender_select' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_gender_select']))),
          'mail' => $form_state['values']['field_mail'],
          'init' => $form_state['values']['field_mail'],
          'status' => 1,
          'access' => REQUEST_TIME,
    );
    user_save(drupal_anonymous_user(), $edit);
}

function form_user_register($form_state) {
    $form['#validate'][] = 'drupal_onrevue1_validate_register_form';
    $form['#submit'][] = 'drupal_onrevue1_form_user_register_submit';
    $month = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October','November', 'December');
    for($i=1; $i < 32; $i++){
        $date[] = $i;
    }

    for($i=date("Y"); $i > 1900; $i--){
        $year[] = $i;
    }

    $form['field_first_name'] = array(
        '#type' => 'textfield',
        '#required' => TRUE,
        '#attributes' => array('class' => array('reg_input _con'), 'placeholder' =>'First Name'),
    );
    $form['field_last_name'] = array(
        '#type' => 'textfield',
        '#required' => TRUE,
        '#attributes' => array('class' => array('reg_input _con'), 'placeholder' =>'Last Name'),
    );
    $form['field_middle_name'] = array(
        '#type' => 'textfield',
        '#required' => TRUE,
        '#maxlength' => '2',
        '#attributes' => array('class' => array('reg_input1 _con'), 'placeholder' =>'M.I'),
    );

    $form['field_gender_select'] = array(
        '#type' => 'select',
        '#attributes' => array('class' => array('drop_filed')),
        '#required' => TRUE,
        '#empty_option' => '- Gender -',
        '#options' => array(
            1 => t('Male'),
            2 => t('Female'),
        ),
    );

    $form['field_month_select'] = array(
        '#type' => 'select',
        '#attributes' => array('class' => array('drop_filed _con')),
        '#required' => TRUE,
        '#empty_option' => '- Month -',
        '#options' => $month,
    );

    $form['field_date_select'] = array(
        '#type' => 'select',
        '#required' => TRUE,
        '#empty_option' => '- Date -',
        '#attributes' => array('class' => array('drop_filed1 _con'), 'style'=>'width:70px;'),
        '#options' => $date
    );

    $form['field_year_select'] = array(
        '#type' => 'select',
        '#required' => TRUE,
        '#empty_option' => '- Year -',
        '#attributes' => array('class' => array('drop_filed1'), 'style'=>'width:80px;'),
        '#options' => $year,

    );

    $form['field_mail'] = array(
        '#type' => 'textfield',
        '#required' => TRUE,
        '#attributes' => array('class' => array('reg_input _3 '), 'placeholder' =>'Email Address'),
    );

    $form['name'] = array(
        '#type' => 'textfield',
        '#required' => TRUE,
        '#attributes' => array('class' => array('reg_input _3'), 'placeholder' =>'Username')
    );

    $form['current_pass'] = array(
        '#type' => 'password',
        '#required' => TRUE,
        '#attributes' => array('class' => array('reg_input _3 '), 'placeholder' =>'Password'),
    );

    $form['field_repassword'] = array(
        '#type' => 'password',
        '#required' => TRUE,
        '#attributes' => array('class' => array('reg_input _3 '), 'placeholder' =>'Re-type Password'),
    );

    $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
        '#attributes' =>  array('class' => array("btn btn-medium btn-success"), 'style'=>'width:60px'),
    );

    return $form;
  }

```

# Answer
use &$form\_state instead of $form\_state in function name it should be

```
 function drupal_onrevue1_form_user_register_submit($form, &$form_state)

```

U have stated blob data as 0 byte. Are the other fields getting stored or not? for viewing values in submit use drupal\_set\_message() to check the values at runtime.
> 1 votes

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


# Question
Title: Why is my Cache Expire "0" even when I set it to be time() + 3600?
I'm caching our hefty menu output with the function show below, as each menu item loads two views (menu popups with sub-taxonomy data as a viewfield). This rids us of about 800 extra queries per pageload since Views Argument Caching doesn't work properly, and static caching seemed liked the easiest way to work around the problem. Also the data doesn't need to be that fresh.

Now the issue is, we want the data to be cleared whenever cron runs -- and I'm setting the expire timestamp to be +1 hour from the moment it gets cached, but when checking custom\_data CID from cache table the expire timestamps shows a 0 (never), instead of the now + hour. Any ideas?

```
/*
 * Check  if we already have main navigation in cache, if not, render it
 */
function mymodule_render_main_menu() {
  $navigation = &drupal_static(__FUNCTION__);

  if ( !isset($navigation) ) {
    // Check if we have cached data
    if ( $cache = cache_get('custom_data') ) {
      dsm("Nav from cache");
      $navigation = $cache->data;
    }
    // Else render the main navigation
    else {
      // Get main menu block
      $navigation = menu_block_block_view('1');
      $expire = time() + 3600;
      dsm($expire);

      // Set it's caching to 60min
      $navigation['#cache'] = array(
        'cid' => 'custom_data',
        'bin' => 'cache',
        'expire' => $expire
      );

      // Render the menu
      $navigation = render($navigation['content']);

      // Push rendered data to cache
      cache_set('custom_data', $navigation, 'cache');
    }
  }

  return $navigation;
}

```

# Answer
Worked using `cache_set('custom_data', $navigation, 'cache', $expire);`
> 1 votes

---
Tags: database, caching
---


# Question
Title: How to tell Custom Breadcrumbs which vocabulary to use?
In my site I have pages with a single vocabulary called "category" and Custom Breadcrumbs displays the taxonomy hierarchy and it works. Another content types has several vocabularies, including "category". But here Custom Breadcrumbs (CB) will not use the category but other vocabulary to generate the trail.

If I exclude the vocabularies I don't want CB to use to only allow "category", then no breadcrumb is displayed.

The only difference I see between those content types is the order in which I have created fields. Category was the last field I created for my second content type

So how can I force CB to use category as vocabulary ?

# Answer
I had the same problem on my site. I managed to fix it the hard way.

Edit custom\_breadcrumbs\_taxonomy/custom\_breadcrumbs\_taxonomy.inc

Add these lines after line 20:

```
$query->condition("v.vid", 2); // 2 is the id of vocab You want to use
$query->orderBy('v.weight');
$query->orderBy('t.weight');
$query->orderBy('t.name');

```

So You have:

```
...
$t_alias = $query->join('taxonomy_term_data', 't', 'r.tid = t.tid');
$v_alias = $query->join('taxonomy_vocabulary', 'v', 't.vid = v.vid');
$query->fields( $t_alias );
$query->condition("r.nid", $node->nid);
$query->condition("v.vid", 2);
$query->orderBy('v.weight');
$query->orderBy('t.weight');
$query->orderBy('t.name');
$result = $query->execute();
$terms[$node->vid][$key] = array();
...

```
> 1 votes

---
Tags: breadcrumbs
---


# Question
Title: How can I display an entire page at a specific path/url in a block?
I am using the HomeBox Module which outputs a page with a "Dashboard" like functionality. However I would like to be able to take this functionality from the page and turn it into a block, so that I could then add this functionality to any node/content type I would need.

What I have tried:

Nodes In Block, Node Blocks, Node As Block modules - these modules would do the trick if the page outputted by HomeBox was actually a proper node. In actual fact it cannot be edited as a node and so the additional options the above modules provide are not available in the page edit form.

Views module - when creating a View, I have tried filtering only by the url/path to show everything from the particular HomeBox page url. However this doesn't seem to be possible in Views. Since the page can't be tagged with taxonomy, isn't a content type, and (as far as I know) doesn't have a node id; by specifying the url and showing the page inside a View I could then make a block display and be done. But there doesn't seem to be general path/url filter in Views.

Does anyone have any suggestions as to what else I should try?

# Answer
> 2 votes
If you do something like this...

D6:

```
$foo=menu_execute_active_handler('path/to/the/homebox/page');

```

D7:

```
$foo=menu_execute_active_handler('path/to/the/homebox/page', FALSE);

```

...`$foo` should include either all of the html or a renderable array of the path/page content in question so *in theory* you could then stuff that in a block, either via a custom module or (ick) using the standard block interface and the (double ick) php input filter.

MORE THOUGHTS:

My basic thought above was to try to get to the menu handler for the page/path in question with as little custom code as possible. But, if you look in the HomeBox module, all it is doing for each page/path is calling `homebox_build()` along with a page argument that is easily crafted up. So, if you are comfortable with coding, you could write a custom module that uses that function within its block hooks to create the content.

Also, not sure about any css/js that would be needed but that could be hand crafted I suppose if necessary.

---
Tags: views, blocks, 7
---


# Question
Title: Drupal commons running very slow, what are the key modules to disable?
I'm running Drupal commons latest version 6.x-2.9 on MAMP 2.1.1 (clean install).

Drupal commons running very slow when I'm in the administer section. There's tons of modules and I'm not sure which are the key ones causing the slowness.

Need advice on that.

# Answer
This is normal for a Drupal site with a lot of modules. There are many SQL queries and huge use of memory to provide these admin pages, but if you look the site as a normal visitor, will see that this isn\`t the same.

Commons, specifically, i had many issues related to very slow admin pages, when developing a large social network, with the many modules from Commons itself and many others specific from the project.

To improve this, you can: * tune your MySQL (the first thing to do is set your tables as INNODB, that you help a lot) * use memcached * use PHP APC * Look around http://web.archive.org/web/20110516021804/http://www.morningtime.com/Drupal-6x-Performance-Guide/513 (the MorningTime site removed the link, so you\`ll only be able to see in the webarchive)
> 1 votes

---
Tags: 7
---


title: edit form: default value file field

text:
# Question
Title: edit form: default value file field
On my edit form I need to fill in the file field, this is my current code:

```
    $form['file'] = array(
    '#title'        => t('Upload image'),
    '#type'         => 'file',
    '#description'  => t('Images must be one of jpg, bmp, gif or png formats.'),
    '#default_value'        => "$link->icon",
    '#ajax'         => array(
      'wrapper'       => 'box',
      'name'          => 'icon2',
    ),
);

```

but the file field remains empty, in this way the admin has to reselect the desired image each time he edits the entry. The field returns 'no file chosen'.

Any ideas?

**Update I**

```
$form['file'] = array(
    '#title'        => t('Upload image'),
    '#type'         => 'managed_file',
    '#description'  => t('Images must be one of jpg, bmp, gif or png formats.'),
    '#default_value' => variable_get('', $fid),
    '#upload_location' => 'public://',
    '#ajax'         => array(
      'wrapper'       => 'box',
      'name'          => 'icon2',
    ),
);

```

# Answer
According to the FAPI documentation, `#default_value` isn't a valid property for a file element which is probably why adding it to the array has no effect.

You might have better luck using a managed file element instead; although the documentation also states that a `#default_value` is not valid for that type either, I've used it successfully for ages now. The default value needs to be a file id (`fid`) which references a file in the `file_managed` table.
> 4 votes

---
Tags: 7
---


# Question
Title: How to change the text format of the body field of 200 nodes at once?
I need to change the **Text format** of the body field of 200 node of the "flats" content type.

I guess I can do it in the database but I don't know where to look.

# Answer
> 0 votes
The query you suggested is great but if you want to make sure you're only including body fields from the content type you want to update you need to extend it slightly:

```
UPDATE field_data_body
SET body_format = REPLACE(body_format, 'plain_text', 'full_html')
WHERE entity_type = 'node' AND bundle = 'flats'

```

You'll also need to run the same query for the `field_revision_body` table or nothing will happen:

```
UPDATE field_revision_body
SET body_format = REPLACE(body_format, 'plain_text', 'full_html')
WHERE entity_type = 'node' AND bundle = 'flats'

```

---
Tags: nodes, entities
---


title: Add class to table in render array

text:
# Question
Title: Add class to table in render array
I am looking to add a class to a table that I am creating.

I have the code:

```
$build['table'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
);

```

I want to add a class to this table. I don't have any templates for the view of this table, so I don't really want to have to create a tpl.php for it, but I will if I have too.

# Answer
Here is description of all parameters that you can pass to theme\_table() function http://api.drupal.org/api/drupal/includes%21theme.inc/function/theme\_table/7

To add classes for table tag use this code:

```
$build['table'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#attributes' => array (
    'class' => array('class name goes here'),
  ),
);

```
> 3 votes

---
Tags: 7, theming
---


title: Drupal node title as URL permalinks

text:
# Question
Title: Drupal node title as URL permalinks
How can I use Drupal node title as URL Permalink just like wordpress %postname% ?

or even change the "node" from example.com/node/id ? (Drupal 6)

# Answer
Enable module Path. it is provided in Drupal core. If you want automatically generate url aliases for new nodes - install Pathauto

> The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.
> 2 votes

---
Tags: theming, nodes, 6
---


# Question
Title: when calling privatemsg_new in a block, how can I correctly set the internal $destination variable?
I am calling privatemsg\_new in php in a block so that the form to contact the node author is on the same page as the content. here is the code.

```
$node = menu_get_object();
if ($node->uid != 0) {
module_load_include('pages.inc','privatemsg');
$recipients = $node->uid;
print "<div>Contact " . $node->name ." about this post.</div>";
$subject = $node->title ." question.";
print drupal_render(drupal_get_form('privatemsg_new', $recipients, $subject));

```

Normally you access this form from the node page via a link that reads 'send this author a message' and that link loads a 'destination' parameter into the url query so that, when the message is finished, it redirects you back to the node page.

My code for the form in the block works fine except for the redirection back to the page after submission. The variable that needs to be set is inside the scope of the privatemsg\_new function:

http://drupalcontrib.org/api/drupal/contributions!privatemsg!privatemsg.pages.inc/function/privatemsg\_new/7

How can I set that variable so that redirection works correctly?

EDIT 8/1/2012 Eugene's answer below was the correct direction and code for this particular problem, but I wanted to update my question with the exact code necessary to achieve a fully functioning 'Contact Author' block. Simply copy and paste this in for Drupal 7 and it should work great, if you looking for the same solution.

```
$node = menu_get_object();
if ($node->uid != 0) {
module_load_include('pages.inc','privatemsg');
$recipients = $node->uid;
print "<div>Contact " . $node->name ." about this post.</div>";
$subject = $node->title ." question.";
$form = drupal_get_form('privatemsg_new', $recipients, $subject);
// Setup destination parameter to be equal to current page.
$form['#action'] = url('messages/new/'. $node->uid, array ('query' =>    drupal_get_destination()));
  print drupal_render($form);
drupal_set_title($node->title);
}

```

You have to set the drupal title manually. The reason being that the privatemsg\_new function overrides this.

# Answer
> 2 votes
Try this code in block, if you don't want to implement any hook in custom module.

```
$node = menu_get_object();
if ($node->uid != 0) {
  module_load_include('pages.inc','privatemsg');
  $recipients = $node->uid;
  print "<div>Contact " . $node->name ." about this post.</div>";
  $subject = $node->title ." question.";
  $form = drupal_get_form('privatemsg_new', $recipients, $subject)
  // Setup destination parameter to be equal to current page.
  $form['#action'] = url('node/'. $node->uid, array ('query' => drupal_get_destination()));
  print drupal_render($form);
}

```

# Answer
> 0 votes
I would try implementing hook\_form\_alter, and adding a submit handler at the end of the submission handler chain to add a redirect. Eg,

```
function mymodule_privatemsg_new_form_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = 'mymodule_submit_adds_redirect';
}

function mymodule_submit_adds_redirect($form, &$form_state) {
  $form_state['redirect'] = '/your/destination/final/redirect/url';
}

```

---
Tags: 7, privatemsg
---


# Question
Title: How do I display a link as an embedded player?
I want to create a field as a link. I want this link to be displayed as a custom embedded player.

I have checked out How do I add embedded YouTube videos in a field? and the Embedded Media Field module however this solution does not work for me.

1. I do not like the admin interface/configuration.
2. The module does not support my flash player.

Any suggestion would be great.

# Answer
> 0 votes
Checkout Drupal Tutorial - Creating an embedded video or audio player for a link field

Dependency Modules:

# Answer
> 2 votes
Another method is to create you own module. Checkout Media Link

Below is the code you would need. This module adds a podbean audio player display for your link field. *Modify the theme code for your embedded player.* Another good place to look at is the field example module.

Again, this module requires the Link module

```
<?php

/**
 * @file
 * Defines a display format for a link that will embed a player.
 */

/**
 * Implements hook_field_formatter_info().
 */
function media_link_field_formatter_info() {
  return array(
    'audio_player' => array(
      'label' => t('Audio Player'),
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
      'field types' => array('link_field'),
    ),
    /*
    'video_player' => array(
      'label' => t('Video Player'),
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
      'field types' => array('link_field'),
    ),
    */
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function media_link_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $elements = array();
  foreach ($items as $delta => $item) {
    $elements[$delta] = array(
      '#markup' => theme('link_formatter_'. $display['type'], array('element' => $item, 'field' => $instance)),
    );
  }
  return $elements;
}

/**
 * Implements hook_theme().
 */
function media_link_theme() {
  return array(
      'link_formatter_audio_player' => array(
          'variables' => array('element' => NULL),
    ),
  );
}

/**
 * Theme function for 'audio player' link field formatter.
 */
function theme_link_formatter_audio_player($vars) {

  $url = $vars['element']['url'];
  return "<div>" .
  "<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0' width='210' height='25' id='mp3playerlightsmallv3' align='middle'>" .
  "<param name='allowScriptAccess' value='sameDomain' />" .
  "<param name='movie' value='http://www.podbean.com/podcast-audio-video-blog-player/mp3playerlightsmallv3.swf?audioPath=" . $url . "&autoStart=no' />" .
  "<param name='quality' value='high' /><param name='bgcolor' value='#ffffff' /><param name='wmode' value='transparent' />" .
  "<embed src='http://www.podbean.com/podcast-audio-video-blog-player/mp3playerlightsmallv3.swf?audioPath=" . $url . "&autoStart=no' quality='high'  width='210' height='25' name='mp3playerlightsmallv3' align='middle' allowScriptAccess='sameDomain' wmode='transparent' type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/go/getflashplayer' /></embed>" .
  "</object>" .
  "</div>";
}

?>

```

---
Tags: 7, media
---


# Question
Title: Views body field pop-up not loading and preview not working
Recently we have moved our website from our own hosting to Pantheon. Since we've made the move the Views body field pop-up won't load anymore. Pop-ups for other field may or may not load. Also the Preview function in Views isn't working either. Because this may sound vague I've made a screencast display the problem. Also no errors are shown or created in the logs. I suspect it has something to do with AJAX.

# Answer
> 1 votes
This happened to me when I used the jQuery Update module with newer versions of jQuery (specifically 1.7). It causes several administrative oddities that you can get around, but the Views admin bug is pretty much crippling.

Here is a great patch that will allow you to choose a different version of jQuery for administrative pages, so for example, you can run jQuery 1.7 for the front end, but still use 1.4.4 for the administrative areas.

http://drupal.org/node/1524944

---
Tags: views, ajax
---


title: Where is the Image Field Settings Form

text:
# Question
Title: Where is the Image Field Settings Form
http://drupal.org/node/1558548

That page says I can fix this bug by visiting the image field setting form - where is this located exactly? I can't find it.

# Answer
> 1 votes
Didn't read the linked site, but:

* Image styles are managed here "admin/config/media/image-styles"
* Image Field settings are managed here: Visit "Structure" -\> Content types -\> Edit %your-content-type% -\> Manage fields tab -\> Click edit link in the row of %your-img-field%

---
Tags: 7, media
---


title: Menu Block change depth

text:
# Question
Title: Menu Block change depth
I'm converting an HTML template to a Drupal theme. The HTML template has a 2-level submenu: `ul` (main) \> `ul` (first-level) \> `ul` (second level).

In my `block--system--main-menu.tpl.php` I do only have: `<?php print $content ?>`

When I check the structure of the Main menu in Drupal (list links) levels are correct.

Now on my frontpage Drupal shows only the first level of the menu. How can I make Drupal show more levels? I'd love to do this without a (non-core) module.

Thanks in advance!

# Answer
> 1 votes
I think you just have the primary navigation enabled in your theme. To see the second level, enable the secondary navigation in your theme settings. But this will split you're navigation. A probably better solution is, to use the "Menu Block" module. This allows you to build different kind of navigations in a block.

---
Tags: navigation
---


# Question
Title: In Views 2, display only one value and leave blank all other values
I have a view that displays all nodes of a content type but I'm trying to display 1 value of a multi-value field and keep the rest of the values of the same field as blank. For example:

One field has 2 values: Yes and No. I'd like to display both nodes in my block in a table but for the column with the Yes/No field, I'd like to show "Yes" but leave blank if value is "No". Can this be done? Thanks

# Answer
Have a look at the Views PHP module. This allows you to check any field of the view with an if-statement (or wgatever you like). Not really a very nice solution, but simple.
> 0 votes

---
Tags: views
---


# Question
Title: How can I route automated emails through an email function in my module?
I was unable to get HTML mail to use a template properly, so I have a mymodule\_mail function that sends emails when a response is required from the user

```
function billiondollar_mail($key, &$message, $params) {
global $base_url;

$message['headers'] = array(
    'MIME-Version' => '1.0',
    'Return-Path' => 'xx@xx.com',
    'Content-Type' => 'text/html; charset=UTF-8; format=flowed',
    'From' => 'XXXX <xx@xx.com>',
    'Content-Transfer-Encoding' => '8Bit',
    'X-Mailer' => 'Drupal'
);

```

I have a switch case on `$key` that loads in html header and footer plus the email body.

I'm wondering if there's some way I can make the system emails (some sent via trigger/actions and the registration confirmation ones) use that same system. Right now they are in plain text, which is incongruous with the rest of the system.

If I can get them using that hook function I will need to know what `$key` value it would have and how to insert the message content.. presumably one of the `$params`

# Answer
> 1 votes
I think this is what you're looking for:

http://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_mail\_alter/7

"hook\_mail\_alter() allows modification of email messages created and sent with drupal\_mail()... All core modules use drupal\_mail() for messaging, it is best practice but not mandatory in contributed modules."

---
Tags: 7, emails
---


# Question
Title: How do i show/hide page content depending on the users role?
I am creating a site that has several roles. When some one who is logged in goes to a certain page I want the page to determine what content needs to be displayed depending on what roll they are.

Example. If the user is attached to the "teacher" role then they will see "Hello **teacher** thank you for visiting our site" then it might have two buttons that leads them to certain pages. If they are attached to the "student" role they will see "Hello **student** thank you for visiting our site" then the two buttons would be different and lead them some where else.

Is there a module that could help with this?

# Answer
There are two good ways you could go about this.

1. Install Panels and enable Page manager. Panels has a huge collection of what are called 'visibility rules' for individual panes. These allow you extremely fine grained control over who sees what portion of the page. Panels offers a lot of power, but brings a lot of complexity along with it.
2. Put your messages each in their own block. Blocks come with the ability to show and hide for certain roles. This method is much simpler, but if you have a lot more content than just the welcome message you want to show and hide panels will end up being a more customizable solution.
> 1 votes

---
Tags: nodes, users
---


# Question
Title: Drush post-installation - where can I find drushrc.php?
Just getting my first hands-on with Drush 5.1. The stuff works and is very promising as per how modules can be installed and enabled. One question though. **Where should I look for the drushrc.php file** that everyone is referring to and how should I code it to set up aliases for my sites?

I did a search over my disk and found nothing except examples.aliases.drushrc.php. Also I found a couple of mysterious locations:

```
C:\Program Files\Drush
C:\Program Files\Propeople\Drush
C:\ProgramData\Drush
C:\ProgramData\Propeople\Drush

```

They surely contain vital stuff and I'm not going to touch anything, but I'm wondering if this is the correct post-installation shape.

# Answer
First off, note that alias records go in \*.aliases.drushrc.php, whereas general (global) Drush settings go in drushrc.php. You can find example.aliases.drushrc.php and example.drushrc.php in the Drush "examples" folder. Drush will look for aliases.drushrc.php and drushrc.php in the ".drush" folder in your home directory. On most of my systems (Linux), my home directory is /home/ga; on Linux, $HOME and ~ will expand to your home directory. On my Windows system, my home directory is at 'c:/Users/Greg Anderson'. To find out exactly where Drush thinks your home directory is, run:

```
drush ev 'print(drush_server_home());'

```

Create a .drush folder inside of your home directory, copy example.drushrc.php to .drush/drushrc.php, and example.aliases.drushrc.php to .drush/aliases.drushrc.php, and customize to suit.
> 10 votes

---
Tags: drush
---


# Question
Title: Ongoing email alerts for content "assigned" to users via Entity Reference
I have put together a work tracking/scheduling system for the company I work for - it's built on Drupal 7 and basically enables clients, projects and tasks to be added and assigned to eachother (i.e. tasks added to projects, projects added to clients) via Entity Reference fields.

These three items are set up as Content Types, and both projects and tasks have statuses (active, ongoing, complete, etc) served by Taxonomy vocabularies. I'm also using Entity Reference to enable tasks to be "assigned" to users.

What I want to do next is set up two email alerts:

* An email alert to the user when a new task assigned to him/her has been added
* Ongoing email alerts summarising all outstanding (i.e. status not set to "complete") tasks (this would be daily, bi-daily or weekly)

I think the first is best catered for using Rules, but I'm not sure how to tackle the second. I know it depends on filtering by status and the reference field as well as being sent out at predetermined intervals, so I know it would probably involve Rules and Cron, but I don't know where to go from there.

# Answer
http://nodeone.se/en/learn-the-rules-framework Check out episodes 2 and 3 in particular. Then watch the rest of the series. Then watch all the other series. Then rejoice that Johan Falk is so freakin' awesome.
> 1 votes

---
Tags: rules, emails, cron, entities
---


title: creating subsites within my drupal site

text:
# Question
Title: creating subsites within my drupal site
I'm trying to create a subsite within our current drupal site. The v1 pass is all static HTML, but very soon, like as soon as I get v1 up I'm going to have to add in a few blocks for dynamic content.

I was wondering what the best way to structure this would be. We currently have a "chromeless-html-page" content type which i'm working with. But I wasn't sure if was the most efficient way as I would have to create a chromeless-page object for each page and then link them together. I was wondering would it make more sense to create a subsite-content-type that would be a view and then display all of those subsite-pages?

not sure if that makes sense or if i'm even on the right track with my question. I'm truly lost any help would be wonderful.

# Answer
> 1 votes
If the subsites are spread across multiple sub/domains, you can use domain to display a different set of nodes per-domain.

---
Tags: views, subsites
---


# Question
Title: Some menus not showing in Menu Settings drop down when editing page
I'm working on a website in Drupal 7.

I have the following menus in admin/structure/menus:

* **About Us Menu** (added)
* Get Connected Menu (added)
* **Main Menu** (default)
* Management (default)
* Navigation (default)
* User Menu (default)

Behind each menu in the list above, I have included "default" if it was included in the Drupal install, or "added" if I have added the menu myself.

I can add any page to any of these menus by using structure/menu/manage/*\[MENU NAME\]*/add, but I would like for my client to be able to select the menu from when adding or editing a page.

By default, I was able to add pages to the the Main Menu menu from the Menu Settings when adding or editing a page, and after adding the About Us Menu, I was able to add pages to same from this dropdown. However, I added another menu - Get Connected Menu, but I do not see it in the dropdown.

Adding additional test menus, I am still able to see only those that are in bold above - About Us Menu and Main Menu.

Has anyone ever seen this or know of a reason why this is happening and how to fix it?

# Answer
> 2 votes
Go to *admin/structure/types/* and click the *edit* link next to your content type. In the *Menu settings* tab select the menus you want to be available in the content creation page.

---
Tags: routes
---


title: Migrating and developing content types

text:
# Question
Title: Migrating and developing content types
I have partially defined a complex content type on a remote site. It's not finished, by no means. Now, I want to migrate this content type to localhost so to continue my development locally. An obvious choice for exporting/importing data is Features. But - if I export the content type definition as a feature, will I be able then to develop it further on localhost? If not, what would be the right way to go?

# Answer
> 3 votes
You will have no problem if you have the same field types installed on the localhost. For example If you are using the *email* field in your production site, it should be installed also in the localhost.

Assuming your are using Drupal 7, you have three choices:

> Bundle copy is a replacement for the Content copy module which lives in the CCK project for Drupal 6.

# Answer
> 0 votes
You must think carefully what dependencies your feature will have. How to structure the thing so it doesn't conflict with other Features.

Check the Kit is a specification:

http://drupal.org/project/kit

---
Tags: nodes, migrations
---


# Question
Title: How can I display author name, picture and signature when viewing a full node in D6?
I'd like to display the name, picture and signature of a node's author at the bottom of each node. The node.tpl.php file that I'm using (supplied by the zen theme) includes variables for the author's name and picture, but not the signature. How can I make that accessible in the template file?

# Answer
> 1 votes
Figured it out. To add a $user\_signature variable to your node.tpl.php file, add this function to your template.php file:

```
function YOURTHEME_preprocess_node(&$vars, $hook) {

  $account = user_load($vars['uid']);
  $vars['user_signature'] = check_markup($account->signature, $account->signature_format);
}

```

---
Tags: 6, theming
---


# Question
Title: Drupal implementing an advertising takeover with page background image
I need to implement a background image advertising takeover that surrounds the page content in drupal. It's similar to the ones on ign (screenshot attached below).

The only ways I can think of seem really hacky, such as using a view block to display one result of a custom content type containing the image and showing the view in a custom region that spans the background of the page.

Can anyone think of a better way? It needs to be easy to set up in the CMS for an administrator and they need to be able to create different takeovers for different sections of the site.

Thanks

# Answer
In your theme's preprocess\_page() hook you could set a variable that is accessible in your page.tpl.php file. Basically something like:

```
function YOURMODULE_preprocess_page(&$vars) {

  $vars['background_image']=make_me_a_background_for_page($_GET['q']);

  // other page preprocessing goes here

}

```

where `make_me_a_background_for_page()` is a custom function that returns a path to an image based upon the page being viewed. You can then use that variable however you want to create the background.

One way would be to put a quick div in the page somewhere like...

```
<?php if (!empty($background_image)): ?>
  <div id="use-this-background-image"><?php print $background_image; ?></div>
<?php endif; ?>

```

and have it hidden in css:

```
#use-this-background-image {
  display: none;
}

```

and then use jQuery to set the body's background to it:

```
// Drupal Behaviors Wrapper here :)

  if ($('#use-this-background-image').length) {
    $('body').css('background-image','url("' + $('#use-this-background-image').text() + '")');
  }

// Drupal Behaviors Wrapper here :)

```

An added bonus of doing it in this somewhat convoluted way is the background image isn't loaded until after your page is, so it pops in after the content, which, to me at least, is nicer looking than watching a big background load and THEN the content.
> 1 votes

# Answer
Do you want a pure Drupal / module based solution? If not, then I have done this most effectively with a bit of jQuery. When someone clicks to go to a certain page, the javascript would check to see if this matches the url in the script. If so, it dynamically changes the CSS as needed (background images, logo / header images, etc).

This is also most effective because you can have arrays of themes. How about multiple games each with its own branding? Very easily accomplished with this solution.

If that is a route you would like to take, let me know and I will provide some links and resources if you are not very familiar with jQuery.
> 0 votes

# Answer
very very easy PHP based solution.

Perhaps even easier than the jQuery would be this:

Lets say you have multiple style.css files - streetfighter.css; kidicarus.css; etc

In your page.tpl.php file (or maybe even in your html.tpl.php file) you add a PHP switch statement just below where the default drupal print $scripts php loads.

Because of the power of cascading style sheets, you can override any of the default style sheets before it to create whatever theme you like. Use php to check the URL then load the stylesheet as needed:

```
switch($url)
    case (url.com/streetfighter)
        print path/to/streetfighter.css;
    case (url.com/kidicarus)
        print path/to/kidicarus.css;
etc

```

now your final css overrides everything from background photos to link colors or colorscheme. Endless possibilities.
> 0 votes

---
Tags: theming, advertising
---


# Question
Title: Narrow down which module is causing a PHP warning
All of a sudden a site on my development server has been producing this php notice:

```
Notice: Use of undefined constant FIELD_BEHAVIOR_DEFAULT - assumed 'FIELD_BEHAVIOR_DEFAULT' in _field_info_prepare_instance() (line 297 of /var/www/mysite/modules/field/field.info.inc).
Notice: Use of undefined constant FIELD_BEHAVIOR_DEFAULT - assumed 'FIELD_BEHAVIOR_DEFAULT' in field_behaviors_widget() (line 458 of /var/www/mysite/modules/field/field.info.inc).

```

Is there anyway to narrow down which module could be causing this error? I've tried disabling a couple but have had no luck so far. I don't want to just disable the display of the warning as I feel I need to find the root of the issue :)

Has anyone else seen this error before? I suspected it might've been the GMap and Location modules for D7, but I've now removed them and I'm still getting this issue.

Thanks for your help!

# Answer
`FIELD_BEHAVIOR_DEFAULT` is defined in the core field.module file, which will always be loaded into the page build if you have the core field module enabled.

If you're getting an error that it's not defined then either the field module isn't being loaded for whatever context you're receiving the error in, or the field.module file has been corrupted/changed.

Try getting the field.module file from a fresh copy of Drupal and replacing it on your site, that might fix the problem. If not, grep your sites/all/modules folder for the string `FIELD_BEHAVIOR_DEFAULT`. That should help you narrow down the modules that use it, and which ones you should try to disable.
> 2 votes

# Answer
To more generally answer the title question, how to narrow down problems, I often find webchick's debugging patch really useful.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Distributed authentication system (different domains, separatate databases)
We got multiple small websites (microsites) and one main high traffic one with big users base. Right now the requirement is to build authentication system which should allow users to loign with the same identity across the network.

All website are running on different domains, powered by Drupal 6 CMS and have separate databases (so sharing tables with prefix is not an option + it creates a huge mess in the db).

Here is the set of core requirements I came up with:

1. Users should be able to login with the same credentials to all sites within the network
2. User’s data sharing between Main site (storage) and all micro sites within the network
3. Data synchronization across the network when user changes the data (update email or password for example)
4. The login/registration process should be seamless and consistent
5. Register on any of the sites across the network and use that identity to login later on.

In the future there might be a need to add openid authentication options.

Basically we are looking at something similar stackexchange does, but not sure if they have central users base on not.

I was thinking about custom solution which will include 2 parts (modules), one will be stored on the Main site for users data storing and responding to requests from clients. Second part (module) will be placed on each microsite, which is going to send requests to the Master. Some kind of client - server setup.

One of the complications I see right away is #3. Data Synhcronization across the network.

I just don't want to reinvent the wheel and maybe some work is already done in this direction.

Looking forward to your ideas on how to approach this project.

EDIT:

Recently I've found couple related threads on the topic:

http://groups.drupal.org/node/24916
http://drupal.org/node/744400

# Answer
This might be overkill, but have you considered using something like LDAP?

There is an LDAP integration module and an LDAP provisioning module. Both of which work quite well.
> 2 votes

# Answer
You might like to take a look at Development Seed's "Simple Sign-On with OpenID" blog post. I believe it's only a proof of concept, but they use OpenID to do single sign on across a network of sites.
> 2 votes

# Answer
interesting problem, I'm faced with the same challenge soon. I'm new to Drupal so I don't have a definite answer. However I'm looking at http://www.janrain.com/ (formerly RPX). They provide different login solutions and one specifically for "federated sites": http://www.janrain.com/products/federate There is a Drupal module for it http://drupal.org/project/rpx

Some details from the module's project page:

> The Janrain Social Login module integrates Drupal sites with the Janrain Social Login service.
>
> Using Janrain Social Login, Drupal sites can authenticate new and existing users with popular social networks, map user profile data from these websites to Drupal fields, and share Drupal content with a user's friends on their social networks.
>
> The module helps Drupal websites quickly and seamlessly integrate with 30+ social networks includingFacebook, Twitter, Google, Yahoo!, LinkedIn, AOL, PayPal, and Microsoft Account.
>
> Instead of having to integrate with each of these sites on your own (and manage API changes over time), Janrain Engage does the heavy lifting for you. Using this module, you can get setup in under 10 minutes. The result is an accelerated user registration process, an enhanced ability to gather user data, and increased site traffic from the viral promotion of your content.
> 0 votes

# Answer
Old question, but I've just used OpenID Provider successfully to login to a Drupal 7 site (the relying party) using an account created on another Drupal 7 instance (the provider).

Just enable OpenID Provider on the provider (not surprisingly) then enable the core OpenID module on the relying site, and point the OpenID URL to the provider's URL.

The email was transferred across. I haven't tested other fields. In addition, I wasn't able to change my password or email on the relying site - my provider account's password wasn't accepted.
> 0 votes

---
Tags: users
---


# Question
Title: Create my own slideshow like views_slideshow and views_galleria?
I want to create my own slideshow module using view. I want to use jquery/javascript provided by client and create slider using views. In short i want to make my own module/slider like views nivo slider

# Answer
Your question lacks a lot of information about what you already have in place but I'll try my best to answer you. You have a couple of options here.

1. Clone the nivo\_slider implementation an use your own javascript in place of nivo.
2. Add your JS to the page using drupal\_add\_js and call the necessary functions to init the js.
> 0 votes

---
Tags: javascript
---


# Question
Title: How can I sort a product display view by product popularity
I'd like to sort a view of Commerce product displays by their popularity (not too bothered by the specifics of how this is calculated). I found a comment by Ryan Szrama that implies it could be possible with vanilla Views:

> The gist of it is going to require a View of Orders joined to Line Items via the "Commerce Line Items relationship" joined to the Products via the "Referenced product" relationship. You can filter by Order State to only see purchased products and then count the occurrence of each Product ID to get the most referenced products. The hardest part will be establishing a relationship from the Product ID to the product display, but I believe you can use the reverse relationship from the product ID to a node referencing it so long as you only have a single product display per product.

Unfortunately even if my Views-fu was good enough to do that, I'd like for this to be just one possible sort (ie you can sort by price, title, or popularity) so I'd like to avoid using a View of orders. Is there an existing Views sort handler for this floating around at all, or perhaps another clever way to achieve it?

# Answer
Commerce Product Popularity provides a Radioactivity field for popularity.
> 0 votes

---
Tags: 7, commerce, views
---


# Question
Title: Filter view by users without a matching record in the related userpoints table
I found out that I'm getting a much better query performance if I use an INNER JOIN of users and userpoints compared to a LEFT JOIN.

Currently, new users have 0 userpoints when they register, I'll change that to 1 point with a rule.

To add 1 point to all users with 0 points I was thinking of using a view and Views Bulk Operations.

To get to "the point": I can't filter the view to show users with 0 points because they don't have a record in the userpoints table. This is the SQL that views tries to generate:

```
SELECT ..
FROM
{users} users
LEFT JOIN {userpoints_total} userpoints_total ON users.uid = userpoints_total.uid
WHERE  (userpoints_total.points = '0')

```

I don't think it's possible to generate a query with views to find users without a record in a related table? Or is there a trick?

# Answer
I figured it out:

```
function MYMODULE_views_query_alter(&$view, $query) {
 if($view->name = "nameofview") {
     $query->where[1]['conditions'][] = array('field' => 'userpoints_total.points', 'operator' => 'IS NULL',);
    }
}

```
> 1 votes

# Answer
There is a trick: your condition needs to be `… WHERE userpoints_total.points IS NULL` this will be true for all users that don't yet have a row in `userpoints_total`. Afaik you can easily add that condition via the views interface.

To be on the safe side you can also use: `WHERE userpoints_total.points=0 OR userpoints_total.points IS NULL`.
> 0 votes

---
Tags: 7, views, userpoints
---


# Question
Title: Is it possible to override a field module's implementation of hook_field_validate()?
I need to override `hook_field_validate()` for a particular field (provided by the Video Embed Field module). The description for that hook states:

> Validate this module's field data.

So the idea is that it's only invoked for the module that implements a particular field, which makes sense.

Unfortunately there's no altering mechanism in place (that I can find) so the implementations of those hooks are pretty much hard-coded. Also the hook is never run through `module_implements()` (as you would expect), so in turn is not available to be overridden using `hook_module_implements_alter()`.

Does anyone know of a way, however unclean, of overriding `hook_field_validate()` for a particular field implementation, without hacking any core/contrib modules?

# Answer
> 8 votes
There is hook\_field\_attach\_validate(), which is invoked by the single function that invokes hook\_field\_validate(), namely field\_attach\_validate(), which is called by field\_attach\_form\_validate().

I did not find an obvious way to get rid of the original validation function, but a quick hack would be to remove the errors, that the original validation function produced, from the `$errors` array in your hook\_field\_attach\_validate() implementation.

---
Tags: 7, entities
---


# Question
Title: How to show custom user profile fields in a view?
In Drupal 7, I am using Profile2 (7.x-1.0-beta1) module to add custom fields like 'Author Name' etc to an user's profile page. How do I pull those custom fields in a view (7.x-3.x-dev)? All other custom CCK fields shows up in a view's selection list but not those added to an user profile page.

# Answer
> 3 votes
I fail to understand why anyone would use Profile2 (or Content profile) when users in Drupal 7 are fieldable.

From what I understand from the Profile 2 project page, it utilizes Entity API; you may need to use EntityFieldQuery Views Backend.

# Answer
> 2 votes
```
<?php

global $user;

$uid = user_load($user->uid);
$profile = profile2_load_by_user($uid, 'showmember_profile');

//laod specific fields from the profile2 showmember
echo $profile->field_firstname['und'][0]['value'];
echo $profile->field_lastname['und'][0]['value'];
echo $profile->field_cityname['und'][0]['value'];
echo $profile->field_phone['und'][0]['value'];

?>

```

# Answer
> 1 votes
Check for user permissions for the particular role that the user belongs to. check if that role has permissions to view the profile of itself and any other user. To check that go to People \>\> Permissions section.

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


# Question
Title: In Views, use group type's image in a field when a group content type is fitered
I currently have a view that filters through a certain content type, which is a group content type. I am displaying fields such as title, body and last comment. I would also like to add an image field, which comes from the content type's group.

Is there a way to do this in Views?

I am using Drupal 7, and Views 3.

# Answer
In the end I used the view field view module: http://drupal.org/project/views\_field\_view

I firstly created a view that filters through all of the group type's images. In the contextual filter I used the group id.

In the other view I used the view above as the view field and used the group id as the arguement.
> 0 votes

# Answer
You will need to setup a relationship between the "Group Type" and "Group Content" content types. If the parent \> child relationship is determined using Taxonomy you can use the "Taxonomy: Parent Term".

Then you can add the field for the image which comes from the parent (make sure you change the relationship to the parent tax) and have it on the same row the as children.
> 2 votes

# Answer
I've got the same problem with OG 7.2, but I solved it *without* **views-field-view**. Instead I used OGs own way:

I first made the relationship **OG membership: OG membership from Node** to get the OG-Membership of the Group-Content I want to show and then...

...I need the Node of the Group of the OG-Membership and that means I need to make the relationship **OG membership: Group Node from OG membership** using the first relationship.

So now I have 2 *relationships* :

* OG membership: OG membership from Node
* (OG membership from node) OG membership: Group Node from OG membership

And now I was able to get access to the fields of the related group by using the relation **Group Node from OG membership**
> 1 votes

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


title: How to get URL value in drupal?

text:
# Question
Title: How to get URL value in drupal?
My URL is something like this http://xyz.com/content/show-cat?catid=2 . Now i want the value of catid (i.e 2) and save it in a variable. I wrote php code like $store=$\_Get\['catid'\];

But this format is not accepted in drupal. How can i implement this? Is there any alternative?

# Answer
> 1 votes
Try `$store=$_GET['catid'];` instead as PHP is case-sensitive.

---
Tags: webforms
---


# Question
Title: Custom tokens and/or text filters for consistent link look?
I have a site with a range of products. In order to ensure an easy input for the content editor and a consistent look throughout the site, I thought I'd make an input filter that would replace any occurrence of

```
[prod:product-name]

```

with a link to the node presenting the product (product-name == product code here). On output, this would be changed into, say:

```
<a href="products/product-name" class="product product-product-name">Real [product-name]</a>

```

However, I have doubts as per the efficiency side of such a solution, namely because - product-name would have to be a value of a field on the content type. Thus, for each replacement, Drupal would have to comb through all nodes, load each of them and perform a test to find a match. Quite database-intensive as I imagine.

So another thought was to provide a custom token. But would that change anything? Would it work within text fields, or would I have to use hook\_node\_view\_alter to invoke the replacements?

What would be your strategy to provide this kind of tokens?

# Answer
You could implement an input filter, or implement `hook_node_view_alter()`.

Keep in mind that an input filter is not only used for node's body, but also for comments, user's signature, some part of a view, and theoretically with any module that uses check\_markup() and that also allows the user to select an input format to use. As consequence of this, input filters should not take assumptions about when it is invoked.

There isn't normally any performance issue for accessing a node's fields; Drupal uses caches to avoid executing queries when not necessary.

If you are talking about the tokens provided from Drupal 7, or from the Token module, you could also implement a token, but you should consider that a token is accessible not only in the context you are expecting it to use it.
You should still need code to replace the token in text, using an input filter (for which the previous notes are still valid), or `hook_node_view_alter()`.

If you need to provide a token that should be accessible in a specific context (e.g. to be replaced in the body of nodes), you could use the code used by Drupal, which (in \_user\_mail\_text()) uses the following code.

```
  if ($replace) {
    // We do not sanitize the token replacement, since the output of this
    // replacement is intended for an e-mail message, not a web browser.
    return token_replace($text, $variables, array('language' => $language, 'callback' => 'user_mail_tokens', 'sanitize' => FALSE, 'clear' => TRUE));
  }

```

user\_mail\_tokens() is the function that provides the custom token that should not be available in other contexts.

```
function user_mail_tokens(&$replacements, $data, $options) {
  if (isset($data['user'])) {
    $replacements['[user:one-time-login-url]'] = user_pass_reset_url($data['user']);
    $replacements['[user:cancel-url]'] = user_cancel_url($data['user']);
  }
}

```
> 1 votes

---
Tags: input-formats
---


title: Description field has no text format

text:
# Question
Title: Description field has no text format
The Feed module successfully imports a RSS feed. However the Description field does not display. I can only see it if I click on "Edit". The problem is that the feed-items do not have a text format.

How can I give the Description field a default text format?

# Answer
> 0 votes
Seems to work properly if I do not use the default feed importer. Instead I created my own feed importer, I think with the exact same settings, and now it imports full html!

---
Tags: feeds
---


# Question
Title: Book revision page showing access denied if no revision present
I've edited the content type *Book* to "create a new revision" whenever user publishes the page (while creation and editing the page).

I have created a custom menu *Book revisions*, with path `node/[node:nid]/revisions` using menu token module. It renders `http://site-url/4/revisions` with `4` as the node id of current node.
I am using Nice menus module to create the menu block and have placed it on every book page so that user can see the revisions whenever he is on the book page.

When I first create a page, and click on this menu, it gives me Access denied page (I'm logged in as user1). But, the moment I edit the page and save it, it works as expected - showing the different revisions.
**Requirement:** I want to display "No revisions" instead of "Access denied" to users. How can this be done?
I'm also open to suggestions to hide the menu for the first time, and again show it as soon as a revision of the node is created.

**Edit:** I find that if a node is not revised (edited), `node_revision` table has only one `vid` for the `nid` of node; and if the node is revised the table contain one `vid` per revision.
Using this information and a database query, I think it would be possible to find out whether a node has revision. Something like

```
$result = db_query('SELECT n.nid from {node_revision} n WHERE n.nid LIKE :uid',array(':uid' => arg(1)));
$temp_var = 0;
foreach ($result as $result_item) {
  $temp_var++;
}
//If revisions are present $temp_var>1
//Only one version present if $temp_var == 1
if($temp_var == 1) {
  //menu unset code goes here...
}

```

I am just not sure in which *hook* should I implement this.

**EDIT:** I'm using Diff module to enable the users to view the differences in two revisions.

# Answer
If I understood this right, you have a (Nice) menu on node pages, and you've added the `node/[node:nid]/revisions` item to that menu. You're not actually listing revisions, just making a link to the revisions page, right?

If so, the problem is that the access callback for that menu item is hardcoded to return access denied if a node doesn't have revisions. Actually looks like this is being fixed for D8. Normally the tab wouldn't show, but it is in your case because you're creating the menu item in a different way, and the access is not checked when the link is printed. The solutions I can think of:

1. Replace the page with a view listing node revisions. Easy, but I don't know if you can replicate all the core revisions page functionality.
2. Create a wrapper menu item around the core revisions page using `hook_menu()`. Call it something else, like `node/%node/revs`. In the callback for that menu item, check if the node has revisions. If so, return the output of `node_revision_overview($nid)`, the core function that generates that page. Otherwise, return 'No revisions'
3. Use `hook_menu_alter()` to take the existing revisions menu item (`node/%node/revisions`) and move it to your menu. Take a look at the definition of the menu item in node.module line 2043. You'll need to change it to not be a `LOCAL_TASK` and then use the menu\_name property to tell it to get into your custom menu. I'm pretty sure this can work.
> 2 votes

# Answer
You could use a module that contextually defines which error page is shown to the user. Basically, you could create a node with content indicating there are no revisions to the book you are viewing and display that 403 page instead of the default 403 page through contexts (probably defined by URL structure including \[node:nid\]/revisions).

Try Context Error or perhaps CustomError.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Selecting nodes by content type and value of a custom field
I need to select nodes (1) of a certain content type and (2) satisfying a test against a custom field's value. Pseudo-code would be:

```
select all nodes of type TYPE_X which are published and where MY_FIELD = 'x'

```

I tried that with the EntityFieldQuery suggested here: How do I query a content type with custom fields in the 'condition' statement but Drupal/php crashes with "Fatal error: Allowed memory size of x bytes exhausted..."

So - what would be the correct code to use? I would appreciate a query which takes revisions into account.

# Answer
In Views, you could do this:

1. Create a view, filter on node TYPE and node PUBLISHED
2. Create an argument/contextual filter using your CUSTOM FIELD
3. In Fields, select NID (and/or TITLE or whatever you want to work with in the node(s))

Preview the view, putting FILTERONTHIS in the arguments/contextual filter area.

Look at the SQL it generated in the Preview and cut/paste it into whatever you need, substituting FILTERONTHIS for a variable of your chosing. Or, save the view and then use views\_get\_view\_result() to access the result.
> 0 votes

---
Tags: entities, database
---


title: Unlimited Values Weight

text:
# Question
Title: Unlimited Values Weight
Currently I have a field that allows unlimited values, and it's displayed as a video player, using user-input URL from that field. Now I would like to do some custom coding or whatever it takes to somehow pick the first URL (the one at the very top), so I can have the video player play only one URL. Any ideas?

# Answer
In a multi-value text field, and assuming D7, the values are something like this:

```
// if set, this is the first value...
$node->FIELD_NAME[$node->language][0]['value']
// if at least one set, this is the last value...
$node->FIELD_NAME[$node->language][count($node->FIELD_NAME[$node->language])-1]['value']

```

so depending on what you mean by 'on top,' one of these values is most probably what you are looking for. (If D6, just take out the `[$node->language]` part)
> 0 votes

---
Tags: entities
---


title: accountmenu for D7?

text:
# Question
Title: accountmenu for D7?
In Drupal 6, I've been using the `accountmenu` module to get a nice couple of links that change dynamically between `[Log in/Create account]` and `[My account][Log out]` according to whether or not the user's logged in.

It doesn't look like this module's been ported to D7 yet though, can anyone recommend an alternative? Or perhaps there are nicer ways to solve this now than in D6?

The module really isn't very large, the D7 porting effort probably would be pretty easy, but I'm new to D7 and I'd probably not do a very good job with it.

# Answer
> 1 votes
I have solved this problem easily for all my D7 installs by simply having two account menus - one with links for anonymous users such as 'login, create account' and the other with menu items to manage the account and logout.

If you set the roles so that 'anonymous' users only see the anonymous menu block, and set the authenticated for the authenticated menu block, then these will switch out seamlessly. Best of all, no custom code or extra modules required!

---
Tags: users
---


# Question
Title: Advanced forum how to change the html without modifying the core
I want to change the html for the topics list in Advanced forum module. I use a custom style. I foond that the file which displays the html is

> sites\all\modules\advanced\_forum\styles\mystyle\advanced-forum.naked.topic-list-view.tpl.php

If I edit this file the changes are displayed. But I don't want to modify core files in order to be able to upgrade. So I tried to copy this file to my custom style's folder. But the changes are not displayed. Is it possible to change the html without modifying the naked style and if yes how?

Thanks in advance

# Answer
> 1 votes
I realize this question was asked months ago, but I ran into a similar situation when trying to override an advanced\_forum template.

The solution was to copy the file into your theme templates folder, and rename it removing the advanced\_forums style name.

In the example of your case, you would copy the file:

\*sites\all\modules\advanced\_forum\styles\mystyle\advanced-forum.naked.topic-list-view.tpl.php\*

to:

*sites\all\theme\mythemename\templates\advanced-forum-topic-list-view.tpl.php*

Note the name change, and that "mythemename" should be whatever your custom theme is. You may also need to copy the file advanced-forum-forums.tpl.php into your theme directory

# Answer
> 2 votes
The easiest way to find the correct file name for your custom template files is to use the Theme Developer moduel. It allows you to point and click on anything in the browser and it tells you which part of the theme framwork rendered it and what options you have to override it.

Please note: You have to clear the theme registery after you added new templates, otherwise they are not shown.

---
Tags: theming, nodes
---


# Question
Title: update variable from 7.1 to 7.2 : got error message "The form has become outdated"
Got D7 multilingual configuration with many modules, from which i18n...

Trying to update variable from 7.1 to 7.2 version, following http://drupal.org/node/1660798 #1 tutorial (I also tried other methods explained in other nodes like http://drupal.org/node/1670274 ).

After clearing cache (twice !), replacing old i18n and variable folders with the new ones, I try to run update.php. Nothing happens, I mean reloading same page... I try then to put website into maintenance mode.

After submitting maintenance mode form, got error message "The form has become outdated. Copy any unsaved work in the form below and then reload this page." So I tried to put first into maintenance mode, **before** replacing folders. But then back to the same story : update.php reloads its page so I have to check again if I'm still into maintenance mode : BUT I'm not anymore...!

I guess what may happen is that changing variable folder generates the following mistake : Drupal doesn't read correctly its database variables, so doesn't see any more it is into maintenance mode ?

So who from the egg or hen comes first ? How could I manage that and stop eating aspirin ? Thanks a lot for sharing experience

# Answer
So to answer the question :

for people who don't manage to update simultaneously variable and i18n to get variable 2.1 & i18n 1.7 :

even if unusual, you have to **update first** from your current version (i.e i18n 1.4 and variable 1.1 ) **to i18n 1.5 and variable 1.2**, only after that you'll be able to update to variable 2.1 and i18n 1.7 versions.

Always following same steps :

* clear cache
* replace modules folders with the new version
* run update.php
> 0 votes

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


# Question
Title: Drupal CSS is not loading after server move
After moving the server, my CSS files don't work. When I open them in a browser, an error shows up:

> SmartOptimizer Error: Could not create cache file(cache/so\_11966173eab0271ad5607eadd11bf298.css.gz).

I have SmartOptimizer Installed, and I don't know if I need to change the settings.

How can I fix this?

# Answer
This doesn't really sound like a Drupal-specific question. That link doesn't even point to a Drupal contrib module.. Have you tried running through the install instructions again?

If you haven't "SmartOptimizer needs write access to smartoptimzer/cache folder. Make sure it's writable." looks pretty telling.
> 1 votes

---
Tags: 6, theming
---


# Question
Title: Access to a website only when I grant them access
I have made a registration form and a login form using PHP.

The registration form saves user's information to a database.

But as I am pretty new to PHP I want to achieve this think. I have also made a whole e-commerce website with Drupal commerce(commerce kickstart) but I want as an entrance page to be this registration form and when I grant them access to be able to see the whole content of my e-commerce website.While i say grant them access when they give me the fields of the registration form,they wont be able to enter the website until I send them a password. So my question is : How can I achieve not be able to see the entire website?What I need to do to protect it? I mean I need to add code on the registration form? on the login form or the template/theme?

I know that I have to use `$_SESSION[]` and `$_COOKIE[]`

For example

```
if($_SESSION['loggedIN'] ===false){ header('location:login_page.php')}

```

but I do not know where to put the code so as to work. In which part of the commerce kickstart do I have also to say that the e-commerce website would be on a sub-domain as the domain will be used for the registration form if this helps.

Thanks!

# Answer
> 2 votes
Ah, you don't need to be doing stuff like that with PHP. Drupal has plenty of tools to handle permissions for users.

Drupal already has the ability to allow you to make sure users need to be approved by an admin - check the user settings.

As for restricting access to "enter" site... well you need to review your user permissions table. "enter" is a pretty vague word to be using in Drupal terms.

# Answer
> 1 votes
I don't really understand why do you use custom login and register form instead of Drupal one. As for me, this is not a good approach.

Nevertheless, if your login form setups $\_COOKIE\['loggedIN'\] variable then it can be used in Drupal.

In code of your form save cookie in a way it can be available to domain and any subdomain

```
setcookie('loggedIN', TRUE, 0, '/', 'domain.com', FALSE, TRUE);

```

This will setup cookie that will be expired on the end of the session.

Create simple drupal module "mylogin" by name (http://drupal.org/node/1074360). In mylogin.module file place this code:

```
/* hook init */
function mylogin_init() {
  global $user;
  if (!$user->uid) {
    /* Check cookie only for anonymous Drupal users. If user is logged-in using Drupal login form then he will not be affected.*/
    if (empty($_COOKIE['loggedIN'])) {
      header('Location: http://domain.com/login.php');
      exit;
    }
  }
}

```

`mylogin_init()` function will be executed on any page, and redirect any users that don't have a Drupal session to your custom login form.

NOTICE! My advice - not to use this method but to use standard Drupal register and login forms instead.

---
Tags: commerce
---


title: What if nid reaches the maximum ?

text:
# Question
Title: What if nid reaches the maximum ?
What if my `nid` reaches the maximum allowed value of MySql int type

I have made a drupal.org site search that ends up Here. And also i found Integer Types (Exact Value). In an app that i am about to build is a contact manager for students. Which is supposed to pull gmail, fb contacts in future. My plan is to make each contact a node. Is it a good idea to keep each contact as separate node? Can you suggest any other brilliant mechanism to handle this?

I am worried about the overflow of `nid` as i made a test run using may own gmail id, which ends up in a 1025 new nodes.

I am using typical Drupal 7.14 installation.

# Answer
If nid reaches the maximum your site will no longer be able to create new nodes as there will be SQL errors whenever Drupal tries to insert a new nid.

Chances are though, that drupal.org will hit this limit before you do, regardless of what you're doing to your site in any useful real-world application.

If drupal.org gets anywhere close to 4 billion nodes, there definitely will be a workaround readily available for you.
> 6 votes

---
Tags: 7, nodes, database
---


# Question
Title: Node reference: Select an exisiting node, or create a new one
I am using Drupal 7, with the References module installed.

I was wondering if there is a way (or perhaps another module) so I can select an existing node from the list or create a new one on the fly (ajax or non ajax)?

So for example I have a button for create new node and automatically select the new node as a reference?

I'd like to have the node reference as a LIST only, not auto complete.

# Answer
Try the Node Reference Create Module.
> 1 votes

# Answer
I do not believe there is an existing module recipe that does everything you describe. You could combine the standard node reference list selector with the Node Reference URL Widget module to meet your requirements. NodeReference\_url expects the referencing nid as a parameter in the URL, so you could add a hyperlink through a module or theme template to render anywhere (next to the standard list or add an extra choice "Add New" to the list with a JQuery onChange). Node Reference URL lets you set a return page to the "Previous page" when editing the node reference field admin/structure/types/manage/\[your content type\]/fields/field\_\[your field\] for a smooth round trip.

I realize this is not an AJAX solution, but these pieces could be converted to such in a custom module and might get you started.

Out of the box, Node Reference Create is as close as you can get I'm afraid.
> 0 votes

# Answer
Check out References dialog also. The module extends reference fields like the user, entity and node reference fields by adding links to add, edit and search for references through a dialog.
> 0 votes

---
Tags: entities, nodes
---


title: Same dates for publish and post

text:
# Question
Title: Same dates for publish and post
I am using the published date module.

The posted date, and published date are the same for the nodes. Does anyone know any reason why that is so?

# Answer
The publish date can change, like after unpublishing and republishing some content. The post date is rather fixed, it's the date the content is created...
> 0 votes

---
Tags: nodes
---


# Question
Title: Using views to generate a summary view of nodes
I have been wrapping my head around this problem. Basically I have changed the post settings to teaser mode. And I have made views that filters node of certain type . To conclude, I want my nodes to be displayed like in this link http://asblab.mie.utoronto.ca/research where the research links has a summary view with the read more.

Thanks in advance.

# Answer
> 0 votes
There are a million different ways to do things in Drupal, but:

1. Create a View
2. Filter on node published and type
3. Sort by whatever criteria you desire and select how many items you want displayed
4. In Fields, select:

a. Node Title - link to node

b. Body or Field that contains the description you want displayed (select Trimmed if you want it shorter than all of it) and remove the label

c. Node Link - enter Read More as the text to display and remove the label

and you should be on your way...

---
Tags: views
---


title: custom views in taxonomy tags pages

text:
# Question
Title: custom views in taxonomy tags pages
I have created a custom view for my Drupal 7 front page, and I have named it "Recent Products", but this view is only working for the front page is not working in taxonomies, tags, content preview pages.

How do I apply this view for every page, or set it as default for pages?

# Answer
> 1 votes
I think there is a misunderstanding: The Views module is used to create pages, or blocks. In both the cases, the created view shows nodes, users, taxonomy terms, modules, etc matching some criteria set for the view.

A view is not a template for altering the content of other pages. For that there is the Panels module. (Emphasis is mine.)

> The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you **visually design a layout and place content within that layout**. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even **override system pages such as taxonomy and the node page** so that you can **customize the layout of your site** with very fine grained permissions.

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


# Question
Title: A custom Field with #submit function can't pass value
i wrote a custom field and i want to do mini validation just in the custom field.

The only input data are the cellphone textfield. The other form fields all are used for validation.

However, i can't pass the value of the field.

Is there something wrong?

```
 function cellphonefield_field_widget_form(&$form,&$form_state,$field,$instance,$langcode,$items,$delta,$element)
    {
        $base=$element;

      dpm($items[$delta]['cellphone']);

        $element['cellphone']=array(
             '#type' => 'textfield',
         '#title'=>t('Enter your Cell phone Number!'),
         '#description'=>t('System will send you a message '),
         '#default_value'=>isset($items[$delta]['cellphone'])?$items[$delta]['cellphone']:'test for this field',
        )+$base;

      $form['send_sms']=array(
             '#type' => 'submit',
             '#name' => 'send_sms',
             '#title' => t('validate your cellphone number'),
           '#value'=>t('Send Me Validate Code'),
         '#weight'=>1,
         '#limit_validation_errors'=>array(
         array('cellphone')),
         '#submit'=>array('send_sms_function'),
        );

      $form['validate_code']=array(
             '#type' => 'textfield',
         '#name' => 'validate_code',
         '#size' => 20,
         '#title'=> t('Enter the validation code !'),
         '#description'=>t('Please check your cell phone sms message and then enter the code in the sms.'),
         '#weight'=>2,

        );

      $form['validate_button']=array(
             '#type' => 'submit',
             '#name' => 'validate_button',
             '#title' => t('validate your cellphone number'),
           '#value'=>t('Validate'),
         '#weight'=>3,
         '#limit_validation_errors'=>array(),
         '#submit' => array('send_sms_function'),
        );

        $form['submit_message']=array(
        '#type'=>'item',
        '#title'=>t('Cell Phone'),
        '#description'=>t('Your phone is been validated!'),
        '#weight'=>4,
      );

        return $element;
    }

    function send_sms_function(&$form,&$form_state)
    {

$cellphone=$form_state['values']['cellphone'];
      dpm($cellphone);
          }

```

# Answer
For validating the content of a field there is hook\_field\_validate(). As example of implementation of that hook in a module, you can look at taxonomy\_field\_validate(), or number\_field\_validate().

```
function number_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
  foreach ($items as $delta => $item) {
    if ($item['value'] != '') {
      if (is_numeric($instance['settings']['min']) && $item['value'] < $instance['settings']['min']) {
        $errors[$field['field_name']][$langcode][$delta][] = array(
          'error' => 'number_min',
          'message' => t('%name: the value may be no less than %min.', array('%name' => $instance['label'], '%min' => $instance['settings']['min'])),
        );
      }
      if (is_numeric($instance['settings']['max']) && $item['value'] > $instance['settings']['max']) {
        $errors[$field['field_name']][$langcode][$delta][] = array(
          'error' => 'number_max',
          'message' => t('%name: the value may be no greater than %max.', array('%name' => $instance['label'], '%max' => $instance['settings']['max'])),
        );
      }
    }
  }
}

```

As far as I can see, fields don't add submission buttons. That is not the purpose of fields, which is to add fields to enter data for an entity (e.g. nodes, users, taxonomy terms).

In your case, the workflow is similar to the following one:

* The user enters a cell phone number
* The module tells to the remote service to send a verification code to that cell phone number
* The user enters the verification code
* The module checks the verification code is the expected one

Such workflow can work if it is done in two steps:

* When the user first enters the cell phone number, the validation hook can just send the cell phone number to the remote service. It cannot wait the user receives the verification code, and enters it.
* The second time, the user edits the verification code, and the validation hook will check the verification code is the right one.

You have to see if checking the verification code can be done synchronously, or asynchronously.
> 1 votes

---
Tags: entities
---


# Question
Title: How do I limit the values returned by ctools_export_load_object()?
Imagine I have the following code.

```
$result = ctools_export_load_object('mytable', 'conditions', array('date' => '1337020900'));

```

How can I limit the values returned by ctools\_export\_load\_object()? What is the difference between `ctools_export_load_object()` and `db_query()`?

# Answer
> 1 votes
You are right; that is how you should call `ctools_export_load_object()` to filter the returned objects. Keep in mind that:

* For each condition you can just enter a value a database field must have
* If you enter more than one condition, the function will return the objects for which all the conditions are verified

The code used from the function for handling the conditions is the following one.

```
  else if ($type == 'conditions') {
    foreach ($args as $key => $value) {
      if (isset($schema['fields'][$key])) {
        $query->condition($key, $value);
      }
    }
  }

```

Because that code, you cannot get (for example) the objects for which the date is 1337020900, or 1337020910, or 1337020940, or 1337020906. You cannot choose the operator to apply for the conditions, which means (for example) that you cannot get all the objects for which the date is greater than 1337020900, or lower than 1337020900.

The difference between `ctools_export_load_object()` and `db_query()` are the following.

* `ctools_export_load_object()` doesn't just return the objects obtained from a database table; it returns also objects returned from a specific hook. This is done from the following code in `_ctools_export_get_defaults()`.

if ($export['default hook']) {
  if (!empty($export['api'])) {
    ctools_include('plugins');
    $info = ctools_plugin_api_include($export['api']['owner'], $export['api']['api'], $export['api']['minimum_version'], $export['api']['current_version']);
    $modules = array_keys($info);
  }
  else {
    $modules = module_implements($export['default hook']);
  }

  foreach ($modules as $module) {
    $function = $module . '_' . $export['default hook'];
    if (function_exists($function)) {
      foreach ((array) $function($export) as $name => $object) {
        // Record the module that provides this exportable.
        $object->export_module = $module;

        if (empty($export['api'])) {
          $cache[$table][$name] = $object;
        }
        else {
          // If version checking is enabled, ensure that the object can be used.
          if (isset($object->api_version) && version_compare($object->api_version, $export['api']['minimum_version']) >= 0 && version_compare($object->api_version, $export['api']['current_version']) <= 0) {
            $cache[$table][$name] = $object;
          }
        }
      }
    }
  }

  drupal_alter($export['default hook'], $cache[$table]);
  ```

</code></pre>
* `ctools_export_load_object()` can automatically join tables, if it finds the right information in the database schema defined in `hook_schema()`.

```
// Build the query
$query = db_select($table, 't__0')->fields('t__0');
$alias_count = 1;
if (!empty($schema['join'])) {
  foreach ($schema['join'] as $join_key => $join) {
    if ($join_schema = drupal_get_schema($join['table'])) {
      $query->join($join['table'], 't__' . $alias_count, 't__0.' . $join['left_key'] . ' = ' . 't__' . $alias_count . '.' . $join['right_key']);
      $query->fields('t__' . $alias_count);
      $alias_count++;

      // Allow joining tables to alter the query through a callback.
      if (isset($join['callback']) && function_exists($join['callback'])) {
        $join['callback']($query, $schema, $join_schema);
      }
    }
  }
}

```
* `ctools_export_load_object()` caches the result obtained, which means it could not execute any query at all.
* `ctools_export_load_object()` uses many functions that are defined in the database schema. You can look at the code comments in `ctools_export_get_schema()` to see which functions are used.

As side note, a comment contained in `ctools_export_get_schema()` says (emphasis is mine):

> Please do not call these directly, **always use the ctools\_export\_crud\_* wrappers** to ensure that default implementations are honored.

# Answer
> 0 votes
as i see it, you have to limit the `$result` array yourself, if the conditions are not limiting enough.

the difference, taken from the documentation:

> This function will cache the objects, load subsidiary objects if necessary, check default objects in code and properly set them up. It will cache the results so that multiple calls to load the same objects will not cause problems.
>
> It attempts to reduce, as much as possible, the number of queries involved.

---
Tags: 7, database, chaos-tool-suite
---


# Question
Title: How do I optimize a Views "execute_count_query"?
So, I was able to optimize a particularly nasty query in one of my views using mymodule\_views\_query\_alter(), bringing it from 13 seconds down to about 200 milliseconds. However, I see in my Devel query log there is an associated "execute\_count\_query" that Views automatically runs that does NOT contain my optimizations. It is as if any count query ignores my hook overrides. Thus, the count query continues to run up a 13 second call! I've pasted it below in all its disgusting glory.

So, how in blazes do I get at this query?

```
SELECT COUNT(*) AS expression FROM (
SELECT 1 AS expression FROM drupal_node node INNER JOIN (
SELECT td.*, tn.nid AS nid FROM drupal_taxonomy_term_data td
INNER JOIN drupal_taxonomy_vocabulary tv ON td.vid = tv.vid
INNER JOIN drupal_taxonomy_index tn ON tn.tid = td.tid
WHERE (tv.machine_name IN (:db_condition_placeholder_7)) ) taxonomy_term_data_node ON node.nid = taxonomy_term_data_node.nid
LEFT JOIN drupal_taxonomy_vocabulary taxonomy_term_data_node__taxonomy_vocabulary ON taxonomy_term_data_node.vid = taxonomy_term_data_node__taxonomy_vocabulary.vid
LEFT JOIN drupal_field_data_field_published_at field_data_field_published_at ON node.nid = field_data_field_published_at.entity_id AND (field_data_field_published_at.entity_type = :views_join_condition_0 AND field_data_field_published_at.deleted = :views_join_condition_1)
WHERE (( (node.status = :db_condition_placeholder_0) AND (node.nid IN (SELECT tn.nid AS nid FROM drupal_taxonomy_index tn
LEFT OUTER JOIN drupal_taxonomy_term_hierarchy th ON th.tid = tn.tid
LEFT OUTER JOIN drupal_taxonomy_term_hierarchy th1 ON th.parent = th1.tid
LEFT OUTER JOIN drupal_taxonomy_term_hierarchy th2 ON th1.parent = th2.tid
LEFT OUTER JOIN drupal_taxonomy_term_hierarchy th3 ON th2.parent = th3.tid
LEFT OUTER JOIN drupal_taxonomy_term_hierarchy th4 ON th3.parent = th4.tid
WHERE ( (tn.tid = :db_condition_placeholder_1) OR (th1.tid = :db_condition_placeholder_2) OR (th2.tid = :db_condition_placeholder_3) OR (th3.tid = :db_condition_placeholder_4) OR (th4.tid = :db_condition_placeholder_5) ))) )AND(( (node.type IN (:db_condition_placeholder_6)) )))) subquery

```

# Answer
> 2 votes
As long as you know the query you want use in its place, you can override the count query for a view fairly easily. There are probably other places to do it but I found `hook_views_pre_execute()` to work pretty well:

```
function MYMODULE_views_pre_execute($view) {
  if ($view->name == 'view_name' && $view->current_display == 'page') {
    $new_count_query = db_select('some_table', 't')
      ->fields('t', array('id'))
      ->condition('some_field', 'some_condition');

    $view->build_info['count_query'] = $new_count_query;
  }
}

```

Views will convert the above query into a `COUNT(*)` at some point further down the line.

# Answer
> 0 votes
Try not to use "Content: Has taxonomy terms (with depth)" filter - use "Content: Has taxonomy term" instead and SELECT sub-query will not be used. This will dramatically increase performance of SQL-query.

---
Tags: 7, database, views
---


title: How should i code a column layout?

text:
# Question
Title: How should i code a column layout?
I'm new to Drupal and I thought a lot about planing a column layout at my frontpage. In each column there is a teaser list of nodes. I have one row with 3 columns, the next with 2 columns... I can't upload the mockup, but I hope you imagine what I'm working on. The important thing is grouping the node lists to different columns.

So what should i use to code this? Blocks? Views? Something with panels? At the moment I'm a little bit confused about all these options...

Greetings

# Answer
> 0 votes
Given the brevity of your description, it is hard to say exactly. If you want to avoid custom coding and use contrib code (always a good thing to try first, in my option), I would consider the following.

* Views Page
* manager
* List item

Panels.

There is a good tutorial on the above (free at the moment) from the good people at Lullabot. The presentation is actually done by Node One, and is one of the best I've seen.

http://drupalize.me/series/learning-page-manager

---
Tags: views, blocks, panels
---


# Question
Title: Side-by-side contact form and GMap using panels
I need a "contact us" page which has a contact form and google map side by side. Thus, I enabled the core "Contact" module and installed GMap module. I also installed Panels module and ctools module to create a page with two columns layout.

I successfully added the contact form into the left column of the panel page, but I failed to add the map into the right column. I thought I can easily add a gmap block into the column, but I could not find any block provided by the GMap module.

How can I do that ? Can I create a block which displays the map by using views.
I don't want to write custom codes.

# Answer
> 1 votes
I found a way:

1. I enabled "GMap Macro Builder" which comes with the GMap module.
2. Added a text format by enabling filter "GMap Macro expander" at the page "admin/config/content/formats/add" and named the text format as "Gmap Macro".
3. Created a map macro at the page "map/macro" to paste into a node.
4. Created a node at "node/add/page" by pasting the macro text copied from the step 3 into the node body, chose a text format "Gmap Macro" which was created from the step 2 and gave a title 'Location'.
5. Created a panel page with two columns layout and url "contact-us". Added the contact form to the left column.
6. Added the existing node "Location" created from the step 4 into the right column.
7. Created a main menu link with the path "contact-us" which is the panel page url.

Finally, I got a contact form with a google map side-by-side.

Required modules:
1. Chaos Tool Suite ( Chaos tools and Page Manager enabled )
2. Panels ( Panels only enabled )
3. GMap ( GMap and GMap Macro Builder enabled )

---
Tags: 7, panels, google-maps, emails
---


# Question
Title: Problem when using Feeds to import nodes which have a image field
I'm using feed to import nodes from a csv file. I'll try to reproduce.

**Everything works fine if I do this:**

1) I create the importer. For Mapping Settings I set:

```
ID -> Node ID
TITLE -> Title
BODY -> Body

```

*This importer will import the csv data to the **cuadros** content type*

2) I import this csv file with no problem at all:

```
ID;TITLE;BODY
83;without title;text
1084;White;text

```

**But I get a message error if I include a image for the node**

1) I create the importer. For Mapping Settings I set:

```
    ID -> Node ID
    TITLE -> Title
    BODY -> Body
    PHOTO -> Images

```

*Images is a image field of the node.*

2) I put the 2 images files in: `localhost/mysite.com/sites/default/files/photos/`

3) I import this csv file

```
ID;TITLE;BODY;PHOTO
83;without title;text;http://localhost/mysite.com/sites/default/files/photos/245c-w1000-h800.jpg
1084;White;text;http://localhost/mysite.com/sites/default/files/photos/261-w1000-h800.jpg

```

4)I get the error message you can see below.

Just in case it was a permission problem I set the **files** folder and all its content to 777, but problems stil persist

```
 The specified file temporary://filel1sCPA could not be copied, because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions. More information is available in the system log.
The specified file temporary://fileqPBtxM could not be copied, because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions. More information is available in the system log.

Invalid enclosure http://localhost/mysite.com/sites/default/files/photos/245c-w1000-h800.jpg
Invalid enclosure http://localhost/mysite.com/sites/default/files/photos/261-w1000-h800.jpg

```

# Answer
> 0 votes
problem was that I had to use the default folder for the image fied, which is **images**. I had set **photos** as the folder for the images.

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


title: How can I build a popup in drupal?

text:
# Question
Title: How can I build a popup in drupal?
I am working with Drupal 7, and I have a block generated by the Views module with titles of many articles. When the user chooses a title, I want a popup with title, body, and image to appear.

Is it possible with any module?

# Answer
you can use lightbox2 module.

And here is the description that how will you use it.
> 2 votes

# Answer
Using lightbox2 for poupup node and content type ,etc (every thing except iamges) is not standard method work but not adequate way.
If you have drupal developing knowledge i suggest you use ctools modal
ctools
automodal module
modal-forms
useful example
> 0 votes

---
Tags: 7
---