# Question
Title: How to hide the "Add comment" link in the teaser?
I don't want the *Add comment* link displayed in the teaser. But the comment form should be displayed along with the content of the node which forms a part of a page.

Edit: I don't have access to the php code. I want to do it through the admin console. Is there a way I can uncheck "Add comment" from appearing in the teaser and instead appear in the full content node which forms a part of a page?

# Answer
You can accomplish this with a custom module, as I found here https://drupal.org/node/1257788

Here is the code you'll need:

```
function MODULE_node_view_alter(&$build) {
  if ($build['#view_mode'] == 'teaser') {
    // remove "add comment" link from node teaser mode display
    unset($build['links']['comment']['#links']['comment-add']);
    // and if logged out this will cause another list item to appear, so let's get rid of that
    unset($build['links']['comment']['#links']['comment_forbidden']);
  }
}

```
> 3 votes

# Answer
In Drupal 7, this can be done in your theme with the THEME\_preprocess\_node() function, for placed inside your template.php file, or inside a custom module using HOOK\_preprocess\_node() function placed inside a custom module.

```
/**
 * Implements THEME_preprocess_node().
 */
function YOURTHEME_preprocess_node(&$vars) {

  if ($vars['node']->type == 'article') {
    // Remove Add comment link from teaser.
    unset($vars['content']['links']['comment']['#links']['comment-add']);

    // Remove login/register to comment link.
    unset($vars['content']['links']['comment']['#links']['comment_forbidden']);

    // Remove comment count for nodes with comments.
    unset($vars['content']['links']['comment']['#links']['comment-comments']);

  }
}

```

Note the above code is untested... I may not have the arrays of doom structured correctly there, but you should be able to figure out the right path to the variable to unset using print\_r($vars\['content'\])

If you don't have access to your theme, the Hide Node Links contributed module may work, depending on your needs. It appears that the module disables all node links, not just the "Add Comment" link, and it does it for all view modes, not just the Teaser.
> 1 votes

# Answer
This works for me, including in template.php. I have to include the return.

```
function MYTHEME_node_view_alter(&$build){
    if ($build['#view_mode'] == 'teaser')
    {
        // remove "add comment" link from node teaser mode display
        unset($build['links']['comment']['#links']['comment-add']);
        // and if logged out this will cause another list item to appear, so let's get rid of that
        unset($build['links']['comment']['#links']['comment_forbidden']);
    }
}
function MYTHEME_links($links) {
    return theme_links($links);
}

```
> 0 votes

# Answer
If you don't have access to PHP code, you can do it through the admin console if you install and enable a module named Fix teaserlinks.

> The “Fix teaserlinks” module is a simple module that may be used to mange the visibility of the links that appear below teasers (i.e. “Add new comment”, “Log in or register to post comments”, “Read more”).

There are versions for both Drupal 7 and Drupal 8.
> 0 votes

---
Tags: comments
---


# Question
Title: How to let user add multiple sub-content fields in the main content?
If I want user to create a main content which can be able to add multiple sub-content for example I wanna do apartment renting website. User have to create the apartment details which contain these fields; Title, Description, Address, Facilities etc. As 1 apartment usually have multiple different units, user have to add their available units in the apartment node which contain fields; Unit title, room size, bedroom, bathroom, price. And they can add many units as they want. The question is what module should I use? Can I use Organic Group module or something simpler then that?

I'm new for Drupal, learn by myself from scratch, anyone please point me the direction.

# Answer
If apartment is one content type, and unit is another content type, you can use entityreference module to reference units in apartments. You will create in apartment content type - entityreference field with unlimited values, type of referenced entity would be unit content type - user will be able then to add as many units to his apartment as he wants.

You can even create a view of entity reference display, and use it for selection of available options in your entityreference field.

http://www.lullabot.com/blog/article/entityreference-multiselectors \- also something about multiselector widgets for entityreference field.
> 0 votes

# Answer
I just had a try multi selects module today but it not actually what I want. So I found a solution using field collection module to add a collection of field by set to unlimited value. :)
> 0 votes

---
Tags: 7, users, entities, organic-groups
---


# Question
Title: Multisite Drupal with Organic Groups problem.. custom /user and /user/register links for each group?
I am using Organic Groups for as a solution for Drupal Sub sites, it is working perfectly, even themes are switching via Organic groups theme but I am having problem with `/user/register` and `/user` pages.

I want to pass context to user pages like `user/groupname/register` or `user/groupname` , so how can I do it ? because `/user` currently throws me out of the currently active theme for Organic Group.

Also one more thing, the Group Id which I want to pass should be as alias?like pathauto paths.

# Answer
I would probably look at PURL for this, an API to make a part of a URL persistent. PURL itself does nothing since it's an API, but you can get started with OG Purl. Be warned, it's more advanced to be creating your own bridge like OG Purl does. A lot of motivation is required :)
> 0 votes

---
Tags: organic-groups
---


title: Image_style_url with [default_image]

text:
# Question
Title: Image_style_url with [default_image]
I am trying to print a commentator's avatar picture in the comments.tpl.php

```
<img src="
        <?php
            if ($picture) {
                print image_style_url('comment_picture', $comment->picture->uri);
                ?>"</img>

```

which works as desired. However it doesn't post the default\_picture if the user does not have a profile picture uploaded.

I've tried using \[default\_image\] but then nothing happens

```
<img src="
        <?php
            if ($picture) {
                print image_style_url('comment_picture', $comment->picture->uri);
             } else {
                print image_style_url('comment_picture', [default_image]);
            }
                ?>"</img>

```

# Answer
> 0 votes
Use below code in else condition...

```
$user = user_load($comment->uid);
print theme('user_picture', array('account' => $user));

```

OR

```
$filepath = variable_get('user_picture_default', '');
$default_image = theme('image_style', array('style_name' => $style, 'path' => $filepath, 'alt' => '', 'title' => ''));
print $default_image;

```

---
Tags: media
---


# Question
Title: how to create views with month and day in contextual filter
Let suppose I have `actor` content type, it has a birthday field (it is date ), I want get all actor that has equal month and day of birth,I want to create a views with `birthsearch/%/%` path, and then I want pass month and day to it , as exapmle `birthsearch/02/25` , it should return all actor that birthday is `25 feb`,I think contextual filter is good idea to achieve this but, by default drupal `Granularity` of date field is

>

it is means I can restrict it to year and month, but I cant restrict it to day and month,

**my question is how can I have views with month and day in contextual filter (passed to it by page Url)?**

# Answer
> 4 votes
I achieve this with below solution,
create birthday field filter in views and set it to something fix =2000-02-02(not important later it will bypass),
then in my custom module I implement `hook_views_query_alter` and change condition to what I want `"DATE_FORMAT(field_data_field_birth_date.field_birth_date_value, '%m%d') = :field_data_field_birth_date_field_birth_date_value";` and work correctly,and views page path is `sbirthdaymd/%` ( as example link will be something like `sbirthdaymd/0524` )

```
/**
 * Implements hook_views_api().
 */
function mymodule_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'mymodule'),
  );
}

/**
 * Implementation of hook_views_query_alter
 * @param $view
 * @param $query
 */
function mymodule_views_query_alter(&$view, &$query) {
    if($view->name == 'search_cast_by_birth_and_death') {
//        ym($view->query,'message');
        $url = parse_url(current_path());
        $temp = explode('/', $url['path']);
         if(!intval($temp[1]))
             $temp[1]="0406";
        if($view->current_display=='page_2'){
        $view->query->where[1]['conditions'][2]['field']="DATE_FORMAT(field_data_field_birth_date.field_birth_date_value, '%m%d') = :field_data_field_birth_date_field_birth_date_value";
        $view->query->where[1]['conditions'][2]['value'][':field_data_field_birth_date_field_birth_date_value']=$temp[1];
        }

     }
    }

```

# Answer
> 3 votes
I've just tested this with the post date field so assume it will work the same with a normal date field.

I added the field post date and then set the format to custom `d` and called the field post day.

I then added the field post date again and set the format to custom `m` and called the field post month.

These fields don't have to be visible so can be excluded from display.

I then added a contextual filter for "Content: Created day" and then "Content: Created month.

Now going to my\_view/01/12 will show post that were created on 1st December.

# Answer
> 1 votes
Building on Zhilevan's answer I was able to add the where entirely programmatically. Doing it this way also meant I had to create the join programmatically.

```
/**
 * Implements hook_views_api().
 */
function misc_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'misc'),
  );
}

/**
 * Implementation of hook_views_query_alter
 * @param $view
 * @param $query
 */
function misc_views_query_alter(&$view, &$query) {

    if($view->name == 'date_test') {

        $url = parse_url(current_path());
        $temp = explode('/', $url['path']);

        // Make sure month and date are zero padded.
        $month = str_pad($temp[1], 2, '0', STR_PAD_LEFT);
        $day = str_pad($temp[2], 2, '0', STR_PAD_LEFT);

        // Create join.
        $join = new views_join;
        $join->construct('field_data_field_date', 'node', 'nid', 'entity_id', array(), 'INNER');
        $query->add_relationship('field_data_field_date', $join, 'node');

        // Add where.
        $query->add_where_expression(0, "DATE_FORMAT(field_data_field_date.field_date_value, '%m%d') = :month_day", array(':month_day' => $month.$day));

    }
}

/**
 * Implements hook_views_pre_execute().
 */
function misc_views_pre_execute(&$view) {
    // This line outputs the generated SQL to the message area for debugging.
    dpq($view->build_info['query']);
}

```

---
Tags: views, datetime
---


# Question
Title: How do I add a date format to custom block output
I have two custom block output fields that are date

```
    function my_three_upcoming_events() {
  $output = '';
  $now_events = views_get_view_result('schedule_list2');
  $upcoming_events = views_get_view_result('clone_of_now');
  $max_events = 3;

  $all_events = array_merge($now_events, $upcoming_events);
/*   print_r ('<pre>');
print_r ($all_events);
exit();
*/  for ($i=0,$z=$max_events;$i<$z;$i++) {

    $node = node_load($all_events[$i]->nid);
    $output .='<div>' . l($node->title,'/node/'.$node->nid) . '</div>';
    $output .='<div>' .($node->body[und][0][value]) . '</div>';
    $output .='<div>' .($node->field_venue[und][0][value]) . '</div>';
    $output .='<div>' .($node->field_session_start_date[und][0][value]) . '</div>';
    $output .='<div>' .($node->field_session_start_date[und][0][value2]) . '</div>';

  }

}

```

and they output like this

