# Question
Title: front page isn't referring to front--page.tpl.php
In my template (page.tpl.php file) I have five regions/sections. Header, section#main\_prefix, section#main\_suffix, and footer. I also have these regions declared in the .info file in my theme. However, my frontpage is only displaying three of those regions; header, main and footer. I created a page--front.tpl.php file and copied/pasted the content from my page.tpl.php file and am seeing no results. Is there somewhere that I need to make a formal link to this, or does drupal automatically know that page--front.tpl.php is the front page? I have not done anything else to specify a homepage and I can't find any other files in the sub or base theme that have the layout of "header, main, footer." It's still just displaying most recent articles.

I need the section#main\_prefix to display, because it has a content block that needs to be on the homepage. This is a static block and isn't contextually dependent in any way. I'm aware that if regions don't have content in their blocks that needs to display, that they won't display. I'm also not seeing any problems in my status report.

Background info:

Aurora is my base theme. Theme related modules include:
Magic, HTML5 Tools, Modernizr, Blockify, Borealis Suite, Fences, context, Panels and Ctools. There may be more that are relevant, but I can't think of them at the moment.

I was using panels everywhere previously, but had to abandon it after it had several problems ctools and the patches I applied broke some stuff with html5 tools. I'm now trying to layout all of my pages with code and regular panels, although I'm not sure yet how I'm going to target them, maybe context?

I'm also using the Bear distro package.

**Thanks for your time and help!** This stack exchange board has been a phenomenal resource in helping me learn drupal so far.,

Cole

**ravenswoodGov.info**

```
name =  RavenswoodGov
description =  RavenswoodGov theme based on the Aurora base theme.
core = 7.x
base theme = aurora

; ========================================
; Regions
; ========================================

regions[header]       = 'Header'
regions[main_prefix]  = 'Main Region Prefix'
regions[content]      = 'Main Region'
regions[main_suffix]  = 'Main Region Suffix'
regions[footer]       = 'Footer'

; ========================================
; Stylesheets
; ========================================

stylesheets[all][] = 'stylesheets/style.css'
stylesheets[print][] = 'stylesheets/print.css'

; If installed through Bower
; stylesheets[all][] = 'components/formalize/assets/css/formalize.css'

; ========================================
; Scripts
; ========================================

; If installed through Bower
; scripts[] = 'components/formalize/assets/js/jquery.formalize.min.js'

; ========================================
; Modernizr
; ========================================

modernizr[tests][] = css_boxsizing

; ========================================
; Settings
; ========================================

settings[toggle_node_user_picture] = '1'
settings[toggle_comment_user_picture] = '1'
settings[toggle_comment_user_verification] = '1'
settings[default_logo] = '1'
settings[logo_path] = ''
settings[logo_upload] = ''
settings[default_favicon] = '1'
settings[favicon_path] = ''
settings[favicon_upload] = ''
settings[hide_recomended_modules] = '0'
settings[aurora_enable_chrome_frame] = '1'
settings[aurora_min_ie_support] = '10'
settings[aurora_html_tags] = '1'
settings[aurora_typekit_id] = '0'
settings[aurora_livereload] = '0'
settings[magic_embedded_mqs] = '0'
settings[magic_css_excludes] = ''
settings[magic_footer_js] = '0'
settings[magic_library_head] = '0'
settings[magic_experimental_js] = '0'
settings[magic_js_excludes] = ''
settings[magic_rebuild_registry] = '0'
settings[magic_viewport_indicator] = '0'
settings[magic_modernizr_debug] = '0'
settings[magic_performance__active_tab] = 'edit-dev'
settings[magic_css_excludes_regex] = ''
settings[magic_js_excludes_regex] = ''

```

**templates/system/page.tpl.php**

```
<?php if ($page['header']): ?>
  <header id="header" role="banner">
    <?php print render($page['header']); ?>
  </header>
<?php endif; ?>

<?php if ($page['main_prefix']): ?>
  <section id="main_prefix">
    <?php print render($page['main_prefix']); ?>
  </section>
<?php endif; ?>

<?php if ($page['content']): ?>
  <main id="main" role="main">
    <?php print render($page['content']); ?>
  </main>
<?php endif; ?>

<?php if ($page['main_suffix']): ?>
  <section id="main_suffix">
     <?php print render($page['main_suffix']); ?>
  </section>
<?php endif; ?>

<?php if ($page['footer']): ?>
  <footer id="footer" role="contentinfo">
    <?php print render($page['footer']); ?>
  </footer>
<?php endif; ?>

```

**templates/system/page--front.tpl.php**

```
    <?php if ($page['header']): ?>
  <header id="header" role="banner">
    <?php print render($page['header']); ?>
  </header>
<?php endif; ?>

<?php if ($page['main_prefix']): ?>
  <section id="main_prefix">
    <?php print render($page['main_prefix']); ?>
  </section>
<?php endif; ?>

<?php if ($page['content']): ?>
  <main id="main" role="main">
    <?php print render($page['content']); ?>
  </main>
<?php endif; ?>

<?php if ($page['main_suffix']): ?>
  <section id="main_suffix">
     <?php print render($page['main_suffix']); ?>
  </section>
<?php endif; ?>

<?php if ($page['footer']): ?>
  <footer id="footer" role="contentinfo">
    <?php print render($page['footer']); ?>
  </footer>
<?php endif; ?>

```

# Answer
The reason why the regions weren't being displayed is because the blocks in them had every content type checked to display in. In order for something to display on the default drupal homepage, everything has to be unchecked. I don't know why this also didn't prevent things from being displayed in search and other types of system pages, they must be considered "basic pages", but there you have it.

The homepage is a page without a content type, by default. So even if you select it to display in all content types, that means it won't display in non-content types...

In short, if you want a block to show up on the default homepage, don't check anything at all in configure/content types
> 1 votes

# Answer
In fact this is just the default behavior : Drupal displays all nodes that receive the "*promote to frontpage*" setting, in a list of teasers of all published nodes.

There are several solutions to change that.

1. In a default install, you can edit page.tpl.php as following :

```
<?php
  if($is_front){
    $title = ''; // removes 'Welcome to @site-name', or put whatever title you'd like to
    $page['content']['system_main']['default_message'] = array(); // removes 'No front page content has been created yet.'
    //OR
    $page['content'] = array(); // removes completely the 'promote to frontpage' list
  }
?>

```
2. You can create a basic page, set it as your default frontpage in *admin/config/system/site-information*, and put your some static homepage content in it.
3. You can use one of the following modules that provide customised home pages dependant on role, or other features: Front, Empty Page, Empty Front Page...
4. You can enable the **Front Page view** to display your own listing content, display it on a page, give that page a path, and set that path to be the default frontpage.
5. At minimum, you can uncheck "promote to frontpage" for any content ! But you'll lose the ability to use this flag in a custom way, in custom views i.e ...

By the way any page, be the front one or not, will display the same regions as set in your page.tpl.php except if you play with `if($is_front){}` in the .tpl or create a page--front.tpl.php. And you'll be able then to specify in *admin/structure/block* which blocks should go in each region for all pages, for all pages except `<front>`, or for frontpage only ...

So as your .info and .tpl look correct, check the blocks settings and its content.
> 1 votes

# Answer
Try this code in your template.php

```
function TEMPLATENAME_preprocess_page(&$variables) {
  if (drupal_is_front_page()) {
    $variables['theme_hook_suggestions'][] = 'page__front');
  }
}

```
> 1 votes

---
Tags: theming
---


# Question
Title: Why does Drupal run slow on localhost wamp?
I'm using an i3 8GB RAM computer and Drupal is as slow as like using some cheap hosting provider.

So what could it be? I am using a freshly installed version of D7 and just browsing through site, going to Reports takes some time and I am not even talking about clearing cache or running cron.

Also using Drush via Git Bash also runs commands slow, like simply 'drush dl libraries' and then enabling it takes like 10 seconds and I am on 100MBit line.

I did some changes to php.ini file like memory\_limit = 2G and etc. but it's as slow as if it was 128M.

# Answer
Installed Acquia Dev Desktop, runs smooth ant fast. Wamp is not production system.
> 2 votes

# Answer
In my experience, the performance difference between running Drupal on a \*NIX system VS Windows is really noticeable.

If you can, try running it on some Linux distro, either as a dual boot or virtual machine. Not only it will run faster, but it be closer to the deployment environment and help you spend less time on preparing/testing it for launch.
> 0 votes

# Answer
i too have faced same problem with wamp server..

I have solved by re-installing wamp server and enabled module\_deflate module in Apache server.

This will do..
> 0 votes

---
Tags: 7
---


# Question
Title: Unable to save data from custom drupal form
I'm unable to save the details into database after the form is submitted in Drupal 7.

Below is the code for my custom form to save the details to DB,

```
function form_module_menu() {
  $items = array();
  $items['form_module/form'] = array(
    'title' => t('Registration form'),
    'page callback' => 'form_module_form',
    'access arguments' => array('access content'),
    'description' => t('Registration Form'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function form_module_form() {
  // This form calls the form builder function via the
  // drupal_get_form() function which takes the name of this form builder
  // function as an argument. It returns the results to display the form.
  return drupal_get_form('form_module_my_form');
}

function form_module_my_form($form_state) {
  $form = array();
    // This is the first form element. It's a textfield with a label, "fName"
  $form['fName'] = array(
        '#type'      => 'textfield',
        '#title'     => t('First Name'),
        '#required'  => TRUE,
        '#size'      => 60,
        '#maxlength' => 64,
  );
  // This is the lastname form element. It's a textfield with a label, "lName"
  $form['lName'] = array(
        '#type'     => 'textfield',
        '#title'    => t('Last Name'),
  );
  // This is the email address form element. It's a textfield with a label, "email"
  $form['email'] = array(
        '#type'     => 'textfield',
        '#title'    => t('Email'),
        '#required' => TRUE, //must fill this if set to TRUE
        '#rules'    => array(
                            ),
        '#filters'  => array('trim', 'uppercase')
  );
  // This is the password and confirm password form element. It's a textfield with a label, "cpwd"
  $form['cpwd'] = array(
        '#type'     => 'password_confirm',
  );
  $form['submit_button'] = array(
        '#type'     => 'submit',
        '#value'    => t('Submit'),
  );
  $form['clear'] = array(
        '#type'     => 'submit',
        '#value'    => 'Reset form',
        '#validate' => array('my_module_my_form_clear'),
  );
  //print l('return to main home page', '<front>');
  return $form;
}

//Rebuild the form
function my_module_my_form_clear($form, &$form_state) {
    $form_state['rebuild'] = TRUE;
}

function form_module_email_validate($element, &$form_state, $form) {
  //email validation not working how to validate email
  $mail = $form_state['values']['email'];
  if (strpos($mail,'@') !== true) {
    form_error($element, t('Please enter a valid email address.'));
  }
  else{
    form_error($element, t('Please enter a valid email address.'));
  }
}

function form_module_my_form_submit($form, &$form_state) {
    drupal_set_message($form_state['values']['fName'].$form_state['values']['lName'].$form_state['values']['email']);
    $sql = "INSERT INTO {customers} (first_name,last_name,email_addr,password) VALUES('%s', '%s', '%s' , '%s')";
    db_query($sql,
        array('%s' => $form_state['values']['fName']),
        array('%s' => $form_state['values']['lName']),
        array('%s' => $form_state['values']['email']),
        array('%s' => $form_state['values']['cpwd'])
    );
    drupal_set_message(t('Thanks for registering with us. You will receive an email shortly to activate your account.'));
    //after successfully saved how to send mail to user with his login details
}

```