2014-04-18 15:15:00 2014-04-19 21:15:00

How can I change to one of the php date formats

Thanks for any help on this

# Answer
> 0 votes
You should use date\_format (Drupal function).

---
Tags: 7, datetime
---


# Question
Title: How to fix my Fivestar widget rendered in a template file?
I have the Fivestar module installed and have made one of my node field as a Fivestar field. Now I am rendering this field in a template file.

```
  $settings = array(
              'content_type' => 'node',
              'content_id' => $variables['nid'],
              'entity' => $variables['elements']['#node'],
              'stars' => 5,
              'field_name' => 'field_rating',
              'autosubmit' => TRUE,
              'allow_clear' => FALSE,
              'langcode' => $node_language,
              'text' => 'none',
              'tag' => 'vote',
              'style' => 'average',
              'widget' => array( 'name' => 'oxygen', 'css' => drupal_get_path('module', 'fivestar') . '/widgets/oxygen/oxygen.css' )
              );
  global $user;
  $fivestar_values = fivestar_get_votes('node', $variables['nid'], 'vote', $user->uid);
  $render_form = drupal_get_form('fivestar_custom_widget', $fivestar_values, $settings);
  print render($render_form);
?>

```

The fivestar field works fine with the only exception that when there are no votes, it shows 4 stars out of five as pre-selected. But once I cast one vote it behaves properly for all users.

How to fix this?

# Answer
> 0 votes
Finally after some headbanging I found that it was occurring due to the "tag" attribute. Generally for each node type, its better to create its own tag, and that would fetch you the correct result. I was using the 'vote' tag of another content type. Hence the problem.

Hope this helps someone...

---
Tags: theming, rating
---


# Question
Title: How to append currency symbol as prefix to total sum in views calc?
I have used Views Calc module to calculate sum of all column fields. How can I append currency symbol as prefix to **Views Calc** calculated total sum?

# Answer
> 3 votes
You can achieve that in two ways CSS or jQuery

1)CSS (Note: It requires CSS2 capable browsers. )

```
td.your-views-class-name:before { content: "$"; }

```

2)jQuery

```
$('.your-views-class.name').each(function() {
  $(this).before($('<td>').text("$"));
});

```

---
Tags: 7, views
---


# Question
Title: Grant/restrict access according to node's author & moderation state
I'm trying to bypass some of the permissions set by Workbench Moderation, only under specific circumstances. For a specific content type, I need the users of a specific Role to be able to: \- View all Published nodes of that content type (this works fine as it is quite general) \- View Unpublished nodes only if the nodes 1. are related to them (through Entity Reference field) or 2. they have created themselves. \- Edit nodes only if they are related to them (through Entity Reference field) or nodes they have created themselves. This should be allowed only in a specific State.

I've tried implementing hook\_node\_access\_records() & hook\_node\_grants() hooks in my module but this doesn't seem to work. In the following example, the conditionals are different than what's mentioned above but the logic is the same:

```
function mymodule_node_access_records($node){
    $grants = array();
    if ($node->nid == 1234 && $node->uid == 99) { //(example conditions)
        $grants[] = array(
            'realm' => 'mymodule',
            'gid' => 123,
            'grant_view' => 1,
            'grant_update' => 0,
            'grant_delete' => 0,
            'priority' => 0,
        );
    }
    return $grants;
}

function mymodule_node_grants($account, $op){
    $grants = array();
    if (($op == 'view' || $op == 'update') && $account->uid == 99) { //(example conditions)
        $grants['mymodule'] = array(
            123,
        );
    }
    return $grants;
}

```

This does add a line in node\_access table where only grant\_view has a value of 1. It should just allow related users to view the specific (unpublished) node but not edit it.

UPDATE: I installed Devel node access and here are my findings for the test case above (node 1234 is Unpublished, user 99 is author):

* Test User can View the node - OK
* Test User can Edit the unpublished node (non-Published draft) - NOT OK
* Test User cannot Delete the node - OK
* Test User can Moderate the Unpublished node (allowed transitions set by WM config.) - OK

Here is what Devel actually displays on that node's view page:

* Create: *YES: by node (permissions)* \- OK
* View: *YES: view own unpublished content* \- OK
* Update: *YES: by node (permissions)* \- This should be overridden by my access module
* Delete: *NO: no reason* \- OK

How can I override this edit permission with my module? I'd eventually like to expand the functionality of this module to cover other cases as well.

# Answer
> 0 votes
Access to the 'node/%node/edit' path is done by `node_access()`. It first checks some global permissions, and then invokes `hook_node_access()` to check for explicit allows and denys. `node_node_access()` checks the permissions at admin/people/permissions, and will return `NODE_ACCESS_ALLOW` if set.

Based on your debug information, it looks like a permission is allowing the update operation, so the grants aren't being checked.

I think you need to do one of two things.

You could implement your own `hook_node_access()` that returns an explicit `NODE_ACCESS_DENY` when you need to. This will override any explicit `NODE_ACCESS_ALLOW`.

The other option is to remove the explicit edit permissions for your content type(s), and then use grants. You would have to update the logic in your hooks to cover all of the cases where someone can edit the content, and not just your special cases.

Make sure you also read up on node access rights (see also this article), as they can be confusing until you really grasp how they work. Just remember

* If using `hook_node_access()`, a `NODE_ACCESS_DENY` will override a `NODE_ACCESS_ALLOW`, but not the other way around.
* If using grants, the default is to deny to all, and then allow to some. It's early, and I can't quite remember if you can explicitly have a grant that denies one that has already been granted.

# Answer
> 1 votes
A helper module that I use for managing node access is ACL .

> The ACL module, short for *Access Control Lists*, is an API for other modules to create lists of users and give them access to nodes. It has no UI of its own and will not do anything by itself

What I suggest is that instead of handling the grants yourself, you outsource it to ACL. The module has a simple (YMMV) to use high-level API that let you grant individual users access (and revoke it).

The documentation is a little sparse, but on the ACL project page existing client projects are listed. I learnt how to use it by reading the source code of those.

Alternatively, you can read the source code of ACL to see how to do low-level manipulation of permissions.

If you end up writing your own module, the introduction to this page gives a good introduction to how Drupal's node access system works. In particular, you should be aware of:

> Node access modules always GRANT access and never restrict it. (It is a whitelisting rather than a blacklisting system.)

I understand you already use DNA (Devel Node Access), but if somebody else stumble across this: DNA (part of the Devel project) is absolutely *essential* if you are going to debug node access.

---
Tags: users, nodes, workbench
---


# Question
Title: Is there for modules the same as theme_get_setting() for themes?
I am using variable\_get('name-of-setting', 'default-value') to retrieve module/theme settings in several locations in code.

The purpose is to keep default settings in one locations preferable in .info file. I am able to this for themes:

```
variable_get('name-of-setting', theme_get_setting('name-of-setting'));

```

Here the theme\_get\_setting() retrieves the settings from the theme-name.info file:

```
settings['name-of-setting'] = some_value

```

Can i do the same for modules? What is the API to retrieve settings from module .info file? If not, how do you handle module default settings to avoid it scatter around code?

# Answer
You're probably looking for `drupal_parse_info_file()`

> Parses Drupal module and theme .info files.
>
> Info files are NOT for placing arbitrary theme and module-specific settings. Use variable\_get() and variable\_set() for that.

Pay attention to the second paragraph - it applies to you :)
> 4 votes

---
Tags: 7
---


# Question
Title: How can I preserve nids during a migration?
I'm writing a migration using migrate/migrate\_d2d to import nodes from one Drupal 7 installation to another.

Currently there are a lot of links on the web that point to articles using the example.com/node/\[nid\] url. Since the site I'm importing to will eventually replace the current one, I need to make sure those links still point to the correct articles.

How can I preserve nids during the migration, so that the old links that use /node/\[nid\] still point to the correct articles?

Alternatively, how can I easily make 500,000+ URLs to old nids redirect to their newly migrated counterpart?

# Answer
> 4 votes
This is actually easy to do. In the prepare() function of the node migration class, just set the nid and is\_new to true:

```
public function prepare($node, $row) {
  // Preserve old nid so that old links to nodes using /node/nid still work
  $node->is_new = TRUE;
  $node->nid = $row->nid;
}

```

# Answer
> 2 votes
Hmmm... with my limited knowledge on this subject my first instinct would be to use the url redirect module to map old urls to new ones, so instead of trying to bend drupal's automatic node id allocation, just map old to new. Should be able to do that easily enough if you've managed to master migrate\_d2d!

---
Tags: 7, nodes, migrations
---


# Question
Title: Replace Ubercart radio button with image?
I have a product with three radio button options, and I want to replace those radio buttons with clickable images. This is how those radio buttons appear in the code:

```
<div class="form-radios" id="edit-attributes-51">

  <div class="form-type-radio form-item-attributes-51 form-item">
    <label for="edit-attributes-51-136" class="option radio"> <input type="radio" class="form-radio" value="136" name="attributes[51]" id="edit-attributes-51-136">Red, +$3.00 </label>
  </div>

  <div class="form-type-radio form-item-attributes-51 form-item">
    <label for="edit-attributes-51-135" class="option radio"> <input type="radio" class="form-radio" value="135" name="attributes[51]" id="edit-attributes-51-135">Green, +$5.00 </label>
  </div>

  <div class="form-type-radio form-item-attributes-51 form-item">
    <label for="edit-attributes-51-137" class="option radio"> <input type="radio" class="form-radio" value="137" name="attributes[51]" id="edit-attributes-51-137">Blue, +$10.00 </label>
  </div>

</div>

```

Instead of the radio button and label, I'd like to simply display a image color swatch. How can I accomplish this? I assume I'd need to somehow reference the "for" value in the "label", but I'm not sure how to do so. I'd prefer not to go the "nth child" route, but I can if I need to.

Thanks!

# Answer
> 1 votes
You can use CSS like so to target the labels:

```
label[for*="edit-attributes-51-"]{
   /* ADD YOUR IMAGE HERE */
}

```

or target the individual ones (135,136,xxx):

```
label[for="edit-attributes-51-135"]{
   /* ADD YOUR IMAGE HERE */
}

```

---
Tags: 7, ubercart
---


# Question
Title: How can I prevent Drupal from stripping/sanitizing anchor tag
In a custom moudule I find email addresses and return them as clickable mailto anchors on the page.