The submit handler is called and the values are displayed.but in database all rows are filled with '%s'. I new to working in Drupal. How to store passwords and how to save the data and send an email to the user registering..

# Answer
As stated by @Molot this should not be used generally. Recommended methods would be db\_insert and db\_merge.

Placeholders are layed wrong, they need to be in single array. Use

```
 $sql = "INSERT INTO {customers} (first_name,last_name,email_addr,password)
         VALUES(:fName, :lName, :email , :cpwd)";
db_query($sql,
    array(
      ':fName' => $form_state['values']['fName'],
      ':lName' => $form_state['values']['lName'],
      ':email' => $form_state['values']['email'],
      ':cpwd' => $form_state['values']['cpwd'],
   )
);

```
> 2 votes

# Answer
As stated by @Molot and @user20301 using the recommended method db\_insert i have created this method for saving the values to db,

```
$values = array(
    'fname' => $form_state['values']['fName'],
    'lname' => $form_state['values']['lName'],
    'email' => $form_state['values']['email'],
    'password' => $form_state['values']['cpwd']
);
$insert = db_insert('customers')
    -> fields(array(
    'first_name' => $values['fname'],
    'last_name' => $values['lname'],
    'email_addr' => $values['email'],
    'password' => md5($values['password']),
))
->execute();

```

this works fine for doing the insert operation..thanks..
> 0 votes

---
Tags: forms, database
---


# Question
Title: Form Validation. Ensure Placeholder is not submitted value
I have a Drupal registration form with a placeholder set on a first name field. I am trying to get the form to check so that if the placeholder value is the same as the submitted value it will give an error asking them to be sure to enter their first name. Here is my code:

```
function mytheme_form_alter(&$form, &$form_state, $form_id){
  if ($form_id == 'user_register_form'){
    $form['field_first_name']['und'][0]['value']['#default_value'] = t('First Name');

    $form['field_first_name']['und'][0]['value']['#attributes']['onblur'] = "if (this.value == '') {this.value = 'First Name';}";
    $form['field_first_name']['und'][0]['value']['#attributes']['onfocus'] = "if (this.value == 'First Name') {this.value = '';}";
    // Alternative (HTML5) placeholder attribute instead of using the javascript
    $form['field_first_name']['und'][0]['value']['#attributes']['placeholder'] = t('First Name');

    $form['#validate'][] = 'parenting_validate_register_form';

    $form['actions']['submit']['#value'] = t('JOIN US FREE');
  }
}

function mytheme_validate_register_form(&$form, &$form_state) {
  if ($form_state['values']['field_first_name'] == 'First Name') {
    form_set_error('firstname', t('Please enter your first name.'));
  }
}

```

So the problem I am having is that with the above, every submission is throwing the error. Even if something other than "First Name" is entered. For some reason `if ($form_state['values']['field_first_name'] == 'First Name')` is returning true no matter what the "field\_first\_name" value is.

I've looked into using https://drupal.org/project/clientside\_validation, but it just seems like overkill for what I'm trying to do.

Thanks for any help.

# Answer
> 0 votes
In your code these two lines may make issue. remove/comment these lines and try.

```
$form['field_first_name']['und'][0]['value']['#attributes']['onblur'] = "if (this.value == '') {this.value = 'First Name';}";
$form['field_first_name']['und'][0]['value']['#attributes']['onfocus'] = "if (this.value == 'First Name') {this.value = '';}";

```

---
Tags: users, forms
---


# Question
Title: Adding labels to a Webform multistep form
I have a form with 3 steps using the Webform module. Is there a way for me to identify what step I'm in so I can style it separately? What I'm after is to place text like *Step 1 \> Step 2 \> Step 3* while highlighting the current step using CSS.

So far, I can't find any ID or class which tells me what step I'm in.

**EDIT**: Not that important but any suggestions on how I can place the text *Step 1 \> Step 2 \> Step 3?* I was thinking of adding the text in `body` but maybe there's another/better way? Just curious.

# Answer
Just add a fieldset around each step with the labels "step 1-3"
> 3 votes

# Answer
You can also use variable\_set to track your current step # and add increments as you go along...

`if(variable_get('stepno')){`

````
variable_set('stepno',variable_get('stepno')+1);
drupal_set_message('step: '.variable_get('stepno'));

````

`} else {
 variable_set('stepno',1);
 drupal_set_message('Step 1');
}`
> 0 votes

# Answer
At the edit side, you can rename the page break also, to keep track in the admin side what step you're editing — I'm using webforms 4 here.
> 0 votes

---
Tags: webforms
---


# Question
Title: exposed filter default values from user fields
How can i set the default value of exposed filter for a view with the current logged in user profile checkboxes?

There can be multiple choices.

Thank you

# Answer
Try like this.

```
function custommodule_form_views_exposed_form_alter(&$form, &$form_state){
  if($form['#theme'][0] == 'views_exposed_form__article__page_1'){
      $form['ct']['#options']['All'] = 'All Article';
  }
}

```
> 0 votes

# Answer
```
 function mymod_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
 if (! _mymod_isFormSubmit()) {
 //exposed filters form hasn't submitted so I am using values from user entity
 global $user;
 $wrapper = entity_metadata_wrapper('user', $user);
 foreach(_mymod_getFiltersMapping() as $filterName => $fieldName ) {
  $tids = array();
  foreach($wrapper->{$fieldName}->value() as $term) {
    $tids[] = $term->tid;
 }
 $form_state['input'][$filterName] = empty($tids) ? 'All' : reset($tids);
}

```

} }

i have this code but did not works..
> 0 votes

---
Tags: views
---


# Question
Title: feeds not update exist node and only add them
I am using feeds module in order to import node from csv file, The mapping equation is

and the updating criteria set to

and my csv file contain this

```
guid,field_type,field_model,field_cost,
1,type1,model1,cost300,
2,type1,model2,cost300,
3,type1,model3,cost300,
4,type1,model4,cost400,
5,type1,model5,cost5,
6,type6,model6,cost6,
7,type7,model7,cost7,
8,type8,model8,cost8,
9,type9,model9,cost9,
10,type10,model10,cost10,

```

**my problem is every time i import csv file the recorded added to my node (not update or replace), where is the problem?**

# Answer
> 3 votes
The problem is here `NOT UNIQUE field set`.after set a field as a unique field every time the nodes will update(replaced).
To set a field as unique click a button below not set as unique , check unique checkbox and update then it will set as unique.

---
Tags: 7, feeds, nodes
---


# Question
Title: howto use tokens as "views filter criteria"
I want make a photo gallery with Drupal and i want show photos uploaded by user in user's page. I tried add token `[node:author:uid]` to `Content: Author uid` as filter criteria, but that shows an error:

```
Unable to find user: [node:author:uid]

```

how to add a token to views filter criteria? thanks :)

# Answer
Try adding a contextual filter - Content: Author uid and make it like below. I think this is what you need.
> 3 votes

---
Tags: views, tokens
---


title: Cache drupal private images

text:
# Question
Title: Cache drupal private images
Is there a way to cache drupal private images in client browser? I have a website with private profile images that are used many times and I want to cache them even for a very few time. How can I do that?

Thanks

# Answer
I finally found how to handle it : there is a hook\_file\_download where i can add and set header for the file :

```
function mymodule_file_download($uri){

// Getting file info
  $info = image_get_info($uri);

  // For images files
  if(isset($info['mime_type']) && strpos($info['mime_type'], 'image/') === 0){
    // cache max-age : 1 day
    // expire-date : now + 86400 s
    // etag using a hash of the file size variable
    return array('Cache-Control' => 'max-age=86400, private',
                 'Expires' => gmdate('D, d M Y H:i:s', time() + 86400) .' GMT',
                 'Last-Modified' => gmdate('D, d M Y H:i:s', time() - 86400) .' GMT',
                 'ETag' => strtr(md5($info['file_size']), 0, 10));
  }
}

```
> 2 votes

# Answer
From https://drupal.org/node/1844126#comment-8215137, a version that does not grant access to all files:

```
/**
 * Implements hook_file_download().
 */
function mymodule_system_file_download($uri) {
  if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
    $ifs = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
    $file = db_select('file_managed', 'fm')
      ->fields('fm')
      ->condition("uri", $uri)
      ->execute()
      ->fetchAssoc();
    if (!empty($file)) {
      $modified = $file['timestamp'];
      if ($modified < $ifs) {
        header($_SERVER['SERVER_PROTOCOL'] . ' 304 Not Modified');
        exit();
      }
    }
  }
  // Don't return headers to avoid granting access to all files.
  $max_age = variable_get('page_cache_maximum_age', 0);
  drupal_add_http_header('Cache-Control', 'private, max-age=' . $max_age);
  drupal_add_http_header('Last-Modified', gmdate(DATE_RFC1123, REQUEST_TIME));
  drupal_add_http_header('ETag', strtr(md5($uri), 0, 10));
}

```
> 2 votes

---
Tags: 7, caching
---


title: Facebook like box as popup

text:
# Question
Title: Facebook like box as popup
I have the facebook like box in a block position and i want to make this block popup for first time visitors only. The popup will open only if the user visits the website for first time and will open once for every visitor.

Is it possible to implement this feature with existing modules? I am not a programmer.

Thank you

# Answer
From Comments:

If you want to do a popup for first time visitors, try the Popup announcements or Popup on load modules.
> 3 votes

# Answer
This can be done easily if you have a control to find the visitor is first time coming to your site.

Set a persistent cookie once the use visists your site for the first time. Example Set a cookie called persistCookie to true/1. If the user visits for the next time check the cookie (persistCookie) exists/enabled to true. `var persistCookie = getCookie("persistCookie");`

With a simple condition below you can have a control over the fb like popup,

```
/* Check the cookie exists in IN your Domain*/
if (persistCookie) {
    /*If cookie exists check the autoopen false*/
    $("#dialog").dialog({
        autoOpen: false
    });
} else {
    /*If cookie exists check the autoopen True*/
    $("#dialog").dialog({
        autoOpen: true
    });
}

```

Sample Demo listed here.
> 1 votes

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


# Question
Title: Give permissions to a non-admin user for custom rules components
I have a view, format: table; and a few fields:

1. Bulk operations: Content
2. Content: Title
3. Content: Price
4. Content: Stock 1 (Stock 1)
5. Content: Stock 2 (Stock 2)
6. Content: Stock 3 (Stock 3)
7. Global: Math expression (Total Stock)
8. Global: Math expression (Total Price)

At `Configure field: Bulk operations: Content` section `SELECTED BULK OPERATIONS` i selected **Delete item** and another 3 options (rules components). These are: **new\_value\_for\_stock\_1**, **new\_value\_for\_stock\_2**, **new\_value\_for\_stock\_3**, **new\_value\_for\_price**.

Admin user can see all these options (rules components), but a non-admin user (eg. an **editor** role) can see only **Delete item**.

Is there a method (trick) to give permissions for a non-admin user (role)?

I enabled **Actions permissions (VBO)** and in `Administration » People » Permissions` are displayed only default actions (eg. EXECUTE Delete item). The custom rules components aren' displayed there.

# Answer
You can set permissions on rule component page in fieldset at the page bottom.

There is an option "Configure access for using this component with a permission."
> 3 votes

---
Tags: users, views, actions
---


# Question
Title: Using clientside_validation project, default validation plugin message not being overridden for states dependent field
I am currently using clientside\_validation with clientside\_validation\_states to validate conditionally required fields.

The issue I am experiencing is when the conditionally required element is invalid (empty), it is showing the generic "This field is required" (from jQuery.validation defaults) instead of using a message that is typically seen (and shows on all other, non-conditionally required fields) - for example, "First Name field is required".

I am using a custom errorPlacement method, but I'm not sure that it matters:

```
    // custom error placement
    Drupal.clientsideValidation.prototype.replaceLabel = function (error, element)  {
      var label, origLabel;
      var wrapperClass = 'formReplacedLabel';
      var WrapperEl = 'span';
      label = element.siblings('label');
      if (label.find('.form-replaced-label').length === 0) {
        label.wrapInner("<span class='form-replaced-label'></span>");
      }
      label.addClass('labelError');
      label.prepend(error);
    };

```

So, the error being passed (for the states dependent control) to the custom errorPlacement method is just the default `$.validator.messages.required` instead of what is passed for the other controls. I can't just change `.messages.required` to something that is for this field specifically either, as I have several forms with state dependent fields.

I have attached an animated gif that I think can explain the issue better than I do.

# Answer
> 1 votes
Turns out this is a bug. The hot fix is to add the `$message` argument to the `_clientside_validation_set_equal()` call on clientside\_validation\_fapi.module. So that it looks like: `_clientside_validation_set_equal($name, $title, $params[0], $js_rules, $message);`.

I've started an issue and submitted a patch https://drupal.org/node/2140163

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


# Question
Title: Getting group posts in og's home page view
I'm theming views-view--og.tpl.php, hoping to change the default group listing table into something a bit more attractive.

I'm looping through the $rows I have available, and for each of them I'm loading a $group\_node object and creating a div with some specific content, such as the group's mission etc. I'd also want to present the lastest 2-3 group posts for each of the groups i'm fetching in $rows, along with their autoring and date information.

If it makes it any clearer, here's what i'm doing:

```
<?php
<?php if ($rows): ?>
    <?php if (drupal_get_path_alias(implode('/',arg())) == 'og') { ?>
        <div id="group-boxes">
        <?php foreach($variables['view']->result as $node) { ?>
            <?php $group_node = node_load($node->nid); ?>
            <!-- Some HTML using the $group_node data goes here -->
        <?php } ?>
        </div>
    <?php } else { ?>
        <div class="view-content">
            <?php print $rows; ?>
        </div>
    <?php } ?>
<?php elseif ($empty): ?>
<div class="view-empty">
  <?php print $empty; ?>
</div>
<?php endif; ?>
?>

```

How can I load all group posts related to a certain group node, and can this be done from the og home page (path /og), as I understand, it's considered outside of group context?

Help will be much appreciated,

Avner

# Answer
> 1 votes
I recommend creating a whole new view, which would list the three most recent posts for the group passed in the argument.

To make it work together with your existing og view, you'll want to attach the new view to your group content type using one of Viewfield, Views Field View and View reference modules.

For example, using Viewfield; to the group node type add a hidden View field called Recents. Set it to "Always use default value". Set the default value to the recent posts view. The argument is "%nid". Exclude its display from node teaser, full view etc.

In the group view, then, along with group name and mission, also add Attrview as a field. Good luck!

# Answer
> 0 votes
Using pagemanager makes this more easy. Use the default view 'og content' that comes when installing og and set format, fields, sorting etc as you like.

In pagemanager edit the page node\_view and make sure there is a selectionrule 'This panel will be selected if Node being viewed is an OG group.'

Then you can use the og content views for displaying stuff and it works just like creating 'normal' views pages, with all benefits views gives.

Pagemanager is installed by ctools, which is necessary for og. You can create and use multiple (group)views on a group page this way.

This is afaik the default approach for displaying ogcontent. In CSS you can use the panel id selector to style specific to these pages.

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


title: Action on every nth node creation

text:
# Question
Title: Action on every nth node creation
I have a content type of event. I need to send all users an email after each 5th events saved, listing this 5 recently created events. What would be the most proper way to do that? I am tending to use `hook_node_insert` but I'm not sure how to check if it is the 5th node after the last email sent.

# Answer
> 7 votes
You could run an EntityFieldQuery on hook\_node\_insert to count all of the nodes of type event and then see if that count plus one (because the new node isn't saved to the DB yet) is divisible by five. Something like this:

```
function mymodule_node_insert() {
  $query = new EntityFieldQuery();
  $result = $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'event')
    ->execute();
  $count = (count($result['node']) + 1);
  if (!($count % 5)) {
    // Generate/Send your email
  }
}

```

Note that the code above is totally untested.

# Answer
> 0 votes
You can use a combination of the Rules module and the Goals and Tasks module.

---
Tags: 7
---


# Question
Title: Simplenews Scheduler - only send newsletter when attached EVA view contains results
Simplenews Scheduler is working well for me to send a weekly email which contains an attached view (using EVA) of nodes.

I would like the newsletter to only send if the attached view contains nodes, so that empty newsletters are not sent.

I can see that this should be possible using the 'Additionally only create newsletter edition if the following code returns true' field on the Newsletter \> Send newsletter according to schedule page. I am currently using this (which always produces a newsletter regardless of whether nodes are displayed in the view):

```
if(views_get_view('job_type_c_list')) {
      return true;
}

```

I have tried using the overall length of the node body to try to work out if a view is present. (I don't know if the tokens can be used in this field or not):

```
if(views_get_view('job_type_c_list')) {
     $myvar = [node:body:?];
     if(strlen($myvar) >= 30) {
           return true;
      }
}

```

When i was working with PHP in the body of the node I was able to evaluate whether EVA was returning nodes by using

```
<?php
    $view = views_get_view('job_type_c_list');
    $printedview = $view->preview('default');

    $myvar = (string)$printedview;

    if(strlen($myvar) >= 1000) {
           print "VIEW ATTACHED";
    }

    else if(strlen($myvar) < 1000) {
           print "NO VIEW ATTACHED";
    }
?>

```

The above code is clearly not the most elegant, but it worked in the node itself. Unfortunately it didn't work in the 'Additionally only create newsletter edition if the following code returns true' Simple news scheduler field.

I have struggled with this for quite some time and would really appreciate some help. Code suggestions would be great, but failing that knowing 'If I can use tokens in the field?' and 'why does the PHP in this field behaves differently to PHP the node itself?' would also be very helpful.

I have had an issue open in the module issues page for a few days now, but it has not received any responses.

# Answer
> 0 votes
did you find out a way to do it? In your example, using views\_get\_view will always return true, because even if the view has no result, the result of the function will be an object, so will not be empty. If you're using views\_get\_view, you will always have a `<div>` inside. You should get the view, then do a preview and then check if there is results or not.

Like this:

```
 $view = views_get_view('view_id');
 $print_view = $view->preview('display_id');
 if(!empty($view->result)) {
   print $print_view;
 }

```

I would be happy to know if you found a solution to this because I will face the same problem in a couple of days, thanks!

---
Tags: 7, emails
---


title: Organic groups and Workflow

text:
# Question
Title: Organic groups and Workflow
How can I create a separated workflow for a content type like "Article" for each organic group?

For example:

* "Math Group" has the roles "Author," "Head."
* "Article" nodes created by users with the "Author" role in "Math Group" will be visible only by users with the role "Head."
* Users with the "Head" role will review "Article" nodes, and then publish it or send it back to "Author" for improvement.

How can I implement it with OG and Workflow?

# Answer
You create a workflow state called "review" and set it so it is only accessible by Head users. Also set the states so any author can only put workflows into this "review" state - only Head users can actually change this to other workflow states.

So, the Head role can access the Workflow summary in order to review all the article group nodes which have been created in the review state.

If the Head approves it, he can change the workflow state to published which is accessible to all.

If the Head denies, he can change the workflow state to Needs work, which will mean the content remains unpublished.

If you want this to go back to the original author you can set this up with an email using actions / triggers or use the rules module.
> 2 votes

# Answer
If you want to set workflow transition permissions with OG group roles instead of global roles, you can use the OG Workflow module.
> 0 votes

---
Tags: 7, organic-groups, workflows
---


title: Dashboard - empty blocks are shown

text:
# Question
Title: Dashboard - empty blocks are shown
I had a some blocks on the dashboard page. Then I created a new role with fewer permissions and wanted to show only a couple of them on the dashboard. I edited all blocks and restricted the access by role.

Now all the blocks with restricted content are still visible in the dashboard but they all have the "(empty)" text on it.

How can I get rid of these blocks completely ?

# Answer
There is a bug in dashboard.module.

Quick and silly solution: disable, uninstall, enable and reconfigure again the Dashboard module. Remember: You will lose all dashboard settings you made :)
> 0 votes

# Answer
Perhaps you can find an answer on my similar question: How to get rid of empty blocks on the dashboard?. I solved my problem by deleting the bloks directly from my database.
> 0 votes

---
Tags: 7, dashboard
---


title: No available translations found

text:
# Question
Title: No available translations found
I've gone ahead and installed Localization Update, Localization Client, Language Switcher Dropdown, and the Language Icons modules. I've also enabled the Locale and Content Translation modules.

I've added two languages to my site (Finnish and French). According to the Translate Interface (Configuration --\> Translate Interface), all of my modules are up to date for translations. However, the Drupal Core (7.24 it says, even though I haven't updated to 7.24 yet, still on 7.23), says "No available translations found" for both Finnish and French.