```
    $tableEntry['Email'] = l($emailAddress ,'mailto:'.$emailAddress , array('html' => TRUE));

    //Snippet of render array being used to create the table.. In a different function from the line above
    $rows = array();
    foreach ($tableEntries as $entry) {
    $rows[] = array(
        array('data' => $entry['Email']), //l($entry['Email'], 'mailto:'.$entry['Email'], array('absolute' => TRUE))),
    );

```

If i create the anchors before passing them into the table's render array, Drupal does something to strip away the html. I have tried a whole bunch of argument options in l() and have also tried directly entering in HTML into l(), all the time the results get stripped. (I always check the generated email address to be sure it was first created successfully) . The only way i am able to get an anchor to display as a link within the browser, instead of plain text, is to call the l() function at the last step of building the table render array eg. the commented out code. Any explanations are much appreciated.

# Answer
Just for sanity's sake...from a 'Drupal' point of view, your code works fine. For example (without the loop),

```
$emailAddress = 'test@test.com';
$entry['Email'] = l($emailAddress ,'mailto:'.$emailAddress , array('html' => TRUE));

//Snippet of render array being used to create the table
$rows = array();
$rows[] = array(
    array('data' => $entry['Email']),
);

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

```

Produces:

```
<table>
  <tbody>
    <tr class="odd">
      <td><a href="mailto:test@test.com">test@test.com</a></td>
    </tr>
  </tbody>
</table>

```

You may have a custom implementation of `theme_table()` somewhere which sanitises the incoming cell data, but it's not being caused by Drupal core.

Or, it might simply be that you're trying to re-use `$entry` when it doesn't make sense to.

```
$entry['Email'] = l($emailAddress ,'mailto:'.$emailAddress , array('html' => TRUE));

...

foreach ($tableEntries as $entry) {

```

Are you sure you meant to overwrite the outer `$entry` array with the one in the `foreach`?
> 2 votes

---
Tags: 7, theming, navigation
---


# Question
Title: Using hook_form_FORM_ID_alter to add CSS class to Simple Hierarchical Select
I'm trying to use `hook_form_FORM_ID_alter` to add a CSS class to one of the select element.

I'm trying to add a CSS class "form-control", to the `<select id="edit-shs-term-node-tid-depth-select-1">`'s class.

I have added it and even performed `drush cc all`, but still nothing was added to the class of select.

**HTML**

```
 <form action="/properties" method="get" id=
  "views-exposed-form-view-property-page-master" accept-charset="UTF-8" class=
  "jquery-once-1-processed">
    <div>
      <div class="views-exposed-form">
        <div class="views-exposed-widgets clearfix">
          <div id="edit-title-wrapper" class=
          "views-exposed-widget views-widget-filter-title">
            <label for="edit-title">Search</label>

            <div class="views-widget">
              <div class="form-type-textfield form-item-title form-item form-group">
                <input class="form-control form-text" type="text" id="edit-title" name=
                "title" value="" size="30" maxlength="128" />
              </div>
            </div>
          </div>

          <div id="edit-field-developer2-tid-wrapper" class=
          "views-exposed-widget views-widget-filter-field_developer2_tid">
            <label for="edit-field-developer2-tid">Developer</label>

            <div class="views-widget">
              <div class=
              "form-type-select form-item-field-developer2-tid form-item form-group">
                <select class="form-control form-select" id="edit-field-developer2-tid"
                name="field_developer2_tid">
                  <option value="All" selected="selected">
                    - Any -
                  </option>
                </select>
              </div>
            </div>
          </div>

          <div id="edit-shs-term-node-tid-depth-wrapper" class=
          "views-exposed-widget views-widget-filter-shs_term_node_tid_depth">
            <label for="edit-shs-term-node-tid-depth">Location</label>

            <div class="views-widget">
              <div class=
              "form-type-textfield form-item-shs-term-node-tid-depth form-item form-group shs-wrapper-processed">
              <input class=
              "element-invisible shs-enabled form-control form-text shs-processed"
                type="text" id="edit-shs-term-node-tid-depth" name=
                "shs_term_node_tid_depth" value="All" size="60" maxlength="128" />
                <select id="edit-shs-term-node-tid-depth-select-1" class=
                "shs-select form-select shs-select-level-1" style=
                "display: inline-block;">
                  <option value="0">
                    - None -
                  </option>
                </select>
              </div>
            </div>
          </div>

          <div id="edit-field-property-type-tid-wrapper" class=
          "views-exposed-widget views-widget-filter-field_property_type_tid">
            <label for="edit-field-property-type-tid">Property Type</label>

            <div class="views-widget">
              <div class=
              "form-type-select form-item-field-property-type-tid form-item form-group">
                <select class="form-control form-select" id=
                "edit-field-property-type-tid" name="field_property_type_tid">
                  <option value="All" selected="selected">
                    - Any -
                  </option>
                </select>
              </div>
            </div>
          </div>

          <div class="views-exposed-widget views-submit-button">
            <button class="btn btn-info form-submit" id="edit-submit-view-property" name=
            "" value="Apply" type="submit">Apply</button>
          </div>
        </div>
      </div>
    </div>
  </form>

```

**template.php**

```
/*
 * implements hook_form_FORM_ID_alter
 *
 */
function directbootstrap_form_views_exposed_form_view_property_page_master_alter(&$form, &$form_state, $form_id) {

    $form['shs_term_node_tid_depth']['#attributes'][] = array('class' => array('form-control'));
}

```

**EDIT**

I have updated my question,

What I'm trying to accomplish is insert a class 'form-control' on to the hierarchical select. But after inserting `dpm($form);` inside the function. All I can find is the array for the element `shs_term_node_tid_depth` but not the `<select>` itself.

here is my **template.php**

```
/**
 * implementation of hook_form_FORM_ID_alter()
 */
function directbootstrap_form_views_exposed_form_alter(&$form, &$form_state, $form_id)
{
 if ($form['#id'] == 'views-exposed-form-view-property-page-master')) {
    $form['shs_term_node_tid_depth']['#attributes']['class'][] = 'form-control';
  }
}

```

# Answer
> 3 votes
You need:

```
$form['shs_term_node_tid_depth']['#attributes'] = array('class' => array('form-control'));

```

or more succinct version:

```
$form['shs_term_node_tid_depth']['#attributes']['class'][] = 'form-control';

```

# Answer
> 1 votes
Views exposed forms are...fun. For example, the form ID you get will *always* be `views_exposed_form`, regardless of the ID you see in HTML or anywhere else. So currently your form alter function isn't named quite right.

You need to alter the form by its correct ID on the PHP side, and grab the context from something else in the form, maybe the html ID itself.

So, a rudimentary version of what you're looking for would be

```
function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'views-exposed-form-view-property-page-master')) {
    $form['shs_term_node_tid_depth']['#attributes']['class'][] = 'form-control';
  }
}

```

Remember to clear the caches after you've changed the function name.

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


# Question
Title: optimal way to remove unwanted js and css files from page
I use drupal 6 and ubercart2. Loading of cart and checkout page takes a while so I am thinking about removing any js and css files which are not used on specific pages. What would be the ideal way to do it? I know about js agregation but want to try the first approach. Thank you very much.

# Answer
> 1 votes
The AdvAgg module can do this fairly easily. Syntax for this is different between 6.x & 7.x. This is the hook syntax for 6.x. Works very similar to hook\_css\_alter() & hook\_js\_alter() in Drupal 7. Using these hooks is how to do it in D7 BTW.

```
hook_advagg_css_pre_alter(&$css, $preprocess_css, $public_downloads) {
  // Remove css files.
}
hook_advagg_js_pre_alter(&$js, $preprocess_js, $public_downloads) {
  // Remove js files.
}

```

# Answer
> 0 votes
Have a look at the FOAD technique to get rid of stylesheets and scripts. It happens in your own theme.

You can take an alternate route and use stuff like Stylestripper module or Mothership base theme.

# Answer
> 0 votes
With reference to your question 'optimal way to remove unwanted js and css files from page', hope this approach works ::

1) Include your js & css files only under appropriate hook as per applicable

2) Use syntax like -

drupal\_add\_js (drupal\_get\_path ('module', 'module\_name') . '/js/js\_file\_name.js' ); drupal\_add\_css(drupal\_get\_path('module', 'module\_name') . '/css/css\_file\_name.css');

3) You can make use of syntax like this to set some settings variable & check in your js file before invoking your event inside the behavior

In module file ::

drupal\_add\_js (array ('module\_name' =\> array ('variable\_name' =\> some\_value)), 'setting' );

In js file ::

```

   Drupal.behaviors.testName = {
     attach: function (context, settings) {
       if(typeof Drupal.settings.module_name != 'undefined'
    &&
    Drupal.settings.module_name.variable_name == some_value){
      // Do SOMETHING
       }
     }
  };

```

4) If your code already included js & css files at places which could be done a better way, then you need to make the code changes accordingly. For example,

If we could include the js & css files in hook\_node\_view (based on D7 standard, say), then we should not include it from hook\_init.

Hope it helps

---
Tags: 6, theming, javascript, ubercart
---


# Question
Title: integrate html, css code into a drupal theme
My client has hired a vendor to create html, css, javascript for a website and we are planning to use Drupal as CMS for this website. I'm one of the front end devs involved in choosing a base theme for this site and our team is fairly new to Drupal. How do we integrate this vendor provided html,css code into a drupal theme? What are the things we need to know before integrating the code? How do we start with integrating this code into Drupal? How do we select a theme that would work with the vendor provided code? What are the things we need to look for ?

# Answer
Read about theming to create your own theme. If what you need is just to append files and folders to your drupal theme without altering it, you must create your own module for your application functions (if you have any), and add your script or styles files with calls to:

```
drupal_add_js(drupal_get_path('module', 'yourmodulefolder').'/path/to/your/js/file')
drupal_add_css(drupal_get_path('module', 'yourmodulefolder').'/path/to/your/css/file')

```

See Adding CSS files and Adding JS files here for more information. The use cases I gave you are for files (assuming the files are inside your module).