Just wondering if anyone has any idea on how to fix this? I haven't tried manually downloading and installing the .po files yet, as that's not really a solution for me, as I will be unable to do this manually for all of our clients.

Just wanted to add that I've tried this now on a few different setups and I still get the same thing happening on each one. I also tried one machine from a fresh install using 7.24, and still get the problem.

# Answer
> 1 votes
I figured out the reason it wasn't working. It's a conflict with the Update Manager module. If that module is installed, Localization Update looks for the newest possible version as returned by that module, instead of looking for the installed version on the system. Because of this, it was looking for 7.24, which doesn't have any translations attached to it as of yet.

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


# Question
Title: Configuration settings in filedepot for folders
How to setup permissions in filedepot module?

I have 2 users like A and B.

User "A" can create the folders and he can upload the files into that folders, but folders and files should not show or share to user "B". User "B" be follow the same functionality.

Only user can view the owned files.

# Answer
Is this a job for the Content Access module?

> This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.
> 0 votes

# Answer
To make this happen,someone with "Administer Filedepot" rights (in /admin/people/permissions), needs to set up top level files for user A and user B (by clicking on the New Folder button). Then click on A's folder in the right-hand pane and click "Permissions". That brings up a dialog that you can use to assign permissions to specific users. (Select user A and check the box for Folder Admin then delete any other access records.) Repeat for User B.

From then on, each User will be able to upload and download files in their own folders and see no one else's.

You will also want to give authenticated users "Access Filedepot" rights in /admin/people/permissions or set up a role with those rights and assign A and B to that role.
> 0 votes

---
Tags: 7, users
---


title: Features menu import/export

text:
# Question
Title: Features menu import/export
I am having an issue with exporting my main menu with the features module. I go to features \> module\_name \> recreate \> menu\_links and then check all the links that I want. Once I import the feature on a fresh instance, not all of the menu links show up. If I go to features \> module\_name \> overridden \> menu\_links all of the links show up there but when I click revert changes, nothing happens

# Answer
> 2 votes
This is a couple months late, but I encountered the same issue and wanted to answer this in case someone runs into the same problem.

Basically, Features will not show menu links unless the link path is identical. So, the paths on the site you're importing to have to be identical to the ones from you're exporting from. If they are different, nothing shows.

If you open up the links.inc file you'll see:

```
 $menu_links['menu-primary:node/1'] = array(
   'menu_name' => 'menu-primary',
   'link_path' => 'node/1',

```

You can manually modify the link path to make things show up, but obviously this isn't ideal. Hopefully this gets addressed down the road...really a killer in my opinion.

---
Tags: routes, navigation, features, importing-exporting
---


# Question
Title: Stop exposed filters from rewriting url to begin with taxonomy/term/all
I have various views that show a limited range of nodes. For example going to collections/country-animals shows nodes with the taxonomy term 'country-animals'.

I have exposed filters enabled on these views, but unfortunately using an exposed filter rewrites the whole URL ignoring the fact that the user was viewing 'country-animals' and wishes to refine the current view by the terms selected. For example refining by 'gold' rewrites the URL to taxonomy/term/all?field\_classification\_metals\_tid\[\]=89 and shows all nodes with the taxonomy term of 'gold' instead of nodes with the taxonomy term of 'gold' and 'country-animals'.

If I take the URL of the page I was on and combine it with the end of the URL that exposed filters creates (collections/country-animals?field\_classification\_metals\_tid\[\]=89) I get exactly the view I want all the 'country animals' refined by 'gold'.

How do I make the exposed filters use the correct URL automatically instead of starting each URL with 'taxonomy/term/all'?

I get the same results with and without better exposed filters.

Here is the view settings page:

I am using Drupal 7 and Views 7.x-3.7

# Answer
Assuming Drupal 7.x and Views 3.x.

Edit the View. In the filter config, make sure the "Allow multiple selections" option is ticked. Without that, you've configured the filter to only allow a single option per filter.

If "country-animals" is setup as a contextual filter, you'll need a patch from this issue to allow multiple terms.

Hope that helps.
> 1 votes

---
Tags: 7, views
---


# Question
Title: Cant display dropdown values on drupal commerce review page
I have a some dropdown fields on on my commerce checkout page where the key is different than the value. I need this to be the case, because at checkout completion, I am submitting the values to an external database, and it expects the key value, not the display value.

However, I've found that the review page is listing the values (which is an uninteligble code and therefore useless to the user). I have not found a way to change this. If you inspect the array building the review page, it contains an array element 'data' which stores all the markup, and I see no way of modifying the display.

How can I display the dropdown keys on the review page?

EDIT: To perhaps make this a little eaiser: by backtracing, I found that this function

```
customer_profile_type_ui/includes/customer_profile_type_ui.checkout_pane.inc:74:function customer_profile_type_ui_pane_review($form, $form_state, $checkout_pane, &$order) {

```

was calling this one

```
commerce/modules/customer/includes/commerce_customer.checkout_pane.inc:315:function commerce_customer_profile_pane_review($form, $form_state, $checkout_pane, $order) {

```

If you examine the code there, you will see that the review pane is being populated directly from the profile object, and the profile object is only storing the values (which makes sense). So, is there any way for me to obtain the keys?

# Answer
You could use

`hook_commerce_checkout_pane_info_alter`

and set a different 'review' callback for the relevant checkout pane.

You can then control the output from your review callback.

See `hook_commerce_checkout_pane_info` for the option detail there.

You could also try theming the review page with

* `THEME_NAME_preprocess_commerce_checkout_review(&$variables) {}` or
* `THEME_NAME_commerce_checkout_review(&$variables) {}`
> 0 votes

---
Tags: commerce
---


# Question
Title: Add the user picture before the username in user listings?
I'm trying to add the user picture before the username in user listings. I've copied `theme_username` into my `template.php` and I'm trying to call `theme` with the argument 'user\_picture' in order to get the HTML that will render the picture, but the call just returns an empty string. I'm providing the uid as the argument. Where am I going wrong? Thanks.

```
function MY-THEME_username($variables) {
  if (isset($variables['link_path'])) {
    // We have a link path, so we should generate a link using l().
    // Additional classes may be added as array elements like
    // $variables['link_options']['attributes']['class'][] = 'myclass';

    // I ADDED THIS LINE

    $output = theme('user_picture', array('account' => $variables['account']));

    // ENDS

    $output .= l($variables['name'] . $variables['extra'], $variables['link_path'], $variables['link_options']);
  }
  else {
    // Modules may have added important attributes so they must be included
    // in the output. Additional classes may be added as array elements like
    // $variables['attributes_array']['class'][] = 'myclass';
    $output = '<span' . drupal_attributes($variables['attributes_array']) . '>' . $variables['name'] . $variables['extra'] . '</span>';
  }
  return $output;
}

```

# Answer
`theme_user_picture` is not a Drupal 7 function, whereas in the example you provide you are using Drupal 7's `theme_username` function code. Moreover, even in Drupal 6, `theme_user_picture` returns nothing because in that version of Drupal it's merely a placeholder and the actual themeing of the user entry is handled via the corresponding template file `user-picture.tpl.php`. This is possibly the reason your `theme` call returns nothing. Please refer to api.drupal.org to find the correct implementation for your Drupal version.

So, assuming that you are on Drupal 7, note that `$variables['account']` is not a fully populated user object and does not contain any reference to the user picture. You need to actually load the user object and give the picture some themeing in order to show it in your listing. Your code could be something like this:

```
function MY-THEME_username($variables) {
  if (isset($variables['link_path'])) {
    // We have a link path, so we should generate a link using l().
    // Additional classes may be added as array elements like
    // $variables['link_options']['attributes']['class'][] = 'myclass';

    // I ADDED THIS LINE

    //$output = theme('user_picture', array('account' => $variables['account']));
    $user = user_load($variables['account']->uid);
    if (isset($user->picture->uri)) {
      $output = theme('image_style', array('path' => $user->picture->uri,'style_name' => 'thumbnail'));
    }
    // ENDS

    $output .= l($variables['name'] . $variables['extra'], $variables['link_path'], $variables['link_options']);
  }
  else {
    // Modules may have added important attributes so they must be included
    // in the output. Additional classes may be added as array elements like
    // $variables['attributes_array']['class'][] = 'myclass';
    $output = '<span' . drupal_attributes($variables['attributes_array']) . '>' . $variables['name'] . $variables['extra'] . '</span>';
  }
  return $output;
}

```
> 4 votes

# Answer
There's a typo (`$ouput` vs `$output`) and incorrect function param (`uid` vs `account`) there.

You could try:

```
$output = theme('user_picture', array('account' => $variables['account']));

```

Note, user pictures will need to be enabled in user account config settings. (`$conf['user_pictures']`)
> 2 votes

# Answer
Instead using Register with Picture module, you can set the weight of the picture field.

Use the Registration Picture Field Weight field to adjust the display order of the picture field on the registration form. It can be a negative or positive number.

> This module exposes the 'upload picture' element to the registration form. It also gives you the ability to set a picture as required in the module settings.
> 0 votes

# Answer
What user listing are you trying create or modify? If it is the standard Drupal user listing page ('admin/people'), you can replace it with a view. If you need to have the same kind of admin functions, consider using Administration Views which give you a number of default views you can modify to add in user pictures.
> 0 votes

# Answer
The code works fine, and when I directly copy-pasted it into my theme it worked. I only had to change the name of the function slightly to match my theme, of course.

So I can only speculate on why this will not work for you, and can only offer some suggestions on narrowing down the problem.

1. You aren't naming your theme function correctly. Maybe you have a typo?
2. Your theme isn't enabled.
3. Your user configurations are incorrect.
4. Your theme registry needs to be rebuilt.
5. You put user-picture.tpl.php into your template directory but it is empty or the code in it doesn't do anything productive.

First, of course, clear your cache. Do this at admin/config/development/performance and click "Clear all caches." This will take care of #5.

Under /admin/config/people/accounts, verify you have user pictures enabled. Check "enable user pictures." Even go as far as specifying a default picture so at least something will get displayed at all times and your browser will show "broken image" placeholders. That will help with #4.

Verify /admin/appearance shows the correct configuration.

There are additional questions that need to be answered if problems persist. Is the code running at all?

Download the Devel module, enable it, and then add `dsm("the theme is being called");` to the top of your theme function. When you view your user list you should see a message box at the top of the page spammed with a line per user.

If you get nothing, the function isn't even being called. If your function is getting called, move that dsm() statement around and try to find which conditional code is happening. You can also `dsm($variables);` to see if there's a problem there, as well.
> 0 votes

---
Tags: theming
---


title: Speech API Javascript and Drupal Forms

text:
# Question
Title: Speech API Javascript and Drupal Forms
I'm using WebSpeech API to allow users speech recognition on my site. I'm using example 3 on this page: https://dvcs.w3.org/hg/speech-api/raw-file/tip/speechapi.html.

My code looks like this:

```
function _google_speech_speak_form($form, &$form_state) {
$modulepath = drupal_get_path('module','google_speech');
$form['textarea'] = array(
    '#type' => 'textfield',
    '#title' => t('Speak It'),
    '#prefix' => '<div id="api">',
    '#suffix' => '</div>',
   );
$form['button'] = array(
    '#type' => 'button',
    '#attributes' => array('onclick' => 'return (false);'),
    '#value' => t('Click to Speak'),
   );
$form['submitt'] = array(
    '#type' => 'button',
    '#value' => t('Save'),
   );
$form['#after_build'] = array('_google_speech_speak_after_build');
return $form;}

function _google_speech_speak_form_submit($form, &$form_state) {
$speechkey = $form_state['values']['textarea'];
drupal_set_message($speechkey);
echo "test";}

function _google_speech_speak_after_build($form, &$form_state) {
drupal_add_js(drupal_get_path('module', 'google_speech').'/webspeech.js');
return $form;}

```

Webspeech.js:

```
 Drupal.behaviors.[google_speech] = function(context) {
 $('#edit-button').click(function() {
  var recognizing;
 var recognition = new webkitSpeechRecognition();
recognition.continuous = true;
reset();
recognition.onend = reset;

recognition.onresult = function (event) {
  for (var i = resultIndex; i < event.results.length; ++i) {
    if (event.results.final) {
      textarea.value += event.results[i][0].transcript;
    }
  }
}

function reset() {
  recognizing = false;
  button.innerHTML = "Click to Speak";
}

function toggleStartStop() {
  if (recognizing) {
    recognition.stop();
    reset();
  } else {
    recognition.start();
    recognizing = true;
    button.innerHTML = "Click to Stop";
  }
  }
 });
 };

```

I referred to this question: How to make form buttons call only javascript? The "toggle" button is not refreshing the page (which is good) but it's also not toggling speech recognition like it should. There are no errors on the screen or in the logs. Any ideas?

# Answer
> 0 votes
To properly add JS or CSS to a form you use the `#attached` array key. See this similar question answered already here with links to documentation. Then your JS button should work.

https://drupal.stackexchange.com/a/70036/3279

---
Tags: forms, javascript
---


# Question
Title: Block/mosaic type homepage with heavily interactive menu
I wanted to know if this was possible to do for a Drupal website like this website has the main navigation how it works and interacts with the main content layout. http://goo.gl/HQ4P8H

What modules must be used to do that? I am okay if it needs .js for the 'effects', but I want to understand how it works when loading new stuff from navigation while in the same page without refresh.

Also when you hover on blocks it gives various/interactive content, menus and links. How is that done on Drupal? Is it something can be pulled of from Views and then applying jQuery to output content in that way while on hover?

So in overall I wanted to know if this can be achieved without custom php coding, because I am not programmer, if it's only .js .css and modules that would be great to know which ones.

Cheers.

# Answer
There is a module to do that, but you have to customize it. It have the animation option using filter, probably you can try to use that filter as menu or change that filter like menu using CSS.

Views Quicksand see the Demo and website using Drupal.

> Quicksand is a JQuery Plugin that provides a nice animation for filtering or reordering lists of content. Views Quicksand integrates this effect into Views. Therefore it provides a views style-plugin, which allows you to alter most settings the quicksand plugin provides.
> 5 votes

# Answer
As Bala mentioned, Views quicksand will work, however if you want them to interlock with different shapes and sizes, you'll likely need to use something like Jquery Masonry alongside quicksand. There's an API and a set of sub-modules already built for drupal.
> 2 votes

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


# Question
Title: #autocomplete_path doesn't present a "spinny thing"
I'm working on adding an autocomplete field to a node edit form using `hook_form`. The field should not be stored in the database; hence the reason I am not adding a field to the node itself.

I seem to have the required components for autocomplete to work, and I've double checked spelling errors, but I can't get a "spinny thing" (aka "throbber") to appear, and there are no attempts by the browser to retrieve data from the autocomplete path when entering data into the autocomplete field.

Javascript is working in the browser, as evidenced by a working entity reference autocomplete field.

Some code:

```
/**
 * Implements hook_menu()
 */
function cao_contenttypes_menu() {
    $items = array();

    // autocomplete
    $items['cao_contenttypes/user/autocomplete/%'] = array(
        'title'            => 'Autocomplete C&O users',
        'page callback'    => 'cao_contenttypes_cao_handler_users_autocomplete',
        'page arguments'   => array(3),
        'access arguments' => array('C&O Administrator'),
        'type'             => MENU_CALLBACK,
    );

    return $items;
}

/**
 * Implements hook_form()
 */
function cao_handler_form($node, $form_state) {
    // Fields in the node add form are merged into the array we create
    // here.
    global $user;

    // Fetch the title field.
    $form = node_content_form($node, $form_state);

    // get a list of users that are allowed to have cao
    $users = _cao_contenttypes_cao_handler_users();
    $form['c__o_user'] = array(
        '#type' => 'select',
        '#title' => 'CaO User',
        '#weight' => -20,
        '#description' => 'Choose a user.',
    );

    if (0 < count($users)) {
        dpm($users, 'users');
        $form['c__o_user']['#type'] = 'textfield';
        $form['c__o_user']['#autocomplete_path'] = 'cao_contenttypes/user/autocomplete';
    } else {
        $form['c__o_user']['#options'] = array();
    }

    return $form;
}

function cao_contenttypes_cao_handler_users_autocomplete($str) {
    if (!$str) {
        return;
    }

    // choose users from among a limited subset
    $users = _cao_contenttypes_cao_handler_users();
    $list = array();
    array_walk($users, function ($item) use ($str, &$list) {
        $comp = substr($item->name, 0, strlen($str));
        if ($comp == $str) {
            $list[] = $item->name;
        }
    });
    drupal_json_output($list);
}

```

# Answer
What you should do is change `$item` inside your `menu()` hook to be

```
$items['cao_contenttypes/user/autocomplete'] = array(
    'title'            => 'Autocomplete C&O users',
    'page callback'    => 'cao_contenttypes_ceao_handler_users_autocomplete',
    'access arguments' => array('C&O Administrator'),
    'type'             => MENU_CALLBACK,
);

```

eg, remove the trailing `%` (Drupal will add in the string for you just fine when it has one) and then inside your callback do something like this:

```
function cao_contenttypes_cao_handler_users_autocomplete($str='') {

  $list = array();
  if ($str) {
    // choose users from among a limited subset
    $users = _cao_contenttypes_cao_handler_users();
    array_walk($users, function ($item) use ($str, &$list) {
      $comp = substr($item->name, 0, strlen($str));
      if ($comp == $str) {
        $list[] = $item->name;
      }
    });
  }

  drupal_json_output($list);

}

```

eg, give `$str` a default value and always return the array of results, even if empty.

Additional comment: Consider cache()ing the output of `_cao_contenttypes_cao_handler_users()` if it is a heavyweight function.
> 1 votes

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


# Question
Title: Views with attachment - How do I exclude pagination offset on every page but the first?
I have a view with an attached view to display the first row with different fields and markup. This works perfectly except for when you start using the pagination.

When I press another page (in the pagination) to load the next group of rows, I don't want either the attached view nor the pager offset.

I've seen some solutions which rely on showing rendered nodes with a different view mode for the first row. I would very much like to find a solution which is compatible with fields instead.

My main problem is that when you've started going through the pages, the first row is always skipped. Even though that is the expected behaviour, it's not how I want it to be.

---

Here's the pager settings for the default display and the attachment display.

**Pager settings**

Default display:

Attachment display:

---

**The rendered view**

Here's how the rows are rendered on the first and the second page. The blue box represents all rows (in my case only 1) from the attachment display and the red boxes represents the rows from the default display. The number in the boxes is the row id.

Please note how row 9 is never shown.

First page:

Second page:

# Answer
> 1 votes
There is a workaround described here: https://drupal.org/comment/4109006#comment-4109006. It is for D6 but as far as I can tell it should work in D7 too. The approach seems a little odd and I didn't try it out on my own, but it might solve your problem.

---
Tags: 7, views, paging
---


# Question
Title: 7 Ubercart - Notify Customer Shipping when Product Ships
For our site, we process payments by performing a Capture on the PayPal site. Soon after, we pack and ship the order.

Does Ubercart provide a means for notifying the customer (via a button click somewhere in the admin site), via a pre-defined email, that the product has been shipped?

# Answer
> 0 votes
There is a group box on each order detail page (e.g., admin/store/orders/123) which looks like the following:

```
Update order:
ADD AN ORDER COMMENT
[                     ]

```

After entering some text here (such as, "your order has been shipped"), clicking Update sends the notification to the customer via email.

---
Tags: 7, ubercart, notifications, commerce
---


# Question
Title: Is registering a controller as a service still frowned upon in D8
In the presentation given in Portland by Kat Bailey in May, registering a controller class as a service was highly discouraged, however a lot has changed since then and I wanted to check if this is still the case.

It is well supported in the code and you can route to actions in the controller you registered via reference to the service id, such as.

```
 defaults:
   _content: 'my.controller:myAction'

```

Rather than referring to the controller class directly.

I can foresee at least a couple of use cases, primarily at the moment it allows an easy option to override / extend an entire controller via replacing the service.

The only other way I know to do that at the moment would be to register an event subscriber to override all the routes to a particular controller which would be rather long winded. Views currently overrides individual routes controller actions this way to reset routes for views with paths (which makes sense as that is more of a path by path based surgical strike).

I don't won't to start down a path that turns out to be a big D8 anti-pattern, but if service controllers are bad, what is the alternative to allow simple replacement of a controller in another module?

# Answer
> 5 votes
From a Symfony docs discussion

fabpot commented

> @lsmith77 is right. I strongly believe that this is NOT a best practice. I don't recommend it at all. That's why it's not in the book and explained in a cookbook entry.

mahono commented