You can add these calls in any hook in your module (I take the dirty way: I put this kind of lines in the global scope, althought it's not the better solution, it doesn't break what I'm doing).
> 1 votes

---
Tags: theming
---


# Question
Title: Node Permission base on per Taxonomy Term
Is it possible to give view page(or article) permission per Taxonomy term? I know there is a "Taxonomy Access Control" module but this module does not really give the permission, beside hiding the node url. Meaning I still able to see the page if I know the original url. For example, "www.mysite.com/node/100".

# Answer
> 1 votes
I think TAC can provide this functionality.

Here's a screen shot of the TAC config.

http://cl.ly/image/1f1Z433r0y1s

---
Tags: nodes, users
---


# Question
Title: How to use LESS (CSS) in a Zen sub-theme?
I'm trying to use LESS in a Zen sub-theme, but while the CSS files are correctly included (even with a ".less" extension), the LESS rules themselves don't seem to be recognized and processed.

Here's my setup :

* Zen theme installed, and sub-theme created (and activated)
* LESS module installed and enabled (along with Libraries)
* the lessphp library has also been installed, following the instructions on the LESS module page.

In my sub-theme folder, I basically have the following files :

* `mytheme.info`, which includes the `css/styles.css` below.
* `css/styles.css`: (provided with the Zen Starter Kit) only contains a bunch of import rules; among them I added `@import "mytheme.less";` which will be the main CSS (LESS) file for my theme.
* `css/mytheme.less`, in the same folder as the `styles.css`. I used this file to test simple LESS rules.

When I use a normal CSS rule in the mytheme file, it's recognized and displayed normally in the site (e.g. `body {color: red;}`. However, even basic LESS rules seem to be simply ignored. Example of code that *doesn't* work:

```
@color: red;
body {
    color: @color;
}

```

I'm not familiar with CSS preprocessors, so I don't know if I'm missing anything. Or is the Zen theme somehow incompatible with the LESS module?

So, any help is appreciated. Thanks in advance.

# Answer
> 1 votes
I can't comment directly about using LESS with Zen, but I have used it with Omega 3.

With this, you have to specify the proper filenames in the theme.info file. The stylesheets need to be named like "styles.css.less", and specified like:

```
stylesheets[all][] = styles.css.less

```

in the .info file. Includes with variables and mixins get named like "mixins.less".

Assuming files are named this way, the module will do its thing, and compile the sheets and rewrite the paths to reflect the compiled versions.

That said, we stopped using LESS a while ago, and have moved on to Sass/Compass.

# Answer
> 0 votes
Zen Grids depend on SASS. Zen Grids were not written for LESS. You can use the Zen theme without the grids component, but that would be more trouble that it's worth.

While developing with a CSS preprocessor locally, you will need to install sass and compass. You will then need a tool to watch your directory of sass files for any changes then compile the SASS into css in the css directory. Usually you would navigate to your theme directory in the command line tool of your choice and enter "compass watch". This will then automatically compile your sass as you save.

For more info see Getting started with Drupal7, Zen, Sass and Compass.

---
Tags: 7, theming
---


# Question
Title: Ajax example dependent dropdown callback
I have two custom Drupal modules moduleA and moduleB. moduleA has all the functions for Ajax calls i.e. `ajax_example_dependent_dropdown_callback` and `_ajax_example_get_second_dropdown_options`.

I create a content type in moduleB called `content_type_b`. I am using Ajax calls in moduleB to populate drop down in `content_type_b`.

While creating content for `content_type_b`, I try to choose a value from the drop down. The first time, it works fine. The second time I get an error saying *"An Illegal choice has been selected. Please contact the administrator"*. All these events happen before a node insert.

When I looked into the logs, the hook\_node\_validate of moduleA is getting called. The node insert must happen in moduleB. So `node_validate` of moduleB must be called. I think since the Ajax functions were present in moduleA, the `node_validate` of moduleA is being called.

Please advice how to proceed in this situation.

# Answer
The issue was fixed by changing one of the fields in the Content Type to List(text) instead of node reference. After this the "Illegal choice error" disappeared.
> 0 votes

---
Tags: hooks, ajax, nodes
---


# Question
Title: Is there a good way to determine which database table are associated with each module?
I have been installing and uninstalling modules on my site and I am starting to run into problems involving re installing previously disabled modules. The install script is finding old database tables from previous module installations and is refusing to install. For some of these modules, there is no 'uninstall' option. Is there a good way to determine which database table are associated with each module? I'm looking for a method of discovery or an online list.

# Answer
> 4 votes
I am unaware of an automated way to check for orphaned tables. Before the Schema API was rolled out in Drupal 7, people would use the Schema module. This had a `hook_requirements()` in it that would do this check and list orphaned tables on the status report.

You could make your own automated test. The procedure would be something like

* Do a `SHOW TABLES` query to get the list of all of the tables.
* Query the `{system}` table to get a list of all modules, both enabled and disabled
* Loop through the modules, and then use `drupal_get_schema_unprocessed()` to get the module's schema. From this, build up a list of tables.
* Do an array difference between the list you just built and the list from `SHOW TABLES`. This should be all tables that aren't owned by a module that is enabled or disabled.

Something like this:

```
$alltables = db_query('SHOW TABLES')->fetchCol();

$modules = db_query("SELECT name FROM {system} WHERE type = 'module'")->fetchCol();

$accountedfor = array();

foreach ($modules as $module) {
  $schema = drupal_get_schema_unprocessed($module);

  if (!empty($schema)) {
    $accountedfor = array_merge($accountedfor, array_keys($schema));
  }
}

// tables not accounted for by hook_schema() from enabled and disabled modules

$orphaned = array_diff($alltables, $accountedfor);

```

This ignore the intricacies of table prefixes, multiple catalogs, and sharing catalogs between applications.

Use at your own risk.

# Answer
> 1 votes
I've encountered trouble using the uninstall on a few modules even when hook\_schema was used. you could try 1) searching for the module in the 'system' table of your database and setting its status to 0 to disable it. 2) look through the module's file contents for hook\_schema function (usually it will be in a {modulename}.install file) This function should allow you to figure out which tables were added to the database when the module was enabled, and to drop them manually if needed.

# Answer
> 0 votes
For what you are trying to do, the Schema API is your friend. Check it out at https://drupal.org/developing/api/schema.

Pay a close attention to the function **drupal\_get\_schema($table = NULL, $rebuild = FALSE)**

Running that function without parameters will return every DB table created using the Schema API. But the returned information will not show the modules ... it just shows the tables and their fields' definitions. But if you are willing to dig deeper, you can clone the drupal\_get\_schema() function a adjust it a little so that the return value is indexed using the modules' names.

The following loop shows how Drupal is already looping through the list of all the modules that implement the hook\_schema()

```
...
// Invoke hook_schema for all modules.
foreach (module_implements('schema') as $module) {
  // Cast the result of hook_schema() to an array, as a NULL return value
  // would cause array_merge() to set the $schema variable to NULL as well.
  // That would break modules which use $schema further down the line.
  $current = (array) module_invoke($module, 'schema');
  _drupal_initialize_schema($module, $current);
  $schema = array_merge($schema, $current);
}
...

```

I haven't tested the following, but it can give you what you need. Just replace the loop using this new version of it. And remember not to modify the core. Copy the entire function in your own code and do the changes there. The modified loop is...

```
...
// Invoke hook_schema for all modules.
foreach (module_implements('schema') as $module) {
  // Cast the result of hook_schema() to an array, as a NULL return value
  // would cause array_merge() to set the $schema variable to NULL as well.
  // That would break modules which use $schema further down the line.
  $current = array($module => (array) module_invoke($module, 'schema'));
  _drupal_initialize_schema($module, $current);
  $schema = array_merge($schema, $current);
}
...

```

If a crappy module is creating it's own DB tables using a direct query, than that would be defeating the purpose of the API and you will not be able to get those using the Schema API.

---
Tags: 7
---


# Question
Title: 500 Internal Error Drupal 7.26 - Can't access forums
last night my site (Drupal 7.26 core) was working fine and then all of a sudden after creating a new forum topic with some excel graphs included (copy paste from excel) the forums completely shut down. All other pages and content are available except the forums. I can't remember the exact error that was coming up at the time but I was getting an error due to the PHP memory limit not being enough. I contacted the hosting company and got them to change it from 32mb to 128mb and also created a php.ini file with the following code:

```
php_value memory_limit = "128M"

```

and placed that in the root folder. The PHP memory limit error stopped coming up but the forums are still inaccessible and I'm now getting the following error when trying to access the forums:

> The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator, webmaster@mysite.co.za and inform them of the time the error occurred, and anything you might have done that may have caused the error. More information about this error may be available in the server error log. Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.

Could someone please help me with this? It is a community site which is pretty useless without the forums.

# Answer
The "500 internal server" error message just means: "Your web server just crashed". There are many different things that can have gone wrong.

To determine the cause, you need examine your web server logs (your hosting provider can tell you where these are if you don't know where to find them).

Below is a list of some of the most frequent causes of a "500" error on a Drupal web site (I am trying to make this generic - for future reference - I know you've covered the PHP memory limit already):

* The setting for PHP `memory_limit` is too low. Note that if you're on shared hosting, you can't change this yourself. You need to get it increased by your hosting provider.
* Your hosting provider has set restrictions on what `php_values` or `php_flags` you can put in `.htaccess` that is violated by one of the `.htaccess`-files created by Drupal or by directives added to these by you.
* Your have syntax errors in one of the `.htaccess`-files in your configuration. (In particular if you've edited the default `.htaccess`.)
* There exists permissions on files or folders that is outlawed by a security measure your hosting provider uses.

As the message says: "The server encountered an internal error or misconfiguration". To gather information about what type of error this was, you need to examine the server (error) logs. There is no way we can help you with this without seeing the relevant error messages from your logs. We don't have access to your server or your logs.

You may also increase the level of error reporting from PHP to get better diagnostics. You'll get full runtime error reporting by adding this to the start of `settings.php` on your site (just below `<?php`):

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

```

In addition, navigate to: *Administration → Configuration → Development → Logging and errors* and select the radio button "All messages". This sets `$conf['error_level'] = 2;`.

When you examine the logs and diagnostics from PHP error reporting, you may find out more about what made your server crash. If you do not fully understand what those messages means, you can update the question with the *specific* error messages, and hope that someone here shall be able to shed more light on the cause of the problem.

If everything else fails, make a backup of your database (you may use the Backup and Migrate module or some DB tool that works independent of Drupal (e.g. *phpMyAdmin*). Then *disable* and *uninstall* the module that you thinks is the cause of your problems (sound like it is the **Advanced Forum** in your case. Make sure you not only disable, but also uninstall (these are two separate steps).

Verify that your site is now stable.

If it is stable, *re-install* the module (e.g. **Advanced Forum**) that caused the problem from scratch.

Re-assess the status of your site. Is it still stable? Is any content missing?

If it is *not* stable, then the problem is *not* solved, and you need to reconsider the use of module that causes grief (i.e. ditch it and find a better module).

However, if content is missing, you should be able to restore that back from the back-up yiu made (perhaps after looking through your backup files for anything problematic, and deleting it from the backup *before* restoring).
> 0 votes

---
Tags: nodes
---


# Question
Title: CKEditor links wrap the contents of a container individually instead of a container
I'm in a situation where I want to use WYSIWYG with CKEditor because of the easy Media integration. However, I'm building a page with some interactive tabs that have markup something like this:

**(#1)**

```
<div class="tab-wrapper">
    <div id="tab1" class="tab">
        <div class="image-wrapper">
            [[Media markup to insert an image]]
        </div>
        <p class="tab-text">Some text.</p>
    </div>
    <div id="tab2" class="tab">
        <div class="image-wrapper">
            [[Media markup to insert an image]]
        </div>
        <p class="tab-text">Some text.</p>
    </div>
</div>

```

I want to wrap each of these tabs with a link, this being the desired end result:

**(#2)**

```
<div class="tab-wrapper">
    <a href="/somepage">
        <div id="tab1" class="tab">
            <div class="image-wrapper">
                [[Media markup to insert an image]]
            </div>
            <p class="tab-text">Some text.</p>
        </div>
    </a>
    <a href="/someotherpage">
        <div id="tab2" class="tab">
            <div class="image-wrapper">
                [[Media markup to insert an image]]
            </div>
            <p class="tab-text">Some text.</p>
        </div>
    </a>
</div>

```

If I try to do this in CKEditor, however, I get this:

**(#3)**

```
<div class="tab-wrapper">
    <div id="tab1" class="tab">
        <div class="image-wrapper">
            <a href="/somepage">[[Media markup to insert an image]]</a>
        </div>
        <p class="tab-text"><a href="/somepage">Some text.</a></p>
    </div>
    <div id="tab2" class="tab">
        <div class="image-wrapper">
            <a href="/someotherpage">[[Media markup to insert an image]]</a>
        </div>
        <p class="tab-text"><a href="/someotherpage">Some text.</a></p>
    </div>
</div>

```

This creates problems with styling and, more importantly, makes some regions of the tab unclickable. What's even more maddening is that *even if I disable rich text and edit the HTML directly* to #3, if I switch back to CKEditor it "corrects" the markup to #2.

Is there any way to change or otherwise prevent this behavior? I still want to use the Media module integration to insert and modify images, so I'm hesitant to simply disable CKEditor and leave it off. I can insert my images, then edit the HTML to insert my link tags properly, then save the page, but it can still break again if I go back to make changes.

I'm currently running CKEditor version 3.6.6.7689, WYSIWYG module 7.x-2.2, Media 7.x-2.0-alpha3, and the latest Drupal 7 core.

# Answer
The CKEDitor by default restricts the HTML you can use to what it considers *safe* by means of something called the advanced content filter (ACF). It is this feature of CKeditor that rejects your HTML-construct.

To change or otherwise prevent this behavior, you must describe the construct you want to allow by using the syntax described in the allowed content rules and assigned the JavaScript variable `config.extraAllowedContent`.

**PS**: If you Google this, you'll often see the following JavaScript suggested to "fix" to CKEDitor removing "unsafe" HTML:

```
config.allowedContent = true;

```

What the above line does it to turn ACF of completely. It will allow *any* valid HTML to be inserted. It is OK to do this for testing and debugging, but it is not recommended that you do this on a production site.
> 1 votes

---
Tags: wysiwyg
---


# Question
Title: How to set up an email notification if a user gets a new role?
I'm on d7. I want to notify users if they have received a new role. Any suggestions on how can I do this? Thanks.

# Answer
> 1 votes
I suppose this is for manually promoting a user. I would try creating a rule using the Rules module for modifying the role and sending a mail to the user about his/her new role on the site.

I'm still learning how to use Rules, so I won't be able to give you a detailed recipe here, but after watching the excellent Rules screencast series at the NodeOne site, you might be able to do this quickly without making a custom module.

# Answer
> 0 votes
You can try "Role change Notify" module. But this module only sending one and the same email content to the user regardless of which new role assigned. You can't send different emails to different user based on the different role assigned.

I think a better way is to use Rules module to achieve. But no easy event can achieve this at the moment. Im still figuring out how to code it with Rules. Any new findings please let us know. Thanks.

---
Tags: 7, users, emails
---


title: Customize the form-portion of a view

text:
# Question
Title: Customize the form-portion of a view
There might be a really simple answer for this, but I haven't found it yet.

I'm using a view with a few exposed filters. The form it generates is too basic, and I want to restructure it a bit, with some "+ advanced" expanding/collapsing divs and things like that.

What method do I hook for this? Or is there a better way?

# Answer
You can override views-exposed-form.tpl.php template. In this overrided template you can putup own div wrapper etc. How to override any template(tpl) visit here.

You can also use hook\_form\_alter. It perform alterations before a form is rendered. So using this add some alteration on form.
> 0 votes

---
Tags: views
---


# Question
Title: Does Drupal override php setting by it self by .htaccess?
When I migrate or restore a Drupal 6 site Always php version I have set in the account page of the shared hosting service has been automatically changed.

For example, though I have set php 5.3 for example.com when I restore the site using exactly the same domain, files, db and the host after the restoration php version is set to php 5.1

Also after the restoration php.ini file gets set back to OFF though it was set to "On" before the restration.

I contacted the shared hosting company but they say I should check the `.htaccess` file that overrides the php setting.

Does Drupal do this?

# Answer
> 3 votes
> Does Drupal override php setting by it self by .htaccess?

No. Nor does it do it by any other method.

As pointed out in the comment by *kiamlaluno*, Drupal comes with its own `.htaccess` file. You'll find it as one the files in your Drupal root. You can read through it yourself and see that it does not change the setting of PHP version that you set in the account page of your shared hosting service.

The `.htaccess` overrides some settings that may be set different in `php.ini`, as shown in the directives below (copied from the default `.htaccess` file), but not anything else. As you can see, it has `IfModule` directives that makes the overrides contigent on the versions of PHP and Apache you use, rather than overriding the version.

```
# PHP 4, Apache 1.
<IfModule mod_php4.c>
  php_value magic_quotes_gpc                0
  php_value register_globals                0
  php_value session.auto_start              0
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_value mbstring.encoding_translation   0
</IfModule>

# PHP 4, Apache 2.
<IfModule sapi_apache2.c>
  php_value magic_quotes_gpc                0
  php_value register_globals                0
  php_value session.auto_start              0
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_value mbstring.encoding_translation   0
</IfModule>

# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
  php_value magic_quotes_gpc                0
  php_value register_globals                0
  php_value session.auto_start              0
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_value mbstring.encoding_translation   0
</IfModule>

```

The changes you ask about cannot be explained by the Drupal `.htaccess`-file or anything else done by Drupal. Nor do I know about any backup/restore program or migration program for Drupal that does such things as those you describe.

# Answer
> 3 votes
If you use Bluehost for instance, and change PHP version in the control panel, it will overwrite Drupal's root .htaccess file, although I believe a backup is made.

What you need to do is this:

1. Rename Drupal's root .htaccess file.
2. Change PHP version in the control panel (5.2 recommended for Drupal 6).
3. Open up the new .htaccess file and copy the info in it into Drupal's .htaccess file. Should be something like `AddHandler application/x-httpd-php52 .php`. Rename or delete this file.
4. Rename Drupal's .htaccess file back to `.htaccess` and everything should be working.

---
Tags: 6, .htaccess
---


# Question
Title: How to use GROUP BY and SUM in Views table?
I have custom entity "product". It's base table is "product" and it's primary/id key is "entity\_id". I have created all Views definitions for this entity.

Additionally I have another table called "product\_stats" with following structure: entry\_id | event | quantity | product\_id | timestamp | uid | path | ip

where product\_stats.product\_id = product.entity\_id

**What I want to achieve:** I want to be able to display

* a) number of entries of particular event
* b) sum the "quantity" of particular event for all my entities.

I have created Views definition for this table and I am able to use relationship but since I don't know how to tell Views to use GROUP BY I ended up with duplicates and I have no idea how to do b)(SUM() the quantity of the events per entity) at all.

---

Here is the table structure

Here is my Views definition:

```
  $data['product_stats']['table']['base'] = array(
    'field' => 'entry_id',
    'title' => t('Product statistics'),
    'help' => t('Table containing various logs related to products.'),
    'weight' => -10,
  );
  $data['product_stats']['table']['entity type'] = 'product';
  $data['product_stats']['table']['group']  = t('Product statistics');
  $data['product_stats']['table']['join'] = array(
    'product' => array(
      'left_field' => 'entity_id',
      'field' => 'product_id',
    ),
  );
  $data['product_stats']['product_id'] = array(
    'title' => t('Product ID'),
    'help' => t('The product ID the entry belongs to.'),
    'field' => array(
      'id' => 'standard',
    ),
    'argument' => array(
      'id' => 'numeric',
    ),
    'filter' => array(
      'id' => 'numeric',
    ),
    'sort' => array(
      'id' => 'standard',
    ),
    'relationship' => array(
      'id' => 'standard',
      'base' => 'product',
      'base field' => 'entity_id', // this is 'field' in doc.
      'title' => t('Product statistics'),
      'label' => t('Product statistics')
    ),
  );
  $data['product_stats']['event'] = array(
    'title' => t('Event'),
    'help' => t('The event type.'),
    'field' => array(
      'id' => 'standard',
    ),
    'sort' => array(
      'id' => 'standard',
    ),
    'filter' => array(
      'id' => 'string',
    ),
    'argument' => array(
      'id' => 'string',
    ),
  );
  $data['product_stats']['quantity'] = array(
    'title' => t('Quantity'),
    'help' => t('Quantity of products influenced during this event.'),
    'field' => array(
      'id' => 'standard',
    ),
    'sort' => array(
      'id' => 'numeric',
    ),
    'filter' => array(
      'id' => 'numeric',
    ),
    'argument' => array(
      'id' => 'standard',
    ),
  );
  $data['product_stats']['timestamp'] = array(
    'title' => t('Timestamp'),
    'help' => t('The UNIX timestamp when event occurred.'),
    'field' => array(
      'id' => 'date',
    ),
    'sort' => array(
      'id' => 'date'
    ),
    'filter' => array(
      'id' => 'date',
    ),
  );
  $data['product_stats']['uid'] = array(
    'title' => t('Author uid'),
    'help' => t('The active user during the event.'),
    'relationship' => array(
      'title' => t('Event author'),
      'help' => t('Relate the event to the user who triggered it.'),
      'id' => 'standard',
      'base' => 'users',
      'field' => 'uid',
      'label' => t('author'),
    ),
    'filter' => array(
      'id' => 'user_name',
    ),
    'argument' => array(
      'id' => 'numeric',
    ),
    'field' => array(
      'id' => 'user',
    ),
  );
  $data['product_stats']['path'] = array(
    'title' => t('Path'),
    'help' => t('The system path where the event occurred.'),
    'field' => array(
      'id' => 'standard',
    ),
    'sort' => array(
      'id' => 'standard',
    ),
    'filter' => array(
      'id' => 'string',
    ),
    'argument' => array(
      'id' => 'string',
    ),
  );

```

I presume that to display data only for selected event I would have to create a Views Field plugin where I would choose the event but I don't know how would I apply it to the field anyway.

---

In the end I think this can be done only by creating a Views Field plugin where user would specify the event(or not) and if the field should COUNT or SUM the results. But that is beyond my knowledge right now.

# Answer
Click on the advanced link on the right side of the views configuration. There you find 'aggregation'. Enable this.

Once this is done you should add all fields you either want to aggregate or groupby.
> 0 votes

---
Tags: views, 8
---


# Question
Title: How to get the updated content of a block via an AJAX call?
I am trying to get to grips with Drupal 8s layout and and architecture.

Having worked with Drupal 6 for the last 2 years I have become used to its procedural style, so I am finding the OOP approach takes a little getting used to.

This is what Im trying to achieve.

My Module has a block which displays content The content of that block is refreshed every 5 seconds This is done with an Ajax call to the server which overwrites the content of the block with the freshly acquired Ajax HTML

So I have gotten the block to display my content on the page easily enough. My problem is now how do I get to the content to refresh. The logic for building the content is contained in functions in my Block class.

I have tried to set up a route in my .yml file to call these functions again to refresh my content via ajax, but I get fatal errors, and also it does not feel like the right approach to access my block class. I feel I should be routing to the controller.

but then, how do I get at the functions that I have written to build the content for the block in the first place?

Should I have written all my logic in my Controller? and if so, how do I access it from my block?

**UPDATE**

Attempting the solution suggested by Daniel Wehner below I receive the following error:

```
    Call to undefined method Drupal\livequotes\Controller\LivequotesController::getEntityManager()
in <b>C:\Work\excel-8\modules\livequotes\lib\Drupal\livequotes\Controller\LivequotesController.php

```

I guess this is because I need to extend my controller or to implement the class that defines getEntityManager()

any ideas on how to do this?

**UPDATE 2**

Following on the suggestion in comments from Daniel Wehners answer I have attempted to use dependency injection to give access to EntityManager from my controller.

This is the code for my controller:

```
    namespace Drupal\livequotes\Controller;

    class LivequotesController{

    protected $entity;

    public function __construct(EntityManager $em) {
        $this->entity = $em;
    }
    /**
     * Re-render a specific block (yeah if we do something it should be generic).
     */
    public function livequotesShowBlock()
    {
        $block = $this->entity->getStorage('block')->load($block_id);
        return $this->entity->getViewBuilder('block')->view($block);
    }
}

```

The following error is received when I try and access function livequotesShowBlock() from my ajax call:

> Recoverable fatal error: Argument 1 passed to Drupal\livequotes\Controller\LivequotesController::\__construct() must be an instance of Drupal\livequotes\Controller\EntityManager, none given

**UPDATE 3**

Following the link to an example of Dependency injection into a Controller class, drupal.org/node/2168121 provided by Daniel Wehners comment in his answer my Controller now looks like this:

```
namespace Drupal\livequotes\Controller;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Controller\ControllerBase;

/**
 * Controller routines for livequotes routes.
 */

class LivequotesController extends ControllerBase{

    protected $entity;

    public function create(Container $container)
    {
        return new static($container->get('entity'));
    }

    public function __construct(EntityInterface $em) {
        $this->entity = $em;
    }

    public function livequotesShowBlock()
    {
        $block_id = "livequotes_content";
        $block = $this->entity->getStorage('block')->load($block_id);
        return $this->entity->getViewBuilder('block')->view($block);
    }
}

```

Unfortunately though, I am now getting the following error:

> Fatal error: Cannot make static method Drupal\Core\Controller\ControllerBase::create() non static in class Drupal\livequotes\Controller\LivequotesController in C:\Work\excel-8\modules\livequotes\lib\Drupal\livequotes\Controller\LivequotesController.php on line 16

**UPDATE 4**

Changing the signature to static

```
    namespace Drupal\livequotes\Controller;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Controller\ControllerBase;

/**
 * Controller routines for livequotes routes.
 */

class LivequotesController extends ControllerBase{

    protected $entity;

    public static function create(Container $container) {
        return new static($container->get('entity'));
    }

    public function __construct(EntityInterface $em) {
        $this->entity = $em;
    }
    /**
     * Re-render a specific block (yeah if we do something it should be generic).
     */
    public function livequotesShowBlock()
    {
        $block_id = "livequotes_content";
        $block = $this->entity->getStorage('block')->load($block_id);
        return $this->entity->getViewBuilder('block')->view($block);
    }
}

```

results in the following error:

> Declaration of Drupal\livequotes\Controller\LivequotesController::create() must be compatible with Drupal\Core\DependencyInjection\ContainerInjectionInterface::create(Symfony\Component\DependencyInjection\ContainerInterface $container)

# Answer
> 1 votes
The proper way is probably to re-render the block in your controller:

```
<?php
class ExampleController extends ControllerBase {

  /**
   * Re-render a specific block (yeah if we do something it should be generic).
   */
  public function renderBlock($block_id) {
     $block = $this->getEntityManager()->getStorage('block')->load($block_id);
     return $this->getEntityManager()->getViewBuilder('block')->view($block);
  }

}

```

---
Tags: blocks, 8
---


title: CCK fields disappears

text:
# Question
Title: CCK fields disappears
I get informed that webforms didn't work anymore. I switched recently to a new server copying database and druapl installation folder to the new server.

What happens is that when webforms using, the fields (dates, numbers, etc) do not come up. I noticed that in the modules list are some incomplete entries like above:

I checked the CCK modules folder and reinstall the folder (cck-5.x-1.12), still the same.

I use CCK too for some fields in content types and it still works for creating and editing content, but when I create a new content type with a CCK field, it fails.

This site is scheduled to migrate to version 7, but meanwhile with version 5 should work.

Any idea where to search for reason that the (sub)modules are blank and propably won't work ?

# Answer
The issue you're running into sounds as if the file permissions are messed up; here's a checklist of things to go through:

1. Open `.info` files of those modules and verify that they exist and have all regular information (name, dependencies, version, etc.).
2. If they exist and have all info, check if they have some weird file access permissions; this could prevent Drupal from reading the content. See file permission instructions for Linux servers, specifically the commands which ensure that the proper permissions are in place:

```
[root@localhost]cd /path_to_drupal_installation
[root@localhost]chown -R YOUR_USERNAME:www-data .
[root@localhost]find . -type d -exec chmod u=rwx,g=rx,o= '{}' \;
[root@localhost]find . -type f -exec chmod u=rw,g=r,o= '{}' \;

```
3. Try replicating the issue on a clean install AND on a clean install with the same installation files.
4. If the above steps don't tell you anything and you still have the issue - hack the core, specifically `_module_parse_info_file()` function in `includes/module.inc` and do a `var_dump()` or `print_r()` on the `$info` variable once it parses the file. Maybe the formatting is off, encoding or something else. This might get you a step further if everything else fails.

Hope this helps.
> 1 votes

---
Tags: entities, 5
---


# Question
Title: Paid node checkout plus membership plans for a Drupal site
I need a solution to these problems for Drupal 7:

I need to create a website where people can post their classified ads. But the twist is that I don't want the ads to be published until the user has paid for it.

Also I need to create a membership plans per role (E.g. Gold Plan, Silver Plan, etc. for monthly subscription)

Now I have tried a few things like:

1. I tried using lm\_paypal for this purpose. But the issue with lm\_paypal is that it does not publish the node after the payment has been made. The admin has to manually check the paypal IPN and publish the content if the node has been paid for. I do not know module development so I am not able to make these small tweaks.
2. I tried using ubercart too but the standard issue rises again. The uc node checkout module is still in the dev version for drupal 7 and it works like hell. So many errors :(

So can anybody please come up with an alternate solution where I can achieve both the "Pay to publish" and "Membership plan" functionality on my Drupal 7 site?

# Answer
> 0 votes
Being a great fan of Drupal Commerce, I will suggest you to use it in your instance for this need.

You can use Commerce Node Checkout module for your pay to publish requirement.

For membership requirement, you can set product for each membership type & set rules for it. Create rules on event completing checkout process & put some condition like - product SKU match to membership product SKU, current user type etc. & then add usertype to the user.

You will get many payment related modules with Commerce, so you don't have to worry about any ecommerce feature.

---
Tags: nodes
---


title: Custom Form API elements in node form

text:
# Question
Title: Custom Form API elements in node form
I am rendering node form on my custom page with such a code:

```
<?php
 $form_state['build_info']['args'] = array($node);
 form_load_include($form_state, 'inc', 'node', 'node.pages');
 $form = drupal_build_form($type . '_node_form', $form_state);
 return drupal_render($form);
 ?>

```

I need to add some custom form elements to the form as follows:

```
 <?php
  $form['mycode'] = array(
 '#type' => 'textfield',
 '#title' => t('My code'),
 );
 ?>

```

The custom form elements are displayed correctly in the form. The problem is, when I submit the form, I cannot see custom values in $form\_state or even $\_REQUEST array. I am checking $form\_state values in the implementation of hook\_node\_submit

What is the correct way to add custom form elements to node form (except creation of fields) ? (I need custom form elements because I need to use different field widgets for various user roles. I also need to add checkbox like "I have read Terms and Conditions" into node form.)

thanks Tomas

# Answer
You need to use hook\_form\_alter for this requirement. You can create a submit function for the same & declare it as submit function for previously created alter function. You can access `$form_state` into that.

In same way you can have your own validate function etc.
> 2 votes

---
Tags: 7, forms, nodes
---


# Question
Title: How can I offer an option for users to switch between Unformatted and Table the Basic Styles section of Views.
I'm using Drupal 6, and the customer has asked for a way for the user to switch between a list-of-nodes view, and a table view. The Basic settings section in Views does not offer a Exposed option, and my Googling has turned up nothing useful in this regard. I'm a somewhat experienced as a Drupal themer, and I could make a duplicate set of Views manually with a different settings to achieve this, but if there's an easier way, I'd like to have your insights.

# Answer
I would most likely go for Views Display Tabs or Quick Tabs (and I would lean towards Quick Tabs because it has a d7 version and is more active).
> 2 votes

# Answer
Creating a new/separate view (with a different display type) is not the best way to go about it. Because if you take that approach your view query will be executed twice when the user switches from one style to the other.

I would do it by letting a single view show selected unformatted fields of the node and then add required JS/CSS to render the same HTML in two different styles depending on the option selected by the user.

Advantages

* view runs only once
* no page reload on switch on display preference
* better for user experience

Disadvantages

* requires slightly more time than if you were to create 2 separate views
> 0 votes

# Answer
For anyone running across this issue but need it for D7 (I know the question is for D6) Checkout the View Modes module. It adds Views display plugin which provides alternate display modes that can be switched to for a single View.
> 0 votes

# Answer
Views Modes has version for D6 at the github and there is demo at www.ugandawatch.org which is running at D6 release.
> 0 votes

---
Tags: views, theming
---


title: Context shows empty views block

text:
# Question
Title: Context shows empty views block
I've got a views block that shows data from node field.

I've set up a contextual filter

NID:

WHEN THE FILTER VALUE IS NOT AVAILABLE

Provide default value: content ID from url.

I've also set up a context show this block

Condition: Node Type

Reaction Block

It works fine, but if the field is empty it will show Block title and empty content.

Is there a way I can hide the block if the view is empty?

Thanks in advance

# Answer
> 2 votes
I've added FILTER CRITERIA: my\_field (NOT NULL)... it was so simple...

---
Tags: views, 7
---


# Question
Title: How to organize the features export modules
As we go along with features export, its being a mess. What I have been doing so far is every module which have another module that contains the feature exports. Let say their is module 'test' and it has some variable settings and I exported it via features. I will have another module name 'test\_features\_export' or something like that which contains the component associated with that module. But in some cases, the component can be too generic like 'role' which can be associated with multiple modules. Then its issue to bind to any specific features where it is meaningful.

So my question is , is there any better way to organize the features exports modules ??

# Answer
What we usually do, is create Features based on Content Type, and group everything related in there.

So a Content Type News, would be put in a Feature 'MyProject\_News'. Together with everthing that is relevant, like Views related to News, pathauto pattern, specific image styles only in use by News content, etc .. Usually, we also have another Base or General Feature, containing more generic stuff like text format settings, site settings, .. and also our roles. This Base/General Feature, is a dependency in all other Features.

Others split it up differently, with a Feature containing all the Content Types, another to hold all Image Styles, another one for Contexts, etc ..

In the end, it's all up to you. You can organize it any way you wish. However I do choose the first method, as in my opinion, a Feature should be able to operate on it's own, or being disabled, without messing up anything in the site.
> 2 votes

---
Tags: features
---


# Question
Title: How can I use the web service with one or none arguments?
I have a web service with the Services module that works perfectly, with an URL like `myweb.com\api\my_conent\124` I obtain the information of `my_content` that has the 124 id.

Now with the URL `myweb.com\api\my_content` I want to obtain all the contents of `my_content`, but it doesn't return anything, a blank page. I have the `'optional' => TRUE,` for the arguments.

How can I use the web service with one or none arguments?

# Answer
Do you have an 'index' operation? Take a look at the `services.services.api.php` file in services module, docs folder.

In the node resource, you have several different 'operations' ( retrieve, create, update & index, .. ). Here's the snippet you should look at:

```
$node_resource = array(
    'node' => array(
      'operations' => array(
        ..
        'index' => array(
          'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/node_resource'),
          'callback' => '_node_resource_index',
          ..
        ),
      ),
    ),
  );
  return $node_resource;

```

GET request to endpoint + resource will trigger 'index'. Read more about it here https://drupal.org/node/783254
> 0 votes

---
Tags: services
---


# Question
Title: Is it possible to get access to files uploaded via FTP in the media module in Drupal 7
I installed media module to select files from server instead of directly upload them but in the `library` tab only the `http` uploaded files are available not the FTP uploaded files. Is it possible to get access and select FTP uploaded files via `media` module?

# Answer
> Is it possible to get access and select FTP uploaded files via media module?

No.

When you upload the files yourself (via FTP or some other means that is not part of Drupal), they will not be recognised or known by the Media module.

There are a helper module called Filefield Sources that let you add files downloaded with FTP to Drupal media management modules. A variation called IMCE Filefield currently integrates with the IMCE module, but there is AFAIK *nothing* similar for the Media module.

It has suggested to integrate Filefield Sources with the Media module. However, there does not seem to be anybody working on it, (just a lot of people who want it).

If you *really* want this, you probably need to add this to the Filefield Sources yourself.
> 2 votes

---
Tags: entities, media, files
---


# Question
Title: Error line appears when using drush 7.x.5.9 -- 32-bit executable?
I keep getting the line "/\[~\]/drush/drush: line 49: /sw/bin/tput: Bad CPU type in executable" in drush 7.x.5.9 on OS X 10.9.2 Core 2 Duo. I think it's related to a 32-bit executable running on a 64-bit-capable processor. Any ideas? It has only happened since I upgraded to 5.9.

# Answer
Try running `tput cols` from your shell. Drush is running this command to determine how many columns wide your terminal is. You could convince Drush not to call TPUT if you instead `export COLUMNS 80` (e.g. in bashrc), but it's probably better to figure out what's wrong with your tput executable. This is possibly related to an installation problem that is independent of Drush.
> 2 votes

---
Tags: drush
---


# Question
Title: IMCE file browser doesn't list the files in the Directory path that are uploaded by FTP
I installed `IMCE` and `Filefield_sources` modules to browse the files on the server. my website is on the `localhost` yet. the directory path of `User-1` which is assigned to the administrator is set to `<root>/temp_files` but when I click on the browse file link in the add new content page it only displays files the are uploaded via IMCE file browser not the files I uploaded in the Directory path. why ?

---

UPDATE:

my OS is Windows so I guest it is not permission related.

# Answer
found it!

Instead of using Filefield\_source module I should use the IMCE for FileField module, that's all. Details from project page:

> IMCE for FileField allows users to select files from IMCE File Browser. It supports FTP uploaded files by automatically registering them as IMCE files thus making them usable in a FileField.
>
> How to use
>
> * Go to your FileField settings page.
> * Check the box saying Allow users to select files from IMCE File Browser for this field
> 1 votes

---
Tags: files
---


title: Time Limit on Comment Edit

text:
# Question
Title: Time Limit on Comment Edit
Let's say a user is registered and posts a comment to a node but didn't like the comment so he/she wants to edit it. I would like to limit the amount of time the user has to edit the comment. After this time has elapsed they should not have the ability to edit the comment, only they will need to contact an admin to do that.

How would I implement this or is there a module to help me accomplish this.

# Answer
Sounds like you're looking for the Edit Limit module.

> Edit Limits adds certain limits to editing nodes and comments. This can set the number of times a node can be edit. This can also set a time frame for nodes to be edited, as well as a different time frame that comments can be edited.
>
> Comments can be set to only be limited within a given time frame. Site administrators can set the number of seconds after a comment is initially posted before it can no longer be edited. Time remaining will be displayed to the user.

Unfortunately, the module is not well documented, but here is an example of how you may use to provide a three minute grace period for editing own comments:

First navigate to *Administration » People » Permissions*. Under *Comment*, enable the permission "Edit own comments" for whatever role you want to have this permission (typically "Authenticated user"). Scroll down to the bottom of the screen and press "Save permissions".

Then, navigate to *Administration » Configuration » Content authoring » Edit Limit* and configure the module to enable comment limits, to three minutes, and select the content types you want this to apply to. Press "Save configuration" when done.

This is how it looks like when working:

At the time of writing, it does not work for RTL languages. See this issue: Edit Limit doesn't show edit link for RTL languages for the current state of this bug.
> 2 votes

---
Tags: 7
---


# Question
Title: generate a coupon automatically after checkout
I have a gift store, customers buy a gift cards. I want to generate a gift code after checkout based on the giftcard they bought (I have gift cards from £25 to £200). they can also buy a gift (product) directly. so the cart might be a mixture of giftcard and products. how can I create a coupon after checkout? I will email them this code after successful checkout

there is no action for creating coupon automatically in rules.

# Answer
Here is a little help.

Actions

1. Add Action - Entites - Create a new entity - select Commercce Coupon - Continue - Save
2. Add Action - Data - Set a data value - select the field you want (ex. entity-ecreated:commerce-coupon-number-of-uses) - enter the value you want - Save
3. Do the 2. for the fields you want

--

At the end I decided to do my custom Rule action for creating a coupon, because is more flexible.
> 1 votes

---
Tags: commerce
---


# Question
Title: Send Billing Information from Address Field to PayPal site using WPS
Referring to the solution here posted by Fnik, I'm trying to implement it on my own custom module. But I thing our two sites are configured differently, and since I'm not too familiar with php, I don't get how to adapt his code for my project.

I use Address Field module for customers billing and shipping address. This doc page explains how it stores its subfields. So I need to access these subfields with the hook Fnik pointed.

My code doesn't do it correctly on checkout. Although syntax seems ok, I get errors (specified bellow) when the function is called. Here is my code:

```
function my_module_commerce_paypal_wps_order_form_data_alter(&$data, $order) {
$profile = user_load($order->uid);
$data['first_name'] = $profile->field_commerce_customer_shipping->commerce_customer_address->first_name['und'][0]['value'];
$data['last_name'] = $profile->field_commerce_customer_shipping->commerce_customer_address->last_name['und'][0]['value'];
$data['address1'] = $profile->field_commerce_customer_shipping->commerce_customer_address->thoroughfare['und'][0]['value'];
}

```

Some context:

* commerce\_paypal\_wps\_order\_form\_data\_alter is a hook from commerce\_paypal\_wps.module
* field\_commerce\_customer\_shipping is a Customer profile reference in Order type order entity.
    + commerce\_customer\_address is a Postal address field type in Shipping information Profile type entity.

Erros, 3 different errors for each $data line:

* Undefined property: stdClass::$field\_commerce\_customer\_shipping in my\_module\_commerce\_paypal\_wps\_order\_form\_data\_alter() (line 27 of ...)
* Trying to get property of non-object in my\_module\_commerce\_paypal\_wps\_order\_form\_data\_alter() (line 27 of ...)
* Trying to get property of non-object in my\_module\_commerce\_paypal\_wps\_order\_form\_data\_alter() (line 27 of ...)

Is is the $profile variable declaration that is wrong right in the beginning, or is it the way to refer to fields and subfields?

Thanks in advanced.

# Answer
The user profile may not have the data saved to it yet, if it is a new user or if you allow anonymous checkout somehow, so it is better to retrieve this data directly from the order. To do that, we have to do some fancy footwork using the entity API - this also avoids any snafus related to database changes or translation arrays. I created a simple function that uses this API to extract an array of address fields:

```
/**
 * Helper to retrieve the profile from an order
 *
 * @param order
 *   The order object
 * @param type
 *   Either shipping or billing
 * @return
 *   The requested data
 */
function _my_module_address_from_order($order, $type="billing") {
  $wrapper = entity_metadata_wrapper('commerce_order', $order);
  $type = "commerce_customer_".$type;
  return $wrapper->$type->commerce_customer_address->value();
}

```

Then I call it thusly in the actual hook:

```
/**
 * Send default billing address to paypal
 */
function my_module_commerce_paypal_wps_order_form_data_alter(&$data, $order) {
  $address = _my_module_address_from_order($order);
  $data['address1'] = $address['thoroughfare'];
  $data['address2'] = $address['premise'];
  $data['first_name'] = $address['first_name'];
  $data['last_name'] = $address['last_name'];
  $data['city'] = $address['locality'];
  $data['state'] = $address['administrative_area'];
  $data['zip'] = $address['postal_code'];
  $data['email'] = $order->mail;
}

```

Note that paypal will not display a billing address unless it gets all of the values address1, city, state and zip as well as first\_name and last\_name!

Much of this solution was arrived at from consulting http://www.drupalcommerce.org/discussions/756/load-address-order
> 1 votes

---
Tags: commerce, entities, payment-gateways
---


# Question
Title: Default Billing Information on PayPal site using WPS
I'm looking for a way to default the Billing Information on the PayPal site when using PayPal WPS to process my payments in Drupal Commerce (v7). Currently, I have the Billing Information defaulted correctly on my Drupal site from the user profile so the customers do not have to enter it again during checkout (already entered when they registered), but do not want them to have to fill their Billing Information on the PayPal site once redirected during payment processing.

I have done this before when creating my own "home-grown" solution using the simple Pay Now button at PayPal by setting input form fields on the page that submits the form to PayPal.

```
<input name="first_name" type="hidden" value="frank" />

```

It would be a far better experience for users that do not have PayPal accounts to have this information defaulted on the "Pay with a debit or credit card" section of the PayPal page.

Thanks for any help! Frank

# Answer
Thanks for your helping clues. I'm using Drupal Commerce V7.x-1.8 with drupal 7.26 and commerce\_paypal WPS 7.x-2.3.

I made a custom module named my\_module. Code Below :

```
function my_module_commerce_paypal_wps_order_form_data_alter(&$data, $order) {
  $user = user_load($order->uid);
  $profile_id = $order->commerce_customer_billing['und'][0]['profile_id'];
  $profile = commerce_customer_profile_load($profile_id);

  $data['first_name'] = $profile->commerce_customer_address['und'][0]['first_name'];
  $data['last_name'] = $profile->commerce_customer_address['und'][0]['last_name'];
  $data['address1'] = $profile->commerce_customer_address['und'][0]['thoroughfare'];
  $data['address2'] = $profile->commerce_customer_address['und'][0]['premise'];
  $data['city'] = $profile->commerce_customer_address['und'][0]['locality'];
  $data['zip'] = $profile->commerce_customer_address['und'][0]['postal_code'];
  $data['night_phone_b'] = $profile->commerce_customer_address['und'][0]['phone_number'];
  $data['email'] = $user->mail;

}

```

Now the customer billing informations are automatically filled up in the Paypal Form. Notice for phone field : I used "night\_phone\_b" field for European phone format. I also hope this helps someone else.
> 2 votes

# Answer
After a little more thorough review of the commerce\_paypal\_wps module I was able to successfully pass default billing information (name, address, email, etc) from my site to the PayPal site. This is helpful if some users may not already have a PayPal account nor want to create one. In this case when they select the "Pay with a debit or credit card" option on the PayPal payment page all their billing information is defaulted from my site as seen on the checkout/review pages so they do not have to enter it again.

The \*commerce\_paypal\_wps\_order\_form\* function in the **commerce\_paypal\_wps.module** creates a hook that you can use:

```
// Allow modules to alter parameters of the API request.
drupal_alter('commerce_paypal_wps_order_form_data', $data, $order);

```

In my \*hook\_commerce\_paypal\_wps\_order\_form\_data\_alter\* function (in my custom module) I set the additional billing address fields as described by PayPal at https://developer.paypal.com/webapps/developer/docs/classic/paypal-payments-standard/integration-guide/formbasics/#id08A6F0SJ04Y (in the "Sample HTML Code for Filling Out FORMs Automatically for Buyers" section).

```
function hook_commerce_paypal_wps_order_form_data_alter(&$data, $order) {
  $profile = user_load($order->uid);
  $data['first_name'] = $profile->field_first_name['und'][0]['value'];
  $data['last_name'] = $profile->field_last_name['und'][0]['value'];
  $data['address1'] = $profile->field_address_1['und'][0]['value'];
  ...
}

```

Thanks for an extensible commerce\_paypal module and I hope this helps someone else.
> 1 votes

# Answer
I answered a variation of this on:

Send Billing Information from Address Field to PayPal site using WPS

However am cross-posting it here since I believe it is a better approach:

The user profile may not have the data saved to it yet, if it is a new user or if you allow anonymous checkout somehow, so it is better to retrieve this data directly from the order. To do that, we have to do some fancy footwork using the entity API - this also avoids any snafus related to database changes or translation arrays. I created a simple function that uses this API to extract an array of address fields:

```
/**
 * Helper to retrieve the profile from an order
 *
 * @param order
 *   The order object
 * @param type
 *   Either shipping or billing
 * @return
 *   The requested data
 */
function _my_module_address_from_order($order, $type="billing") {
  $wrapper = entity_metadata_wrapper('commerce_order', $order);
  $type = "commerce_customer_".$type;
  return $wrapper->$type->commerce_customer_address->value();
}

```

Then I call it thusly in the actual hook:

```
/**
 * Send default billing address to paypal
 */
function my_module_commerce_paypal_wps_order_form_data_alter(&$data, $order) {
  $address = _my_module_address_from_order($order);
  $data['address1'] = $address['thoroughfare'];
  $data['address2'] = $address['premise'];
  $data['first_name'] = $address['first_name'];
  $data['last_name'] = $address['last_name'];
  $data['city'] = $address['locality'];
  $data['state'] = $address['administrative_area'];
  $data['zip'] = $address['postal_code'];
  $data['email'] = $order->mail;
}

```

Note that paypal will not display a billing address unless it gets all of the values address1, city, state and zip as well as first\_name and last\_name!

Much of this solution was arrived at from consulting http://www.drupalcommerce.org/discussions/756/load-address-order
> 1 votes

---
Tags: commerce, payment-gateways
---


# Question
Title: Node title get deleted when saving a translation of the node
Not sure if this is issue of the Title module which I have enabled, or just a bad configuration.

To reproduce:

1- Create a content type: **My content** and checked **Enabled, with translation**

2- Create a english node with title: **My english node title**. Save

3- Create a translation for that node to french with title: **My french node title**. Save

4- Now(after I saved the french node) if I go to edit the english node the **title field** is empty

It happens in the other way too. If I edit and save the english node and then I go to edit the french node the **title field** is empty

How can I trace this? It seems a bug to me, but not sure.

# Answer
Do you want to manage your content type translation at **node level** or **field level** ? You can have a mix of both on the same site if needed, for different content types, but don't mix up within a content type.

If you choose "basic" node translation for content type A, you won't need the Title module, so if it's enabled/in use for content type B, just **don't** "replace" (`admin/structure/types/manage/content_type_A/fields/replace/title`) the **built in** node title of A by a field.

Then when you translate a node from `node/xxx/translate` then `node/add/content_type_A?translation=xxx&target=lang` , everything should be ok.

Read also Gábor Hojtsy explanations which are still valuable about translation settings, or Randy Fay Field translation: First steps
> 1 votes

---
Tags: i18n-l10n
---


# Question
Title: Is linking to autocomplete results possible?
When users search a member profile using Views autocomplete exposed filter text field, is it possible to link the result values? Suppose we are searching some 'XY' user. The results appear as autocomplete drop-down. When we click on them, we are redirected to the member's description page.

Is linking to autocomplete results possible?

# Answer
> 1 votes
Yes it is possible. You can try Search Autocomplete moodule.

Module page says:

```
 This module allows you to add autocomplete functionality to virtually any fields of a Drupal site. During the input, the field will be expanded and offer a list of suggestions before you start the search.
    By default, the module integrates with search forms from the Drupal core Search and Search Block.

Uses either static data, external or internal URL callback or an embeded view style to easily create your suggestions set.

```

For more information go through the module documentation.

---
Tags: ajax
---


title: Suppress VIEW on a specific URL

text:
# Question
Title: Suppress VIEW on a specific URL
There are two URL's on which I want to suppress a VIEW , Below are the urls's :

http://mysite.com/drupal/?q=searchpanel&body\_value=
http://mysite.com/drupal/?q=searchpanel

How can I stop a view to appear on above link .

Thanks for any help in this!

# Answer
Create the view and render it as a block, then go to block settings, set the view to show on every page except:

> drupal/?q=searchpanel&body\_value=
>
> drupal/?q=searchpanel

Edit: Add the created view block to the content area where you want it to display e.g footer, content etc. it will show on every page except the pages above
> 0 votes

---
Tags: views
---


# Question
Title: New role assigned on user account update
I'm thinking about writing a condition ("has new role(s)") using the Rules module to send an email to user to whom a new role is assigned. I need to know how to actually code this...

```
If (user has a new role(s)) {

  //   do something

}

```

I think that, by comparing whether a user has a role before saving and after saving or updating the content, one could tell whether a new role assigned. But I can't figure out how to code it and what API I should use. Please advise.

# Answer
> 0 votes
Just found a way to do it without coding. Works well so far.

**EVENT:** After updating an existing user account

**CONDITIONS:**

1) Data \>\> List contains item - LIST: "account-unchanged:roles", ITEM: "Role A" (Check NEGATE)

**AND**

2) Data \>\> List contains item - LIST: "account:roles", ITEM: "Role A"

**ACTION:** Send mail

Ref: http://goo.gl/Pcz2wN

---
Tags: rules, users
---