> It would be nice to understand why what is (not) best practice. @fabpot: could you give some more info why you think so (or is there more information about that somewhere else?) To me most important is to learn best practices how to make my bundles customizable.

fabpot commented

> The DIC mostly helps manage "global" objects. Controllers are not global objects. Moreover, a controller should be as thin as possible. It's mainly the glue between your Model and the View/Templates. So, if you need to be able to customize then, it probably means that you need to refactor them and extract the business logic from them.

With that said, here's a blogpost arguing for controllers as services: http://pooteeweet.org/blog/1947

# Answer
> 2 votes
This session by Tim Plunkett in Prague 2013 was insightful:
https://prague2013.drupal.org/session/drupal-8-routing-method-madness

In the questions part I asked about why controllers are not services. I think the reply was that we get too many services..

Too bad you can't hear the questions in the video.
I have a suggestion for "homework": You have a look at the video and figure out at which minute he talks about controllers vs services. Then you add the timing to this answer :) Must be somewhere in the questions part.

Otherwise, I think the place to ask is IRC #drupal-contribute. And then extend this answer, so others can benefit from it.

# Answer
> 2 votes
I think the "best practice" for Drupal 8 will be:

1) Controllers are not services, but use either ControllerBase or the traits we're planning to build to get at "common" services. They may, optionally, use the ContainerInjectionInterface to get other services.

2) Controllers are thin enough that you wouldn't want to bother swapping them. If you really need to there's still a way to alter a route definition, akin to hook\_menu\_alter.

3) Any really significant logic belongs in a separate service from the controller, and *that* service should be unit tested. The Controller is really just glue code.

Controller services are supported and there are some cases where they're better, such as the HtmlPageController wrapper, but those are unusual. The typical case will be ControllerBase/ContainerInjectionInterface.

---
Tags: 8
---


# Question
Title: How to upload new versions of an image with the same access path?
We have two sites, one is a static HTML site. Another is an Drupal site. For example:

* www.my-html.com
* www.my-drupal.com

On the my-html.com site, we have a dynamic image banner, links to a JPEG on the my-drupal.com site, which can be managed by the user using Drupal CMS, i.e.:

```
http://www.my-drupal.com/sites/default/files/my-html_banner.png

```

The users can upload new versions of the `my-html_banner.png` from time to time. Hopefully, when a new version of the image is uploaded on `my-drupal.com`, it will be refreshed on `my-html.com`.

However, the newer versions of the .png will end up with different filenames in `sites/default/files`, i.e.:

```
my-html_banner.png
my-html_banner_0.png
my-html_banner_1.png
...

```

Is there a way to use a fix path to refer to the latest version of a uploaded image? Or is it possible to config Drupal to replace existing image if the uploaded image name is identical?

# Answer
> 0 votes
You can try the Upload File Replace module, This module solves that problem by swapping the names of the older and newer file so that the newly uploaded file will retain its original name.

> This is a small utility module that automatically stops Drupal from renaming new files upload via filefield CCK. When 2 files with the same name exist, the older files will be renamed.

---
Tags: media, files
---


# Question
Title: How should I use hook_field_extra_fields()?
I just found out about `hook_field_extra_fields()`, but the documentation doesn't really tell me how to use it.

Where is the extra-fields output generated?

I tried hard to understand the Node and Poll modules, but I can't figure it out. I also tried to add a custom field formatter.

# Answer
`hook_field_extra_fields()` is invoked by \_field\_extra\_fields\_pre\_render(), which is a pre-render function used by field\_attach\_form(), and field\_attach\_view().

```
/**
 * Pre-render callback to adjust weights and visibility of non-field elements.
 */
function _field_extra_fields_pre_render($elements) {
  $entity_type = $elements['#entity_type'];
  $bundle = $elements['#bundle'];

  if (isset($elements['#type']) && $elements['#type'] == 'form') {
    $extra_fields = field_info_extra_fields($entity_type, $bundle, 'form');
    foreach ($extra_fields as $name => $settings) {
      if (isset($elements[$name])) {
        $elements[$name]['#weight'] = $settings['weight'];
      }
    }
  }
  elseif (isset($elements['#view_mode'])) {
    $view_mode = $elements['#view_mode'];
    $extra_fields = field_extra_fields_get_display($entity_type, $bundle, $view_mode);
    foreach ($extra_fields as $name => $settings) {
      if (isset($elements[$name])) {
        $elements[$name]['#weight'] = $settings['weight'];
        // Visibility: make sure we do not accidentally show a hidden element.
        $elements[$name]['#access'] = isset($elements[$name]['#access']) ? ($elements[$name]['#access'] && $settings['visible']) : $settings['visible'];
      }
    }
  }

  return $elements;
}

```

Using those functions, you should not invoke the hook directly. Those functions are already used for entities that Drupal knows; if you are implementing a field for nodes, all you need to do is implementing the hook.

An example of `hook_field_extra_fields()` implementation is mollom\_field\_extra\_fields().

```
function mollom_field_extra_fields() {
  $extras = array();
  $forms = array_flip(db_query('SELECT form_id FROM {mollom_form}')->fetchCol());
  foreach (mollom_form_list() as $form_id => $info) {
    // @todo Technically, an 'entity' does not need to be a Entity/Field API
//   kind of entity. Ideally of course, developers should use fieldable
//   entities, but contributed/custom code may not. It is not clear whether
//   registering extra fields for non-existing entities/bundles can break
//   anything, so leaving it this way for now.
    if (isset($info['entity']) && isset($forms[$form_id])) {
      // If the entity type does not implement bundles, then entity_get_info()
      // assumes a single bundle named after the entity.
      $entity_type = $info['entity'];
      $bundle = (isset($info['bundle']) ? $info['bundle'] : $entity_type);

      $extras[$entity_type][$bundle]['form']['mollom'] = array(
        'label' => t('Mollom'),
        'description' => t('Mollom CAPTCHA or privacy policy link'),
        'weight' => 99,
      );
    }
  }
  return $extras;
}

```

The effect of that code is allowing administrator users to change the order in which fields are rendered when the entity is rendered, or shown in the edit form, when the entity is edited. The *Field UI* module expose a UI that allows users with the right permission (usually administrator users) to sort those *false* fields.
> 7 votes

# Answer
This is a simple example showing how to add an additional field to the Field UI and provides an example of one way of inserting the field onto a node.

```
/**
 * Implements hook_field_extra_fields().
 */
function MODULE_field_extra_fields() {
  $extra['node']['article']['display']['extended_submitted_by'] = array(
    'label' => t('Extended Submitted By'),
    'description' => t('Provides Jumper Menu for Version Selection'),
    'weight' => 0,
  );
  return $extra;
}

/**
 * Implements hook_node_view().
 */
function MODULE_node_view($node, $view_mode, $langcode) {
  // Only add if the view mode is for a full view, although we
  // could control this via the Field UI too using 'hidden'.
  if ($view_mode == 'full' && $node->type == 'article') {
    $node->content['extended_submitted_by'] = array(
      '#markup' => '<p>This is inserted unless hidden in the field ui.</p>',
    );
  }
}

```
> 18 votes

---
Tags: entities
---


title: Problem with date formatting

text:
# Question
Title: Problem with date formatting
I've a strange problem with Date formatting in Chinese.

The  string has to appear after year(for example 2013年). The string appears in all years before 2013 and also in 2013. But if it is future year(2014, 2015 etc) then it doesn't appear.

This is the date format used.

```
Y\年 n\月 j\日

```

I am not sure if it is Drupal's problem or PHP's. And I have no clue how to debug this issue. Any kind of hint is most welcome.

# Answer
I don't know really why but I have a solution for you first put you result in a variable, ( try you result something like this Y/n/j ) then exclude variable by `/` and finally use your character.

```
$temp=date('Y/n/j');
list($y,$n,$j)=exclude('\/',$temp);
$final="$y\年 $n\月 $j\日";

```

I hope be useful for you. :)
> 0 votes

---
Tags: i18n-l10n, datetime
---


# Question
Title: Drupal Print PDF module with Chinese characters
I'm using the Print PDF module, but cannot get Chinese characters to display. I have tried DOMPDF (which displays as ?????), and TCPDF (which displays rectangles). I have tried changing all the settings (Use dompdf's Unicode Mode, dejavusans font etc...) but nothing works. What could I be missing?

I have set up mbstring in my php.ini as follows:

mbstring.detect\_order . . . . . . . . . . . . .auto

mbstring.encoding\_translation . . . . . . . .On

mbstring.http\_input . . . . . . . . . . . . . . .auto

mbstring.http\_output . . . . . . . . . . . . . .UTF-8

mbstring.http\_output\_conv\_mimetypes . .text/|application/xhtml+xml

mbstring.internal\_encoding . . . . . . . . . .UTF-8

mbstring.language . . . . . . . . . . . . . . . .Neutral

mbstring.strict\_detection . . . . . . . . . . .Off

mbstring.substitute\_character . . . . . . . .no value

EDIT: It seems that I need to add the Firefly Sung font for this to work, but I still can't figure out how with respect to Drupal. Also - it seems you can only set one font for the entire site - not one font per language, which is what I want?

Thanks

# Answer
> 0 votes
Well I sort of solved it by using @font-face directly in the template file. Not the ideal solution, but it's working.

---
Tags: files
---


# Question
Title: Where is the content of a node's body stored?
In the node table, you'll find everything except the actual body. Where can I find this body text? I'm assuming it's being stored as a blob somewhere.

# Answer
> 42 votes
I don't have a running drupal installation here, but I asked myself this very question a couple of weeks ago, and it took time to find the answer.

If I remember correctly, the body of the node is stored in the table that is used to keep the "revisions" of the node. I am not sure what its name is, but it should be something like "node\_revision" or "node\_revisions."

# Answer
> 58 votes
In Drupal 7 the body has been moved to the field\_data\_body table.

# Answer
> 9 votes
It's the "node\_revisions" table, in Drupal 5.

# Answer
> 9 votes
In Drupal 6, content of the node's body is saved in 'node\_revisions' table under 'body' field.

> node\_revisions.body

In Drupal 7, content of the node's body is saved in 'field\_data\_body' table under 'body\_value' field. In case content revisions are there then it also saves the data in 'field\_revision\_body' table under 'body\_value' field.

> field\_data\_body.body\_value
>
> field\_revision\_body.body\_value

In Drupal 8, content of the node's body is saved in 'node\__body' table under 'body\_value' field. In case content revisions are there then it also saves the data in 'node\_revision\__body' table under 'body\_value' field.

> node\__body.body\_value
>
> node\_revision\__body.body\_value

# Answer
> 6 votes
Your content types body content is saved in `field_data_body` and `field_revision_body` tables.

# Answer
> 3 votes
This is the SQL you would use (MySQL client):

```
SELECT node.nid,node.vid,type,node.title, body
FROM node join node_revisions ON node.nid = node_revisions.nid
WHERE node.title = 'some title';

```

So yes, the answer is the "node\_revisions" table in Drupal 6.

# Answer
> 3 votes
In Drupal 7, the node body is found in field\_data\_body and field\_revision\_body. New fields added using CCK (which is added to core in Drupal 7) are found in field\_config and field\_config\_instance. In Drupal6, the node body is stored at node\_revisions and fields created are saved at content\_node\_field and content\_node\_field\_instance.

# Answer
> 1 votes
I have created few new content types, and for them, the body or the description goes to column field\_description\_value of table `content_type_<type_name>` where `type_name` is the new content type's name.

# Answer
> 1 votes
In Drupal 7 its in field\_revision\_body .. if you describe that table you will see theres a col for Body summary and its a longtext type.

---
Tags: nodes
---


title: Dreamweaver and Drupal - PHP files

text:
# Question
Title: Dreamweaver and Drupal - PHP files
I am using Dreamweaver and Drupal, and I defined a site through a local server (using Acquia).

My site works fine through Dreamweaver. In the Dynamically Related Files, Dreamweaver discovers all the CSS and JavaScript files.

Dreamweaver does not *discover* any of the PHP files used by Drupal.

Does someone know how can I make Dreamweaver *discover* all the template files?

# Answer
You should go to File or Edit and under that **Preferences** and under that add the .module , .info , .js , .css and all other extensions as per your need extensions and save it .Then you would be able to open the drupal php files. Add the extension in the highlighted part of the image.
> 1 votes

---
Tags: theming
---


title: CKEditor using the website CSS

text:
# Question
Title: CKEditor using the website CSS
What I want, is that the CKEditor will use the website css, as you can see here:

**it is not the same as:**

I am using less css. I have tried to define the main less css file which imports all the other less css files together. This didn't work. Also the automatically generated css file by drupal doesn't has a solid path to put into the CKEditor CSS settings underneath the CSS file path settings.

Is there a way to make my editor use the same style as I use for the website?

# Answer
> 0 votes
**1.** Go to a random page of your drupal website
**2.** Look into the page source, there should be an CSS file generated by Drupal itself (weird long name.css) Click on it.
**3.** Create a CSS file named CKEditor.css and put it in your theme root folder.
**4.** Copy all the CSS from the temporary CSS file and paste it into your newly created CSS file named CKEditor.css
**5.** In the CKEditor configuration underneath the CKeditor CSS settings, paste the CSS file path of CKEditor.css
**6.** Clear your browser cache and you're ready to go.

# Answer
> 2 votes
LESS like SASS has to be compiled to real CSS-files.

Find out where the compiler put the CSS-files eg. by disabling css-aggregation and check the source-output of your site.
Add the paths of the css-files to your CKEditor-settings.

---
Tags: wysiwyg, theming
---


# Question
Title: Changing the number of search results per page with the core search module
What is the best way to change the number of search results per page when using the core search module?

I have both Drupal 6 and 7 sites that I would like to do this with.

In Drupal 6, the value 10 is hardcoded in `do_search()`.

In Drupal 7, the value 10 is hardcoded in the hooks, eg `node_search_execute()`, and there isn't a tag added that can uniquely identify the query for altering. The idea has been floated in the issue queue, but as of 2013-01-30, nothing has been committed yet.

In the past I have hacked core and handled upgrades with patch management using the normal methods.

# Answer
Overriding the hook implemented from the Node module is not possible because hook\_search\_execute() is invoked by search\_data() using the following code.

```
  if (module_hook($module, 'search_execute')) {
    $results = module_invoke($module, 'search_execute', $keys, $conditions);
    if (module_hook($module, 'search_page')) {
      return module_invoke($module, 'search_page', $results);
    }
    else {
      return array(
        '#theme' => 'search_results',
        '#results' => $results,
        '#module' => $module,
      );
    }
  }

```

`$module` is the parameter passed to `search_data()`. `hook_search_execute()` is similarly to hook\_form() which is invoked for the module implementing the content type, not for every module.

I was looking for a way to alter the query executed to search nodes, and the only way I found is to alter the page callback for search/node. That is the way that requires less code. Otherwise, the only alternative I can think of is implementing a search module to replace the search tab implemented for the Node module.

Since Drupal uses hook\_search\_info(), but doesn't uses `hook_search_info_alter()`, and `hook_search_info()` doesn't return much useful data (at least to help overriding the search query), I think there aren't other alternatives.
> 1 votes

# Answer
A new feature in Drupal 7 is hook\_module\_implements\_alter

You could use that to fork/override the node\_search\_execute (hook\_search\_execute) function in your own module.

e.g:

```
/**
 * Implements hook_module_implements_alter
 */
function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'search_execute') {
    // Sorry node module, no hook_search_execute for you
    unset($implementations['node']);
  }
}

```

and then implement your own copy

```
/**
 * Implements hook_search_execute
 * Override core node_search_execute here with custom implementation
 * Basically a clone of node_search_execute, but with limit variable available
 * See mymodule_module_implements_alter
 */
function mymodule_search_execute($keys = NULL, $conditions = NULL) {
  // Add new limit conf variable
  $limit = variable_get('search_result_limit', 10);
  // Build matching conditions
  $query = db_select('search_index', 'i', array('target' => 'slave'))->extend('SearchQuery')->extend('PagerDefault');
  $query->join('node', 'n', 'n.nid = i.sid');
  $query
    ->condition('n.status', 1)
    ->addTag('node_access')
    ->searchExpression($keys, 'node');

  // Insert special keywords.
  $query->setOption('type', 'n.type');
  $query->setOption('language', 'n.language');
  if ($query->setOption('term', 'ti.tid')) {
    $query->join('taxonomy_index', 'ti', 'n.nid = ti.nid');
  }
  // Only continue if the first pass query matches.
  if (!$query->executeFirstPass()) {
    return array();
  }

  // Add the ranking expressions.
  _node_rankings($query);

  // Load results, use limit variable
  $find = $query
    ->limit($limit)
    ->execute();
  $results = array();
  foreach ($find as $item) {
    // Render the node.
    $node = node_load($item->sid);
    $build = node_view($node, 'search_result');
    unset($build['#theme']);
    $node->rendered = drupal_render($build);

    // Fetch comments for snippet.
    $node->rendered .= ' ' . module_invoke('comment', 'node_update_index', $node);

    $extra = module_invoke_all('node_search_result', $node);

    $uri = entity_uri('node', $node);
    $results[] = array(
      'link' => url($uri['path'], array_merge($uri['options'], array('absolute' => TRUE))),
      'type' => check_plain(node_type_get_name($node)),
      'title' => $node->title,
      'user' => theme('username', array('account' => $node)),
      'date' => $node->changed,
      'node' => $node,
      'extra' => $extra,
      'score' => $item->calculated_score,
      'snippet' => search_excerpt($keys, $node->rendered),
      'language' => entity_language('node', $node),
    );
  }
  return $results;
}

```
> 0 votes

# Answer
To get more than 10 search results on one page in Drupal 7, I have used search\_config module. I used it's latest version '7.x-1.1-beta2'.

Once the module is enabled, you can configure the pager limit from Configuration-\>Search and metadata-\>Search settings (admin/config/search/settings) under 'ADDITIONAL NODE SEARCH CONFIGURATION' section. You will see 'Results' section there and you can specify pager limit to show more than 10 search results on one page.
> 0 votes

---
Tags: search
---


title: Image redirection problem

text:
# Question
Title: Image redirection problem
I have created a product teaser using views and included images as one of the fields (by including **\*(Products referenced by field\_product) Field: Images\*** ). In the settings for **" (Products referenced by field\_product) Field: Images "** I linked the image to **"content"**. But the result is something different. Instead of linking the image to **"original content"**, Drupal is linking it to the edit page of that content. Please help me fix this problem. I want my **"product Image"** to link to its **"original content(the product itself)"**.I Followed this procdure to create product teaser (Advanced Product Display Listing using Views).

# Answer
You can follow these steps to achieve what you want.

* Add a field in your views **Content:Nid**.
* Rearrange the field & place above added field at the top of yours **(Products referenced by field\_product) Field: Images**.
* Edit **(Products referenced by field\_product) Field: Images** & set **Link image to** `Nothing`.
* Click on **Rewrite results** & check **Output this field as a link**.
* Paste `node/[nid]` token in **Link path**.
* Save it & you are done :)
> 1 votes

---
Tags: commerce, media
---


title: D7: copy data from node to node

text:
# Question
Title: D7: copy data from node to node
I got a content type 'activities' with a text field called 'transport'. When a users submit a new activity, I want them to be able to copy data from earlier activities: just recycling data in other words.

Example: Activity1 has a field ('transport') that contains text. Activity2 has an empty field 'transport'. Is there an easy way for a user to copy the data from Activity1 to Activity2? The less clicks the better. What's the best practice?

Thanks!

# Answer
I don't know if it's the best way to do it, but if I was in this situation I will do that way: hook\_form\_alter =\> use a sql query to get the last node id of his last post, then node\_load() and in form\_alter copy the data you got from node\_load() into the new node.

This solution should work if you already have a value in at least one of the previous one.

```
function YOURMODULENAME_form_alter(&$form, &$form_state, $form_id) {
    //get your form id of the admin activity page
    drupal_set_message($form_id); //or echo $form_id; it should be activity_node_form
    if($form_id == 'activity_node_form'){
        $form['#submit'][] = 'YOURMODULENAME_submit';
    }

}

function YOURMODULENAME_submit(&$form, &$form_state){
    if(isset($form_state['values']['field_activitiy'][LANGUAGE_NONE][0]['value'])){
        if(empty($form_state['values']['field_activitiy'][LANGUAGE_NONE][0]['value'])){
           $lastNode =  YOURMODULENAME_query();

           $node = node_load($lastNode['entity_id']);
           if(isset($node->field_activitiy[LANGUAGE_NONE][0]['value'])){
                $form_state['values']['field_activitiy'][LANGUAGE_NONE][0]['value'] = $node->field_activitiy[LANGUAGE_NONE][0]['value'];
           }
        }
    }
}

function YOURMODULENAME_query(){
    global $user;

    $query = db_select('node', 'n');
    $query->join('field_data_field_activity', 'a', 'n.nid = a.entity_id');
    $query->condition('n.uid',$user->uid,'=');
    $query->fields('a', array('entity_id'));
    $query->orderBy('a.entity_id', 'DESC');
    $query->range(0,1);
    $result = $query->execute()->fetchAssoc();
    return $result;
}

```

Tell me if you got an error. PS:once you got the form\_is remove the line

```
drupal_set_message($form_id);

```
> 1 votes

# Answer
I think you should use the "Node clone" module, and make a hook to reset the fields you want to be empty.

\[Edit after comment\]

Well you say "When a users submit a new activity, ...", so that would work for future node creation. Instead of using /node/add/activity, you should use the link /node/XXX/clone.

To update existing nodes, I see two options:

* SQL request: not sure you can determine which Activity Transport mapping...
* add a select list with the list of all your "activities" (or an autocomplete field, depending of how many activities you have), on change of this list, make an AJAX call sending the activity NID as parameter. The AJAX function should return the "transport" field value of this node, then you can replace it in the current activity form.

I hope I'm understandable :p
> 0 votes

---
Tags: entities
---


# Question
Title: Update views result after unset() in views_pre_render
In `hook_views_pre_render(&$view)` I have a simple code:

```
foreach ($view -> result as $key => &$result) {
    if('some condition') {
        unset($view -> result[$key]);
    }
    if('some condition') {
        unset($view -> result[$key]);
    }
}

```

Above works OK. it unsets result row of the view. Now, in my view I am displaying 2 results per page. Currently have it outputs 10 node which means there are 5 pages.

The problem is, as you might suspect that if, for example, 2 unset results happened to be on page number, say 2, of the view, this page is still displayed in the pager. So what I have now is 2 results on page number 1, no results on page number 2 and 2 results on page number 3.

Similarly, if only 1 result is unset, I have 2 results on page number 1, 1 result on page number 2 and 2 results on page number 3.

is there a way of letting the view know that it needs to update it's structure? There is a query\_alter possible solution but I would like to avoid it if possible.

I do realise that this might not be the best way to unset results and I am open to suggestions, however i would like to keep the code in my custom module (not being fore to alter template.php).

# Answer
You may want to look at doing this in Views' hook\_views\_post\_execute():

> This hook is called right after the execute process. The query has been executed, but the pre\_render() phase has not yet happened for handlers.

as the paging happens in the handler phase, and hook\_views\_pre\_render()

> This hook is called right before the render process. The query has been executed, and the pre\_render() phase has already happened for handlers, so all data should be available.

All about the various Views hooks is available here:

https://api.drupal.org/api/views/views.api.php/group/views\_hooks/7

Also, some interesting conversation about this process and potential alternate suggestions is available here in a drupal.org issue queue "update pager count after chaning results in hook\_views\_pre\_render" as well.
> 4 votes

---
Tags: 7, views
---


title: DB - local to a friend

text:
# Question
Title: DB - local to a friend
I want to duplicate my locally hosted website to a friend's environment. He says he needs a copy of website's database. I'm a bit of a an Drupal rookie so I have no clue of how do this. We are using a code base so all the other files are in there.

I check settings.php and it says I have mysql as the driver I have drush and run the command

drush mysql-dump \> random.sql

This didn't work. I got an error saying; the drush command mysql-dump could not be found.

Please follow me through the steps of how do this. I really need to sent share this website with my friend as quickly as possible.

Thank you

# Answer
> 4 votes
To export your database, for example to migrate it, simplest option is to use Backup and Migrate module.

> Back up and restore your Drupal MySQL database and files or **migrate a site between environments**. Backup and Migrate supports gzip, bzip and zip compression as well as automatic scheduled backups.

Emphasis mine.

To do it with **Drush**, use:

```
drush sql-dump > my-sql-dump-file-name.sql

```

You need to have `mysqldump` installed in your system. In Linux, it usually can be found in *mysql*, *mysql-client* or similarly named package, and installing it should take care about path configuration etc. In Windows, it's probably already in path like `C:\Program Files\MySQL\MySQL Server 5.6\bin` (depending on where you have installed it). Make sure to add that path to system's PATH variable (My Computer -\> Properties or similar, depending on Windows version; look for "system variables", "environment variables", names like that).

# Answer
> 1 votes
I'm using the Backup and Migrate module to achieve this. With this module, you can save your database as a ZIP-file via the Drupal `Configuration > System` interface and send it to your friend. He has to import the file and install it in his local database.

---
Tags: database
---


# Question
Title: Add CSS file to certain pages only with theme.info file?
If I want to add a CSS file to certain pages only I know how to do this with the drupal\_add\_css function in the template.php file, but can you also do it with the theme.info file? Or is the theme.info only for adding CSS files globally?

# Answer
> 1 votes
Hope this will help you,

In Drupal 7 you can use **template\_preprocess\_page** or **template\_preprocess\_node** function for your requirement in **template.php** file as **Namari** suggested with **drupal\_add\_css**.

* You cant use theme.info file to particular pages. If you add the CSS in theme.info file then the CSS will included for each page. As you want to include the CSS file for particular pages so better to use **template\_preprocess\_node** OR **template\_preprocess\_page**.
* **drupal\_add\_css** : Adds a cascading stylesheet to the stylesheet queue.

```

    /**
     * Implement template_preprocess_page()
     *
     */
    function yourThemeName_preprocess_page(&$variables) {
        if (arg(0) == 'node' && is_numeric(arg(1)) && arg(1) == 123) {//check your condition here
        //you can also use $node = $variables['node']; $node is the node object where $node->nid is the node id
            drupal_add_css(drupal_get_path('theme', 'theme_name') . "/cssfilename.css");
        }
    }

```

```

    /**
     * Implement template_preprocess_node()
     *
     */
    function yourThemeName_preprocess_node(&$vars) {
        $node = $vars['node'];
        if($vars['type'] == 'my-node-type' && $node->nid == 123 ) {// check your condition
                drupal_add_css(drupal_get_path('theme', 'theme_name') . "/cssfilename.css");
        }
    }

```
* If you are checking for a node then better to use **template\_preprocess\_node** than **template\_preprocess\_page**

# Answer
> 1 votes
I think it only globally, you should do it the the preprocess page instead.

---
Tags: theming
---


# Question
Title: Translated Taxonomy terms in node creation page?
Drupal 7 multilingual website(English and Arabic):

I have a taxonomy term named "Food Category".Added some terms in it.Also i added translation for each terms .

I added a field to select the term in a content type :

LABEL : **Select List Food Category Item**

MACHINE NAME : field\_list\_items

FIELD TYPE : Term reference

WIDGET : Select list

I want to show the Arabic terms when i translate a node to Arabic.Now it is in English only.

Please advice me.

# Answer
> 0 votes
I found the solution :

***admin/config/regional/i18n/select***

```
CONTENT TO FILTER BY LANGUAGE
 Select nodes by language
 Select taxonomy terms by language

```

unselect

> Select taxonomy terms by language

---
Tags: i18n-l10n, taxonomy-terms
---


# Question
Title: Drupal commerce - how to redirect user in checkout based on form values
In my drupal commerce checkout page form function, I have created a radio list:

```
$form['accounts'] = array(
    '#type' => 'radios',
    '#title' => 'Please chose from the following options',
    '#options' => $options,
  );
```

and it does create the radio button list.

I then put some code in to the submit function to redirect if I chose option 0:

```
function subscription_pane_checkout_form_submit($form, &$form_state, $checkout_pane, $order) {
  dpm($form_state['values']);
  //$selection = var_dump($form_state['values']['accounts'], true);
  //watchdog('subscription', $selection);
  var_dump($form_state['values'], true);
  if($form_state['values']['accounts'] == 0) {  //if the user clicked 'none', go immediately to the review page
    $order = commerce_order_status_update($order, 'checkout_review', FALSE, TRUE, t('User is not any of the current accounts, proceed to review page'));
    drupal_goto('checkout/' . $order->order_id . '/review');
  }
}

```

but its always directing me to the review page, instead of moving to the next custom page (which definitely exists and is accessable, because you can reach if with the 'go back button' on the review page). I tried viewing the $form\_state\['values'\] but couldn't figure out how to do it properly

Also, when I tried using '0' instead of 0 in my if statement, then clicking next button kept me on the same page.

# Answer
I figured it out. The issue is that the value I was trying to reach is really at

```
$form_state['values']['email_verification']['accounts']
```
where 'email\_verification' is the name of the checkout page the submit button is on.
> 0 votes

---
Tags: forms, commerce
---


# Question
Title: Multiple facets are shown with Content fields with multiple words
I implemented filtering through facets and facing a very strange problem.

I have been trying a content type with a field for Region. Region contains options like North America, Latin America, Asia, etc. In my facets, it ends up looking like this (screenshot attached as well):

REGION: america asia north latin

What I am hoping is that it shows me the way I entered it in the system.

Why is it breaking at the spaces and turning "North America" into "North" and "America"?

The field type is "Text" though.

# Answer
> 0 votes
Found the solution.

I was using Search API for indexing, and within that type of field to index was set to Fulltext. I changed it to String and it got fixed.

Thanks.

---
Tags: views, search
---


title: Spliting a node into multiple pages

text:
# Question
Title: Spliting a node into multiple pages
Content type - article. I want to make articles split into multiple pages when the article itself becomes too long. For example if we have an article "how drupal works" it would be huge :), I want to split it to several pages and at some point you get "continue to page 2 of 10" and then "continue to page 3 of 10" and so on. Hope you got me and can share some ideas. Thank you in advance!

# Answer
I suggest split your text to some part with jquery and by scrolling you append(may with some effect like fadeIn .... ) another part to main part.
**I suggest you achieve this job by jquery (client side solution)**
> 9 votes

# Answer
You are looking for Smart Paging module

> Provides splitting up long Drupal content into sub pages by number of characters/words or by a placeholder HTML tag for node, user and taxonomy term entities.

**For Drupal 6**

Paging module, you can set character limit and it will automatically split in to sub pages see the below screen shot

> Break long pages into smaller ones automatically by words(or characters) limit
> 9 votes

# Answer
Well a workaround I would use would be to split it into multiple articles and combine them with a view-page (which has a pager) since you are working with views allready. Just filter out your articles on nid or some (hidden) tag. If you want them all to be the same max-size you could use https://drupal.org/project/maxlength. Add part X to title, this way its also easy for you readers to distinct the different pages.
> 0 votes

# Answer
I dont see what Views AJAX pager (which pages views result lines) has to with your article display (which is per se 1 result only). Two different things to page. But you might wish to output your "article content as a computed field". Start with a computed field that prints only the first x words of your article content field. (or up until the first page-breaker) Finish it off with a self-generated html "more link". That more link calls your view with an argument. You can use that argument in your computed field's PHP. Display the x-th part depending on your argument received.
> 0 votes

---
Tags: 7, nodes
---