# Question
Title: How to access the order total amount in Drupal commerce?
I'm trying to make a block with an image that would change when there is something in his or hger basket (empty basket image when basket is empty, full basket when it's full) My understanding of PHP is weak, but I found this topic :

http://www.drupalcommerce.org/discussions/787/simple-shopping-cart-summary

and I wrote that:

```
<?php
global $user;
$order = commerce_cart_order_load($user->uid);
$wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_total = $wrapper->commerce_order_total->value();
if ($order_total['amount']>0) echo ('<a href="/twotrees/cart"> <img src="/sites/default/files/basketfull.png" > </img> </a>');
else echo ('<a href="/twotrees/cart"> <img src="/sites/default/files/basketempty.png" > </img> </a>');
?>

```

Now on my home server everything worked as expected. On the reomte one i got several show-stopping errors.

If i put the whole thing, I get

```
EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. w EntityDrupalWrapper->set() (line 744 of /profiles/commerce_kickstart/modules/entity/includes/entity.wrapper.inc).

```

By trial and error, I detected that leaving the first two lines

```
global $user;
$order = commerce_cart_order_load($user->uid);

```

are 'innocent'. It's the third one

```
$wrapper = entity_metadata_wrapper('commerce_order', $order);

```

that generates the error. So actually it's the code from that commerce thread that seems to generate the error. To me it seems pretty innocent, though.

As I said, I know very little about PHP, not to mention the internals of Drupal Commerce. I'd be grateful for any suggestions.

# Answer
Try this

```
global $user;
$image = theme('image', array('path' => url('sites/default/files/basketempty.png', array('absolute' => TRUE))));
$order = commerce_cart_order_load($user->uid);

if ($order) {
  $wrapper = entity_metadata_wrapper('commerce_order', $order);
  $line_items = $wrapper->commerce_line_items;
  $total = commerce_line_items_total($line_items);
  if($total['amount']){
    $image = theme('image', array('path' => url('sites/default/files/basketfull.png', array('absolute' => TRUE))));
  }
}

echo l($image, 'twotrees/cart', array('html' => TRUE));

```
> 7 votes

---
Tags: commerce
---


# Question
Title: Use a view to show multiple content types, but only show a field if it belongs to specific content type
I was wondering if the following was possible:

* content type A and B have field X
* create a view to show nodes of content type A and B
* show only field X for nodes of content type B?

# Answer
Yes, i'm pretty sure you could use a module like Display Suite to make a custom `view_mode` for content type B. You could only use this `view_mode` in your View to show everything but field A from Content Type B.

Note, there are other modules that let you define custom display modes as well -- DS is not the only solution.
> 1 votes

# Answer
As tenken said using DS and creating additionnal custom display modes (if needed) is a really good way to go.

I always use display modes in views ("Show: content" and select the display mode) whenever possible. So that when I add a field to a content type I just have to configure the "Manage Display" sections (1 per view mode).

Sometimes I need extra fields to render, to use as token for other settings (rewrite a field, header/footer text, more link,...) or to make grouping. To achieve this I switch the "Show" option from "content" to "fields" and add "Content: Rendered Node" field (that comes with Entity API module). Then the "Show complete entity" display option of this field allows us to choose a display mode (Full content, teaser, list item or any other display mode) and render the nodes.

In some specific situations you may need to share fields between content types. This can be done using "Add existing field" in "Manage fields" section of content types.
> 0 votes

---
Tags: views
---


# Question
Title: Drupal 7 Search Redirect (similar to the old AOL keyword search)
I've searched around for any pre-existing solutions to tackle this problem but so far nothing obvious. Here is basically what I'm after:

1) User enters keyword(s) via core search box

2) If user enters a specific keyword from a list of pre-determined keywords, redirect them immediately to a specific URL/node, e.g:

```
switch ($keyword) {
    case 'brand a':
        drupal_goto('brands/brand-a');
        break;
    case 'brand b':
        drupal_goto('brands/brand-b');
        break;
    default:
       do a regular keyword search . . .
       break;
endswitch;

```

3) If their keyword doesn't exist in the pre-determined list, shuffle them off to the standard Drupal search

Any ideas on how to best accomplish in Drupal 7?

# Answer
If there is only a few you and you don't need any advanced matching you can add a path alias for the search path pointing to the preferred page.

E.g. searching for `brand a` gives you the path `search/node/brand a`. This path you can add as a path alias at `admin/config/search/path/add` pointing to a node of your choice.

For more advanced matching (and a more solid solution) you should probably hook into `hook_search_preprocess()` and do something along the lines of your example code.
> 0 votes

---
Tags: search
---


title: Drupal 7 search through block content

text:
# Question
Title: Drupal 7 search through block content
This is my problem:

I used views module to create several blocks of one content type and displayed those blocks in one basic page. My client would like to have that page included in search results when he searches for some word from those blocks. Seems like Drupal's core search module indexes only content from pages, not content from displayed blocks. Is there some module that I could use, which would index block's content too?

# Answer
> 1 votes
I don't know if it will help you, but the way I solved a similar problem was by using Google Search, which indexes the rendered page.

# Answer
> 1 votes
The Search by page module for D7 will search block content, provided it is placed in the same region of the theme as the main page content. See this issue for details.

If Search by Page does not solve your problem, there is also and abandoned module named Block Search, for D6. It will not work with D7 of course, but it may be a better starting point for a custom module for D7 than starting from scratch.

# Answer
> 1 votes
There is a module Google Custom Search Engine that let you embed a Google site search into a Drupal site. It's still in dev for D7, but seems to work OK.

> Google Custom Search Engine (CSE) is an embedded search engine that can be used to search any set of one or more sites. No Google API key is required.

Read more at www.google.com/cse/.

---
Tags: 7, views, search
---


title: trouble with hook_menu

text:
# Question
Title: trouble with hook_menu
I am trying to set up a new menu item in Drupal 7 and not having any luck. I've tried several examples and have been successful at this in the past, but this is just not working.

The following code is in a module called directory, I keep getting a "page not found" error.

```
function directory_menu() {
  $items=array();

  $items['directory'] = array(
    'title' => 'Employee Directory',
    'page callback' => 'directory_content',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

function directory_content() {
  $content = array();

  $content['raw_markup'] = array(
    '#type' => 'markup',
    '#markup' => 'Testing',
  );

  return $content;
}

```

# Answer
Your code is working perfectly ok. I installed it you can check the screenshot below.
> 0 votes

---
Tags: routes
---


# Question
Title: View to show node titles only when a new comment has been posted?
I am trying to create a view that will show the titles of all nodes only when these nodes have new comments. I need a filter like "Content has new comments" but there isn't any. Can somebody help?

# Answer
You can add a relation in views "comments of the node" and add filter criteria by comment post date. As I know there is no status "new" in comments that's why you can limit them by date.

Or you can add custom field with status but you will need a logic how to add and remove that status.
> 1 votes

---
Tags: 7, views, comments
---


# Question
Title: Is this snippet modification correct? (php snippet in a drupal commerce rule)
I´ve read about the possibility to use this snippet to hide a specific checkout pane (in Drupalcommerce), according to the cart contents.

Could I use this somewhat modified to hide a pane when the user completing the order is registered?

```
<?php
function hook_commerce_checkout_pane_info_alter(&$checkout_pane) {
    foreach ($checkout_pane as $pane_name => & $pane_data) {
        if ($pane_name == 'customer_profile_shipping') {
            $order = commerce_cart_order_load($user->uid);
            if (!empty($order->data)) {
                    unset($checkout_pane['customer_profile_shipping']);
}}}}
?>

```

I understand that I should change this `if (!empty($order->data)) {` maybe to something like this? `if ($user->uid > 0) {`

Is that correct? I want tu hide the pofile2 pane:

So it would be like this:

```
<?php
function hook_commerce_checkout_pane_info_alter(&$checkout_pane) {
    foreach ($checkout_pane as $pane_name => & $pane_data) {
        if ($pane_name == 'customer_profile_shipping') {
            $order = commerce_cart_order_load($user->uid);
            if ($user->uid > 0) {
                    unset($checkout_pane['commerce_p2cp_profile']);
}}}}
?>

```

I´m not sure **how to add that into a rule set**...

# Answer
> 1 votes
You can add your PHP code in action of some rules. For this you will have to enable core PHP filter module. Once you enable it, you go to ADD ACTION in rules and you will find a option "Execute custom PHP code". If the variable you are suppose to use is available there for using with the PHP code then it will work without any problem..

As per your requirement, if you do this by simple small module then also it will work fine as you just have to put this hook in your .module file, declare the module in .info file & enable it....I am suggesting using module as I see you are already checking your condition in code...

---
Tags: commerce, rules
---


# Question
Title: How to make drush to work correctly in Windows?
In Linux drush is comfortable with all Linux native commands. But how to make it working in Windows?

Of course there is a drush installer for Windows and it is correct, but the real question is: how to make all commands to work correctly?

For example `drush sql-dump` returns this error:

```
'mysqldump' is not recognized as an internal command

```

# Answer
I'm going to assume that you're trying to ask how to get drush working in windows.

If you consult the documentation there is a windows installer:

> The Drush Windows Installer provides a convenient way to install Drush and the components it needs in order to run on Microsoft Windows. You may download it from the attachments list at the bottom of this page. Please see the installation guide below for instructions on how to run the installer.

Furthermore, if you're trying to get drush working before 5.7 there's a manual installation guide if you need to:

> The Drush Make command does not work in Windows 7 / Vista, when using Drush release 5.5, 5.6, or 5.7. However, the current development version of Drush fixes this issue! The only problem is there is no windows installer program for this version.
>
> No worries. This article provides instructions for manually installing the latest development version of Drush in Windows.

**Update:**

> For example drush sql-dump returns this error :
>
> 'mysqldump' is not recognized as an internal command

This is a seperate and non-drupal issue. This is caused because drush doesn't know the path to mysql.exe. You need to update your paths in order for msqldump to work. Search super user or stackoverflow regarding mysql, windows and or path together in order to get an answer. I used to know this but it's been too many moons.
> 6 votes

# Answer
To make drush sql-dump work on Windows, verify that the PATH environment variable includes mysql binaries. Locate the Environment Variables dialog, for Windows 7 right-click Computer -\> Properties -\> Advanced system settings -\> click Environment Variables button. Under System variables select Path variable, click Edit and at the end of Varable value: field add the path to your mysql binaries.

For example, if you use WampServer, the typical location for mysql binaries is at

```
C:\wamp\bin\mysql\mysql5.5.24\bin

```

and let's say your Path variable contains these paths:

```
%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem

```

Mind that the paths are separated by ';' and there is no need of quotes if your path contains spaces. After your modification the Path variable should contain

```
%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;C:\wamp\bin\mysql\mysql5.5.24\bin

```

If the Path variable doesn't exist, go ahead and create one.
> 5 votes

---
Tags: 7, drush
---


# Question
Title: How do I prepopulate the value of a taxonomy term reference field on the node creation form?
I'm using an approach similar to the one taken in this question. The difference is that I have a taxonomy term reference field in the user profile that I want to use to prepopulate a custom content type.

To prepopulate a text field on a custom content type with a value from the user profile, I have added this code to a custom module:

```
function MYMODULE_form_MYFORM_node_form_alter(&$form, &$form_state, $form_id) {
 // test if node for has been assigned a NID. If not then populate fields with default data */
  if (empty($form['nid']['#value']) && (!isset($form['#node']->op))){
    global $user;
    $user_fields = user_load($user->uid);
    //set age
    if (isset($user_fields->field_acc_age['und'][0]['value'])){

      $form['field_ad_age']['und'][0]['value']['#default_value'] =  $user_fields->field_acc_age['und'][0]['value'];
    }

```

However, when attempting to prepopulate a taxonomy term reference field from the user profile to the custom content type, the above code doesn't work; there is no error, but the value is not carried across. I assume this is because term references are stored differently in the DB, but I don't understand how to change the code to make it work.

# Answer
Try the following code.

```
function MYMODULE_form_MYFORM_node_form_alter(&$form, &$form_state, $form_id) {
  // Check if the node has a node ID. If not, then populate the fields with the default data.
  if (empty($form['nid']['#value']) && (!isset($form['#node']->op))) {
    global $user;
    $user_fields = user_load($user->uid);
    // Set age.
    if (isset($user_fields->field_acc_age['und'][0]['tid'])) {
      $form['field_ad_age']['und'][0]['value']['#default_value'] = $user_fields->field_acc_age['und'][0]['tid'];
    }
  }
}

```
> 4 votes

---
Tags: hooks, entities
---


# Question
Title: When in admin overlay, submitting form over 400 times
I have built a very simple module which just implements a block with a custom form. When submitted, the content is emailed to me. I show this block on the dashboard, and without the admin overlay it works totally fine.

But when I access the dashboard in the overlay and submit the form, I get no feedback at all (I user drupal\_set\_message() when the email is sent, but that doesn't show up) and half a minute later I find 437 copies of the same email in my inbox.

Unfortunately I have no idea at all where I could start debugging THIS. Maybe the overlay is just a coincidence. But what else could cause this massive submission of email and/or the form?

Any ideas are appreciated.

Thanks,

Victor

UPDATE: The (simplified) code below, this very basic form still has the same problem. How is this possible?

```
<?php

function mvp_form_test_block_info() {
  $blocks = array(
    'mvp_form_test_test_block' => array(
      'info' => 'Test Form',
      'cache' => DRUPAL_CACHE_GLOBAL,
      'properties' => array(
        'administrative' => true,
      ),
    ),
  );
  return $blocks;
}

function mvp_form_test_block_view($delta='') {
  if ($delta != 'mvp_form_test_test_block')
    return array();

  return array(
    'title' => 'Test Block',
    'content' => drupal_get_form('mvp_form_test_test_form'),
  );
}

function mvp_form_test_test_form($form, &$form_state) {
  $form = array();
  $form['sometext'] = array(
    '#type' => 'textfield',
  );
  $form['button'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );
  return $form;
}

function mvp_form_test_test_form_submit($form, $form_state) {
  watchdog('mvp_form_test', 'Form submitted with text '.$form_state['values']['sometext']);
  drupal_set_message('Form submitted with text '.$form_state['values']['sometext']);
}

?>

```

# Answer
Not sure what is exactly causing this, but maybe you can use a static variable as a workaround for this issue.

```
function mvp_form_test_test_form_submit($form, $form_state) {
  $sent =& drupal_static(__FUNCTION__);
  if(!$sent) {
    watchdog('mvp_form_test', 'Form submitted with text '.$form_state['values']['sometext']);
    drupal_set_message('Form submitted with text '.$form_state['values']['sometext']);
    $sent = true;
  }
}

```
> 0 votes

---
Tags: emails, forms
---


# Question
Title: field_get_items / value when creating new content
I think I am about to lose my mind .. how in earths name do I get the value of a field in a widget during creation? I created a custom field widget, and during creation of new content I want to be able to do the following:

I want to create a custom field that I can attach to any content type. This custom field has two elements, a textfield to search for products in MySQL. And a selectbox. The selextbox should get filled with options that match the letters that the user types in the textfield.

I checked field\_get\_items and a lot more, but I just cannot get it. The code below has elements from a form that I made, so please just overlook those parts. I used DPM($something); everywhere trying to see if I can see the value of $element\['searchfield'\] anywhere ..

$items = field\_get\_items('node', $node, 'searchfield'); .. doesnt work, but from what I understand this is only to be used after the node is created .. ie to retrieve the added values, I NEED the values during runtime ...

```
/**
* Implements hook_field_widget_form().
*/
function field_zoekproduct_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  switch ($instance['widget']['type']) {
    case 'field_zoekproduct_field' :

      $element['searchfield'] = array(
        '#title' => t('Zoek naar een product'),
        '#type' => 'textfield',
        '#maxlength' => 115,
        '#size' => 55,
        '#weight' => 0,
'#default_value' => 'zoek...',
'#attributes' => array('onfocus' => "this.value = '';"),  //when textbox gets focus the default value will be removed
'#ajax' => array(
  'event' => 'change',
  'callback' => 'zoekproduct_zoek_getypte_text',
  'keypress' => true,
  //'effect' => 'fade',
  'wrapper' => 'dropdown-second-replace',
),
    );

```

**// with the piece of code below in a form module I can get the value of the textfield in $selected and therefor am able to fill my select with options from the database that match $selected .. now How do I do the same with a custom field????**

```
$options_first = zoekproduct_maak_een_eerste_selectie();
$selected = isset($form_state['values']['searchfield']) ? $form_state['values']['searchfield'] : key($options_first);

$element['overzicht_producten'] = array(
'#type' => 'select',
'#title' => t('Overzicht producten'),
'#prefix' => '<div id="dropdown-second-replace">',
'#suffix' => '</div>',
'#size'=>1,
'#validated' => TRUE,
'#options' => zoekproduct_zoek_naar_getypte_text($selected),
'#default_value' => isset($item['overzicht_producten']) ? $item['overzicht_producten'] : '',
'#ajax' => array(
  'event' => 'change',
  'callback' => 'zoekproductfield_selecteer_product',
  'wrapper' => 'find_product',
),
);

      break;
  }
  return $element;
}

```

# Answer
> 0 votes
One option would be to take advantage of *states* (see states and/or forms reference).

Here is an example... It's by no means perfect but hopefully it will give you an idea of how *states* work:

```
$options_1 = array('Option A', 'Option B', 'Option C');
$options_2 = array('Option D', 'Option E', 'Option F');
$element['overzicht_producten'][] = array(
  '#type' => 'select',
  '#title' => t('Overzicht producten'),
  '#options' => $options_1,
  '#states' => array(
    'visible' => array(
      // To make this select menu visible, type "Visible1" (no quotes) into the "searchfield" box.
      ':input[name="searchfield"]' => array('value' => 'Visible1'),
    ),
  ),
);
$element['overzicht_producten'][] = array(
  '#type' => 'select',
  '#title' => t('Overzicht producten'),
  '#options' => $options_2,
  '#states' => array(
    'visible' => array(
      // To make this select menu visible, type "Visible2" (no quotes) into the "searchfield" box.
      ':input[name="searchfield"]' => array('value' => 'Visible2'),
    ),
  ),
);

```

Hope that helps... :)

# Answer
> 0 votes
So after a loooong puzzle .. I found the answer

You can get the values during creation with doing the following:

```
$selected =  ($form_state['values']['field_zoekproduct']['und']['0']['searchfield'];

```

---
Tags: 7, entities
---


title: Adding comments to user profiles

text:
# Question
Title: Adding comments to user profiles
I would like users on my site to write "feedback" of other users.

My thought is to have a content type called Feedback, and create a view of it, to preview at the foot of the user page. I can also put the main display of comments on its own views page.

Well, that's the display of them covered, but how do I enable them to be written? ie, link from the profile to create Feedback, and have it relate to that profile.

Also, Profile2 looks lacking, because you cannot control URL output.

# Answer
You can use the entity reference field. Entity Reference module provides the autocomplete field for the user reference.

Add an entity reference field on the feedback content type. This field is autocomplete field. So whenever you create a feedback you can select the name of the user for which you want to add the feedback and refer the same.

Still if you are unclear then provide me some more info so i can help you out..

**Update:** In your case you have to create a link on the user profile page and add the name of the user being viewed in the query string. So if you are viewing the profile of user1 then on the user profile you can generate the link **$base\_url/node/add/feedback?name = user1**

Now when any one clicks on that page you will be redirected on the node creation page and you can get the argument value from the URL. You can set this argument value in the form field using hook\_form\_alter() hook.

**Update 2:** I found something like your question here
> 1 votes

---
Tags: nodes, users, views
---


# Question
Title: Submit handler: Prevent other handlers from running in certain circumstances only
I'm creating a custom module which adds a submit handler to a form. The idea is that it checks whether a hidden "honeytrap" field has been filled in.

If the field has been filled in, a success message is shown, but the form content is not e-mailed. If the field has not been filled in, the form is submitted as normal.

**I don't want to use a form validator here** (so this answer on DSE is unfortunately no use). I want the spam robot to think that the form has been submitted, so that it doesn't try again and learn about my special field.

At present, I have the following code:

```
function par_report_repair_form_webform_client_form_26_alter(&$form, &$form_state, $form_id)
{
    array_unshift($form['#submit'], 'honeytrap_submit_handler');
}

function honeytrap_submit_handler($form, $form_state)
{
    // what goes here?
}

```

I'm not clear what to put in my submit handler. I'd like the following behaviour:

* If the honeytrap field *has* been filled in, display a "success" message but **don't allow any additional handlers to run**
* If the honeytrap field *hasn't* been filled in, continue as normal.

Any suggestions? I've tried simply setting `$form['#submit']` to be an empty array, but that didn't help.

# Answer
By the time your submit handler is running you cannot change the other submit handlers that are running.

What you could do is make sure your form alter runs last (change the weight of your drupal module in your install file to a highier number to make it run later). That way you can be a bit more sure that no one else is adding submit handlers after your form alter.

Then in your form alter do something like this:

```
// Add the original submit handlers to the form state for us to use later.
$form_state['original_submit_handlers'] = $form['#submit'];
// Replace the original submit handlers with out own.
$form['#submit'] = array('honeytrap_submit_handler');

```

Then in your submit handler:

```
if (honey_trap_fails) {
  // Do whatever, but don't call the original submit handlers.
}
else {
  // Do whatever, and then:
  // Call the original submit handler because it was a successful submission.
  // Replacing yours as it has already been called.
  $form['#submit'] = $form_state['original_submit_handlers'];
  form_execute_handlers('submit', $form, $form_state);
}

```

There is something important to take into account here: If there are submit handlers on the button that was clicked then they will take precedence over submit functions attached to the form. See form\_execute\_handlers() for a bit of further insight on how to handle button submit handlers.
> 5 votes

---
Tags: forms
---


# Question
Title: How to filter latest 10 days from the current date in Views
I have created a listing page for News in Views. I wish to filter the news, just to show the latest 10 days from the current date. I wonder how to achieve this through Views.

# Answer
You can set it using filter criteria. Look at the snapshot below.

Look at the Pist date (\> -10 days),by adding the field **post date** in the filter criteria and setting to -10 days will give you the nodes created in last 10 days
> 5 votes

---
Tags: views
---


# Question
Title: How does Drupal handle concurrent user creation?
I can't understand a specific part of the Drupal code, namely this snippet:

```
  $account->uid = db_next_id(db_query('SELECT MAX(uid) FROM {users}')->fetchField());

  // Allow 'created' to be set by the caller.
  if (!isset($account->created)) {
    $account->created = REQUEST_TIME;
  }

  $success = drupal_write_record('users', $account);

```

This is from the Drupal 7 code

My question is about concurrency. I imagined that two concurrent sessions are executing this and because the lack of transaction handling here they might try to insert two records with the same uid.

Can you tell me why this works in production? How is it possible that Drupal uses no transaction management although for example creating a node usually involves writing records into many different tables.

# Answer
> 3 votes
> How is it possible that Drupal uses no transaction management?

It's not. The code you're querying is part of `user_save()`; the very first line in that function is:

```
$transaction = db_transaction();

```

The rest of the function is wrapped in a `try...catch` that explicitly rolls back the transaction upon exception. The same is true for `node_save()`, and plenty of other core functions that require transactions.

See the `db_transaction()` docs for more info.

---
Tags: 7
---


title: Gallery Jquery Pager

text:
# Question
Title: Gallery Jquery Pager
I have created a "partners" block in the rightmenu of my theme .. it works perfect and all, but it shows only 6 partners (set from views settings) with newest first .. now my problem is i want to have a "view all" button, also i want to have a pager with jquery transition to view next 6 partners etc.

how can i do this? also, what modules do i need for this?

Thank you in advance

# Answer
Try to use this module views\_load\_more
> 0 votes

---
Tags: views, javascript
---


# Question
Title: Datetime retrieved from db is 7 hours off?
I am having trouble displaying the correct date, well actually its only the time.

In the db the date is stored in this form: `2012-09-28 23:30:00`

That is the value for a date of an event.

When I retrieve it using this script:

```
$ttdate = $obj->field_date_test_value;
$nttdate = strtotime($ttdate);
$okdate = format_date($nttdate, $type = 'medium');
print $okdate;

```

...it works fine but the time is off by 7 hours. So instead of showing `Fri, 9/28/2012 - 4:30pm` it shows `Fri, 9/28/2012 - 11:30pm`.

Note that on the event's page, drupal retrieves the correct time...

I did some research and I figured it has to do with the timezone? But I have the timezone set to Los Angeles so I am not quite sure what is going on. Maybe its my script?

# Answer
> 2 votes
Date/times are generally stored in the database as UTC, so if your timezone is UTC -7 hours then all your times will be out by 7 hours (between the database and your expected output).

When you load a date from the database you then have to apply the desired timezone before displaying it or doing calculations on it or whatever.

For some examples you can see what the date module does with: date\_formatter\_process() and date\_tokens()

It creates a new `DateObject and then runs date_timezone_set($date, timezone_open($timezone));` on that date to set the timezone.

If you just want to use the site timezone (or user selected timezone) you can use date\_default\_timezone().

There is also the drupal core function format\_date(), which takes a timestamp, a date format, and a timezone and gives you the output date. That would be the easiest option.

For example, you might do this:

```
$okdate = format_date($nttdate, 'medium', '', date_default_timezone());

```

# Answer
> 0 votes
It sounds like the time is being stored as a unix timestamp, meaning the value will always be GMT/UTC no matter what your servers timezone is set to.

A unix timestamp will always return the number of seconds from `1970-01-01T00:00:00Z ISO 8601` or `00:00:00 UTC on 1 January 1970`

If you store a datetime set created in America/Los\_Angeles time it will be stored with a 7 hour difference when properly converted and stored as a unix timestamp (always GMT/UTC).

I will update my answer if you will post the DB type and DB Field type that is being used to store the datetime data.

---
Tags: datetime
---


title: How do I show content in an overlay?

text:
# Question
Title: How do I show content in an overlay?
I want to display some content, returned from an AJAX call in an overlay or popup.

Do you have any idea on how I can do it?

# Answer
> 8 votes
If your are using Drupal 7 you could make a use of the administrative overlay with a custom module.

You will need 3 hooks in your CUSTOM\_MODULE\_NAME\_HERE.module file :

```
/**
 * Implements hook_menu().
 */
function CUSTOM_MODULE_NAME_HERE_menu() {
  $items = array();
  $items['your/path/to/your/page'] = array(
     'page callback'    => 'CUSTOM_MODULE_NAME_HERE_page',
     'access arguments' => array('access content'),
     'type'             => MENU_NORMAL_ITEM,
  );
  return $items;
}

/**
 * Implements hook_admin_paths_alter().
 */
function CUSTOM_MODULE_NAME_HERE_admin_paths_alter(&$paths) {
    $paths['your/path/to/your/page'] = TRUE;
}

/**
 * page callback
 */
 function CUSTOM_MODULE_NAME_HERE_page(){
    $output = 'your page content';
    return $output;
}

```

# Answer
> 5 votes
Along the lines of ipwa's response above, the overlay paths module is simple and easy to use for this type of thing.

# Answer
> 4 votes
The easiest way is to implement a simple custom module that does the following:

* Implement hook\_menu() and defines a custom *page callback*
* Return the content you want in your page callback
* Include your favourite jQuery lightbox plugin (either via a Drupal module or by hand)
* Add a custom javascript file via drupal\_add\_js()
* In your custom javascript file, bind the event of your choice and make the lightbox plugin load external content from the URL in your hook\_menu()

If you prefer, you can always have your hook menu return the content in JSON form, using drupal\_json() and add it as inline html to the lightbox, instead of referencing an external file.

# Answer
> 2 votes
A very easy way to do this from Display node as a popup window: There are a lot of solutions for this kind of stuff. I would do it in the theme layer to have something really light. You can also use the variety of popup modules for this. One simple way to do this, is use the Lightbox2 module, checkout this documentation page: http://drupal.org/node/252260

# Answer
> 2 votes
To show a whole page content in a overlay(popup), use overlay\_path module.

Install the module and in configuration u include the url of the page you need to show as an overlay(popup).

# Answer
> 0 votes
you can use some simple jquery and css as mentioned here and load an external page by ajax.

# Answer
> 0 votes
Simple dialog module can be useful, it's easy to implement a link to your popup page

---
Tags: 7, modal-dialogs
---


# Question
Title: Create node fields with values that change every week but old values are being stored
My company has about 15 oil tanks. Every week a guy checks the remaining oil in every tank and writes down the numbers. I want to create a visual representation of the remaining oil in every tank. I have a drupal installation already setup in my server and I thought that I could incorporate a solution in the existing site. What I have done so far:

* I have created a new content type called tanks.
* Created the various fields (like tank\_id, volume, status etc) that will hold information about the tank.
* I also have a field that is called latest\_amount where I want to store the most recent measurement of oil in the tank.
* I have also written some basic php code that does a simple division (latest amount/volume), gets the percentage of the tank that is full and I'm thinking about drawing with html a basic shape that will be green if it's above 75%, yellow if it's 25%-75% and red if it's below 25% (maybe there is a module that can help me with this drawing).

My problem is that I want to keep past measurements so that I can create a graph with these percentages over the last 3 months. Is there any way for me to keep these stats along with the date that the specific field value has been added? Also, is there a way to restrict node editing to only adding a new value in the latest\_amount field every week (i.e. not being able to alter any other information about the tank)?

# Answer
> 0 votes
you can add another content type named "measurement" and add number (dates and quantities) related fields in it.

with references or entity reference it's easy to associate those measurement nodes to your tank nodes. simply create a view then and sort it the way you want.

# Answer
> 0 votes
Check the module field\_collection

> Provides a field-collection field, to which any number of fields can be attached.

1. add field collection to your tanks content type
2. in collection add fields for stats like date, amount etc
3. after that you can store latest amount and display them in views, charts etc

# Answer
> 0 votes
There are several ways to do this.

Your `tanks` content type already holds the measurements. To keep past measurements, all you need to do is to change the field `latest_amount` to be `this_weeks_amount`, and also to make sure you create a *new* node every week, when new measurements are reported. As long as you do not delete or overwrite the previous nodes, all the past measurements will be in the database and you will be able to display it as a text time-series (but not a graph) with *Views*, or to create some custom code that can pull data from the all the nodes kept in the database to create the time-series graph, etc.

But if I was doing this, I would set up a custom entity to hold the time-series in my database, rather than using nodes. This is a tiny bit more work to do, but allows you to get rid of all the excess baggage that gets inserted in the database when you use *fields* to create a new content type.

---
Tags: 7, entities
---


# Question
Title: Load CKeditor with Simplified Toolbar on dynamically created page element
Drupal 6 ckeditor 3.6.4

I have page that loads the text area dynamically, so I am using

```
  CKEDITOR.replace('textarea-id');

```

Which works, but it is bringing in the full toolbar. I would prefer that the simplified toolbar is used, but it would also be acceptable to use the toolbar I have defined if loading the simplified is not possible. Least desirable would be to hard-code the toolbar, but I consider that a last resort. How do I accomplish this?

I have tried

```
 CKEDITOR.replace('textarea-id',
    {
        toolbar : 'myprofile'
    });

```

Which throws js error: Type x is undefined , I think related to the fact that it cant load the profile. Suggestions?

# Answer
For better or worse, this is how I did it:

http://joe-riggs.com/blog/2012/11/drupal-ckeditor-load-configuration-settings-on-dynamic-page/
> 1 votes

# Answer
This is an example to load custom buttons in the Ckeditor toolbar:

```
CKEDITOR.replace('textarea-id');

CKEDITOR.config.toolbar = [
   ['Bold','Italic','Underline','SpellChecker','TextColor','BGColor','Undo','Redo','Link','Unlink','-','Format'],
   '/',   ['NumberedList','BulletedList','JustifyLeft','JustifyCenter','JustifyRight','Font','FontSize'],
    ] ;

```
> 0 votes

---
Tags: 6, wysiwyg
---


title: Expose date filter in views

text:
# Question
Title: Expose date filter in views
So, what I want is a dropdown to filter news by months, the select box is like that(months are grouped by years):

```
- All
-- 2013
--- Jan
--- Feb
--- Mar
--- ...
-- 2012
--- Jan
--- Feb
--- Mar

```

How I can do that ?

Thank you for your Help.

# Answer
You just need to create groups for these results:

you want to group the results by Year and Month, so you need to add two fields:

**First field for group by Year \[Content: Post date\]:**

**Second field for group by Month \[Content: Post date\]:**

**Add filters and sort criteria:**

**Choose format settings:**

**Group yearly results:**

**Group monthly results:**

**That's it!**

Your results:

```
- 2013
-- Jan
--- tilte #1
--- ...
-- Feb
--- title #4
--- ...
--- Mar
--- title #6
--- ...

```
> 1 votes

---
Tags: views
---


# Question
Title: Related Content Block for a Views Page, Not a Node Page
I've created a views page that displays the most recent node of a certain content type. I have an image field in that content type that I would like to have displayed in the sidebar in a related content block. I have achieved this on the individual node pages using the contextual filter of NID with Content ID from URL. However, the views page is not the node page, so the related content block will not appear. How would I achieve this? Thanks!

# Answer
You created views block which display current node images - right? What images you want to display on views page?

You can create another views block where display images from some nodes(add some term to nodes to mark them) or images from recent nodes which views shows.
> 0 votes

---
Tags: views
---


# Question
Title: Empty response after a callback in form_alter
I am trying to add a new field in a preexistent form and invoke a callback. The response of the callback is alway an error with an empty response:

> An AJAX HTTP error occurred.
> HTTP Result Code: 200
> Debugging information follows.
> Path: /system/ajax
> StatusText: OK
> ResponseText:

ResponseText is always empty.

The code I use in `my_form_form_alter()` is the following.

```
$form['country_views_exposed_form'] = array(
  '#type' => 'select',
  '#title' => t('Country'),
  '#options' => array(
    'sl'  => 'Select...',
    'au'  => 'Australia',
    'nz'  => 'New Zealand'
  ),
  '#ajax' => array(
    'callback' => '__my_callback',
    'wrapper' => 'country-views-exposed-form-wrapper-',
    'method' => 'replace',
    'event' => 'change'
  ),
  '#attributes' => array('class' => 'views-exposed-widget')
);

```

All I put in `__my_callback()` produces the same result: I don't get a clean response.

```
function __my_callback(&$form, &$form_state) {
  return $form['states_views_exposed_form'];
}

```

# Answer
I have resolved. Exposed form fields don't are the same of 'normal' form fields in drupal. I have applied the patch #46 listed here: http://drupal.org/node/1183418
> 2 votes

---
Tags: ajax, forms
---


# Question
Title: How to group views rows by year using date field?
I have a content type with a date field. I need to output them grouping by year, i.e.

```
2011

- nodeA 2011-09-01
- nodeB 2011-01-29

2010

- nodeC 2010-12-08

```

How can I do that?

# Answer
> 16 votes
1. Add a second date field to the view.
2. In the configuration of that field

1. Configure the field to only display the year
    2. Exclude the field from display
3. In the format settings of the view, group by this field.

# Answer
> 16 votes
@phils suggestion needs an update: just strip html for the field (in the Rewrite Results section). I can validate that this worked for me where @Oswald's solution did not.

# Answer
> 1 votes
Disable RDF-Module from Core.

Had the same problem and after searching for hours I finally stumpled upon this hint from KarenS: http://drupal.org/node/1253562#comment-4886998 Just disable the RDF-Module and maybe re-edit your date formats.

---
Tags: 7, datetime, views
---


# Question
Title: Is there a variable that keeps track of which pages are enabled or disabled in Page Manager?
I'm using the Features module and I'm tired of manually enabling/disabling pages (user\_edit, user\_view, etc.) Is there a variable that I can add to Strongarm to control this in code?

# Answer
Yes, there's a variable per page of the form "page\_manager\_MACHINE\_NAME\_disabled", eg. "page\_manager\_node\_view\_disabled". You need to set it to FALSE using Strongarm to enable the corresponding page.
> 3 votes

---
Tags: features, configuration, strongarm
---


# Question
Title: Allow a user to flag the same node/user multiple times
The flag module allows flags to be defined per user. For example, User 1 can flag Node A and B, and User 2 can flag Node A but not Node B.

In this situation, a flag is either on or off per user. However, is there a way to allow a single user to flag the same piece of content multiple times?

Use case: I have created two content types, **Message** and **Reply**. I want to limit the number of times that users can reply to a message (say, to 3). To do this, I was going to use Rules to automatically flag the original *message* each time a user writes a *reply*. However, since content is either flagged or unflagged, I don't see any way to allow a user to flag the content multiple times.

Any ideas on how to approach this use case are welcome, including using modules other than the flag module.

# Answer
> 2 votes
How about using the Five Star module and incrementing the rating each time? Eg, first reply, rate the message 1. Next reply, re-rate the message 2. When you get to 3 (or 4 or 5) don't allow more. You could implement this directly with the Voting API if you wanted to, too, I'd imagine, if you needed higher than 5.

---
Tags: flags
---


# Question
Title: Strict warning: Only variables should be passed by reference
I am getting this error on this line in my code. I'm guessing I need to break this line down a bit. Any comments would be great.

```
$promobox_id = reset(array_keys($result['fieldable_panels_pane']));

```

# Answer
> 3 votes
That's not a Drupal error. It's a PHP error. You're getting it because the `reset` function expects an array to be passed by reference. You are passing it the return value of the `array_keys` function, which does not return its result by reference.

If you want to break down your code to avoid this error, try something like this:

```
$array_keys = array_keys($result['fieldable_panels_pane']);
$promobox_id = reset($array_keys);

```

Also, consider seeing this page for more information: http://www.php.net/manual/en/language.references.pass.php

# Answer
> 0 votes
Change it to:

```
$arr = array_keys($result['fieldable_panels_pane']);
$promobox_id = reset($arr);

```

`reset()` takes the first parameter by reference, which should be a variable as the exception suggests. (not the direct result of a function execution).

You'll probably see a lot of these if you've recently upgraded to PHP5.4.

---
Tags: theming
---


# Question
Title: How to target and remove a given fieldset
I am very new to drupal and have been playing around with lots of different modules and core features. I have now come to an issue I have been trying to solve for the pass 48hrs without finding the right solution.

I am building a forum, using the core module, but my problem is when users post a new topic / comment, they are given the option of selecting which 'text format' they want to use. I want drupal to take it as given that filtered HTML is the only option and not offer the use a 'plain text' format.

I can just target the fieldset's id with 'display:none' in CSS and that does work, will not display any more, but I would like to know how to remove the fieldset code itself.

I have tried this,

```
function THEMENAME_form_alter(&$form, $form_state, $form_id)  {
  unset($form_id('edit-body-und-0-format');
}

```

The 'edit' id is the id on the fieldset for the text options, but all this does is give me the white screen of death....

So what I am doing wrong?

Many thanks for any help given....

Glenn.

# Answer
There's a wee bit of confusion in your PHP code there; you're calling a function with the same name as the string passed in `$form_id`, and passing `'edit-body-und-0-format'` as a parameter.

What you need to do is change the relevant field in the `$form` array, e.g.

```
function THEMENAME_form_alter(&$form, $form_state, $form_id)  {
  $form['edit-body-und-0-format']['#access'] = FALSE;
}

```

Using `#access` is preferred to `unset()`; there might be something in a validation/submit handler that's relying on the existence of those fields, whether or not values have been submitted this time round, and removing it completely might break those (or cause some unpleasant warnings).

If you haven't already installed it, the Devel module is a must for development; you can use the `dpm()` function to inspect PHP elements on the front end. If you add `dpm($form);` to your current function, for example, when you visit the page you'll see a nice structured output of the `$form` variable making it easy to find the element(s) you want to alter.

Update...

If you're trying to hide the text format options there's a slightly different approach. You need to attach an after build function to the textarea, and remove the format options in there. For example:

```
function THEMENAME_form_alter(&$form, $form_state, $form_id)  {
  if ($form_id == 'some_form') {
    $form['body']['#after_build'][] = 'MYTHEME_body_after_build';
  }
}

function MYTHEME_body_after_build($element) {
  $element[LANGUAGE_NONE][0]['format']['#access'] = FALSE;
  return $element;
}

```

or something very similar.
> 2 votes

---
Tags: forms, nodes
---


# Question
Title: In Drush what is the difference between ard and arb?
In Drush what is the difference between ard and arb commands? When should I use one over the other?

# Answer
They're actually aliases of one another, so you can use either.

If you type `drush help arb` you'll see at the bottom:

```
Aliases: ard, archive-backup, arb

```

And for posterity, `drush help ard`:

```
Aliases: ard, archive-backup, arb

```
> 6 votes

---
Tags: drush
---


# Question
Title: Entity Reference and nested arguments in Views
My site has 3 nodes:

* **Program**, which is a list of **Course** nodes.
* **Course**, which contains basic information about a course you can take
* **Course Date**, a specific instance of a **Course**. Each **Course Date** references one **Course**, and the titles are auto-generated.

The view I'm scratching my head over is

* I need a view that loads on each **Program** node, showing all current **Course Dates** who's Entity Reference matches any **Course** in the current **Program**.

It would be a lot simpler if each **Course** was only in one **Program**, but they aren't.

I've tried Relation and found it too buggy for production. I've tried Reference and Entity Reference, and settled on the latter as it seems more featured.

Would it be possible to automate some kind of reverse field reference? Any tips welcome!

# Answer
Actually Entity Reference does implement reverse pointers, so to speak.

On your program view, which I suppose has entity reference fields to course nodes, first set up a **Relationship** (under the 'Advanced' view section) that will link to the view the specific Course nodes that exist for the current program as entity references.

* If you go to add a relationship, you'll get a dialog that looks like this:

* Set it to filter the potential relationships to ones using 'Entity Reference' fields.
* Select the '**Referenced entity**' field that exists in the Program content type to point to its Courses (whatever you called it). You can choose to change its name to 'Referenced course' or something short like that for later. You can also limit the view to include only Programs that *have* course fields by checking that 'Require relationship' box!
* Now all those course nodes are available in your view (you can add their fields to your view if you need to)
* Next, add one more relationship. This time look for the relationship that is a '**Referencing entity**' (as opposed to 'Referenced entity') for your Course Date node. That will provide a link to all Course Date nodes, which themselves reference the current Course node. When setting up this second relationship, make sure you select the previous relationship to be used in the 'Relationship' dropdown. After all, this reverse reference points to the course node of the current program, not to the current program itself, right?
* Finally, you should now be able to add fields for course nodes and course date nodes that relate to your program, because of these two relationships. Just make sure the fields you add, have the correct Relationship set from the relationship drop-down. That way they will pull from the correct node.
> 1 votes

# Answer
May be you could try (and adapt) this snippet in the contextual filter based on your entity reference field of your view

```
$ Node = menu_get_object ()   // we get the current node
switch ($ node-> type) {          // We can manage multiple scenarios depending on the type of content
  case 'type A':                          // For the content type A
    $ Related_ids = array ();
    $ Related = field_get_items ('node', $node, 'YOUR_FIELD_ENTITY_REFERENCE')    // Get the entity reference scope
    if ($related && is_array ($related) && sizeof ($related)> 0) {
      for ($i = 0; $i <count ($related); $i++) {
        $ Related_ids [] = $related[$ i]['target_id'];
      }
    }
    return implode ('+', $related_ids) // It returns the values of the field entity reference

  default:
    return 0 / / default it returns 0
}

```

See this issue for further informations
> 0 votes

---
Tags: nodes, entities, views
---


# Question
Title: Can I autopopulate between different users' forms with Rules and Webforms or EntityForms?
I need to create a form in which some fields auto-populate with the values submitted on other users' forms. Specifically, the manager has to submit a form documenting the progress of projects a, b, and c. However, the manager needs the option to ask another staffer to complete a form for one of the projects. So when the staffer submits the form, their value of textarea field "Project B Status" autopopulates into the field "Project B Status" on the manager's form. The manager can then edit staffer's text if necessary and submit the final report.

I have tried doing this using both WebForms and EntityForms and have tried using Rules to autopopulate. I cannot get it to work right, but before I continue I would like to know if these are the best modules to use or if I am doing something wrong (as I am fairly new to Drupal).

Many of the answers I have seen on this issue involve editing the actual php, which I would prefer not to do at this point (but will if someone can tell me specifically what to do).

# Answer
> 0 votes
If I were to approach the problem, each project would be a node.

* First install the Field Collection (documentation) and Field Permission modules.
* Create a new Content Type (`admin/structure/types/add`) and call it *Project*.
* Assign the fields you want filled in (`admin/structure/types/manage/project/fields`).
* Add an additional field called *Project Status* of type "Field Collection" and choose "Embedded" as the widget type. Click save, leave **Hide blank items** checked on the next page, then click save again.
* Go to the Field Collections page (`admin/structure/field-collections`). You'll see your new *Project Status* field listed. Click "Manage fields" and add your subform fields here.
* At this point, your manager should be able to create new *Project* nodes, and the *Project Status* field will hold the additional information. You'll need to set up the field permissions so that the staffer role can only edit the *Project Status* field.

Back on your node fields page (`admin/structure/types/manage/project/fields`) edit each field. Near the bottom of each field's settings, look for the **Field visibility and permissions** section. Choose the **Custom permissions** radio button and look at the settings available. For your project, you want to allow your staffer role the ability to edit anyone's value for the *Project Status* field, but none of the other fields.
* Remember to also set permissions to allow the manager role to create *Project* nodes, and the staffer role to edit *Project* nodes (`admin/people/permissions#module-node`).

As an added bonus, you can set the field settings for the *Project Status* field to allow an unlimited number of values. This would allow for updated status as the project progresses. YMMV of course.

---
Tags: rules, forms
---


title: Rendering node contents only

text:
# Question
Title: Rendering node contents only
For the purposes of the Cycle plugin I need to render a node without any external buildup, just the `$content`. Is that possible?

# Answer
In Drupal 7, `node_build_content()` governs the generation of the render array for the node's content:

```
$node = node_load(1);
$content = node_build_content($node);

```

If you take a look at the source for it, you can see how the final render array is built and you can pick and choose what you want in the render array by copying the relevant parts from `node_build_content()`.

For example, if you wanted to just render the node's fields, you might do:

```
$view_mode = 'full';
$langcode = LANGUAGE_NONE;

$node->content = array();

field_attach_prepare_view('node', array($node->nid => $node), $view_mode, $langcode);
entity_prepare_view('node', array($node->nid => $node), $langcode);
$node->content += field_attach_view('node', $node, $view_mode, $langcode);

```

If you did that, `$node->content` would then contain the render array for just the fields without all the extraneous stuff like links or other stuff third-party modules might add.
> 2 votes

# Answer
Great question! This is common when you want to load a node via ajax or some other interactive use-case. My solution is two-fold:

## Create a hook\_menu() entry

The `hook_menu()` entry handles the special path you'll likely want in order to create your naked node without disrupting normal usage. In this case I want `node/%/plain` which for node 46 would be `node/46/plain`:

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

  $items['node/%/plain'] = array(
    'page callback' => '_mymodule_callback',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array(1),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

```

These settings will pass the second URL argument to both our callback and `node_access()`, which handles permissions issues with viewing nodes.

If you think of `node/%/plain` as three parts separated by slashes (part 0, part 1, and part 2), then sending `array(1)` into these callbacks passes along the node ID for them to use.

## Create your callback

```
/**
 * Helper function to render plain node
 */
function _mymodule_callback($nid) {
  $node = node_load($nid);

  if (!empty($node)) {
    // Render
    print drupal_render(node_view($node));
    drupal_exit();
  }
  else {
    // Put 'node not found' msg here
  }
}

```

This function prints out the desired code, then gracefully exits out of Drupal, preserving session data and all the other moving parts within Drupal.

Make sure you use `drupal_exit()`. Using a plain `exit` is bad, m'kay?
> 1 votes

# Answer
Sure, just node\_load() whatever node you want and print out whatever you want out of it. Just be aware that drupal saves whatever the user enters, and then relies upon the rendering to clean it up, so, for example, if you have a text field that you want to be plain text, the user can enter whatever he or she wants in it, and that will be saved into the db as is.
> 0 votes

# Answer
One way to get content on a page without any external markup is by registering a path with hook\_menu() and then output the necessary node parts in the page callback function:

```
function mymodule_menu() {
  $items['somepage/%'] = array(
    'title' => 'Somepage',
    'page callback' => 'mymodule_node_callback',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function mymodule_node_callback($nid) {
  if ($node = node_load($nid)) {
    $content = 'node content you want on the page';
    print $content;
  }
}

```

`somepage/64` would then (once you have modified the page callback function accordingly) get you the content of node 64 for example. It's important to use `print` or similar so that Drupal won't add anything else to the page (`return` would get you the result with external markup added).
> 0 votes

---
Tags: theming
---


# Question
Title: Drupal 7: notify user module recommendation
I'm trying to figure out what the best solution to a project requirement is. The basic premise is that a site needs to have a notify user feature - similar to how Facebook works.

A listing in the site will appear showing the number of notifications (similar to this site actually, on the top left). A sample notification would be: another user commented on your node.

Another possible notification would be "a node was created in a subscribed taxonomy term".

I've been looking at the Notifications module, but I'm not convinced it can do what I need it to do.

Has anyone ever built a solution to this problem? Or am I looking at a lot of custom work?

# Answer
> 3 votes
For the record: The Notifications module will not do what you want. But worse, the D7 port is in alpha and hasn't progressed since 2011-Dec-04, there are 217 bugs in the issue queue and no maintainer in sight. Its maintenance status is listed as "Seeking new maintainer". In other words, this yet another abandoned Drupal module. Unless you're prepared to adapt and maintain this yourself - stay away.

There is a survey page for notifications modules, but it only confirms that what is called a "Notification" module by Drupal developers provides *email* notification, which is not what you want. The type of notofication you want tend to be referred to as "flags" by Drupal developers, so you want to search for "flags" in addition to "notifications".

To get on-screen Javascript notifications (similar to Facebook and Stack Exchange), my suggestion for a starting point is to see whether you can combine the Flag module, the Message module and the Rules module to do what you want. But to get these three modules combined to produce the desired effect will not be trivial.

An alternative solution (first mentioned in a comment by Nigel Waters), you could use the Message module to create the activity stream. Then use Views to generate the stream applicable to the currenly logged in user. And finally use the Menu Badges module to display the number of notifications.

You may also want to read: How to create a basic message - notifications system displaying a real time message counter badge?

---
Tags: 7, flags, notifications
---


# Question
Title: How to find the path of the feed for content type in drupal 7?
I wanted to add the path to the feed view display, but I'm not able to know what the path is?

# Answer
You can use the Views module to create feeds. Simply add a new display of type "Feed" and customize the view to contain only the content you want. **You have to set the path** in Feed Settings(enter your own path for example: type feed or any path you want).

To add a "Feed" display:

Go to your views administration and select the view you want to edit. Towards the top of the page you will see the "Displays" heading with an "+ Add" button. Click that and select "Feed" . You will then have a Feed display that is using the Default Display's settings.
> 0 votes

---
Tags: feeds
---


title: How to add tags to my sandbox module?

text:
# Question
Title: How to add tags to my sandbox module?
I 'm working on a sandbox module, which is text\_or\_user\_reference field.

To release the module, I have to create a branch of the module i.e 7.x-1.0

Since beginning of the module development I was not aware with this thing, so I was working on master branch.

Now I have to add the tags to create the branch. To create the tags I followed this guide on drupal.org

These are the commands to push and create the tags:

> git tag 7.x-1.0
>
> git push --tags
>
> git push origin tag 7.x-1.0

I have applied all the commands, but I am not able to see whether tags are created or not.

My problems:

* How to check whether tags are created or not ?
* Do I have to seperately assign to tags to each file like `.module` file, `.install` file etc.
* When I go to Edit of the project and select the dropdown **version to work from** it doesn't show the tags/version I created i.e. 7.x-1.0

Consider this command:

> git branch -v

What should I expect as a result after I run it? The list of all the files of current branch?

# Answer
> 3 votes
In *git*, the terms "branch" and "tag" always applies to the whole repository, not to the individual files. A branch denote is a *series* of commits (so you always use an "x" instead of specific version number for a branch). A tag is a label for a *specific version*, so you specify the version number (e.g. `1.0` for the first released version, `1.1` for the next, and so on.)

The command `git branch -v` will give a verbose listing of the current head. It should, in the case of Drupal 7, start with a line `* 7.x-1.x`. If it says `master` on the first line, you've not set things up right.

Before adding tags, you need to get your project on a `7.x-1.x` *branch*. In your local repository, do the following to checkout branch `7.x-1.x` and delete branch `master`, and push those changes to the remote:

```
git checkout -b 7.x-1.x
git branch -d master
git branch -v
git push origin 7.x-1.x
git push origin :master

```

After you've made sure the branch is `7.x-1.x`, you can go ahead and add a tag to your release.

You can use the commands you refer to, to tag. To see all the tag(s) in the local repository:

```
git tag

```

After pushing to the remote, if you've done this correctly, you should be able to click on the *Version control* tab and find the `7.x-1-x` branch in the *Version to work from:* pull-down menu. If you retain the `master` branch, make sure that you make the `7.x-1.x` branch the default.

---
Tags: version-control
---


# Question
Title: Anonymous user having user relationships
I have come up with a peculiar problem. IO am using the User Relationships module for my Drupal 7 site. The issue is that i had given privileges to the anonymous user to view user profile. The anonymous user however cannot be a part of the user relationship but that user had clicked on that action and now somehow or other when i log in as an authenticated user and see the view which i have created to show me the users who are following me, i see i am followed(the name of the relationship) by an Anonymous user. How can i remove this. i also checked in the databases but i saw nothing regarding this...no request with user id 0. i also have all the correct permissions.

Any Suggestions

Regards

# Answer
> 0 votes
I ran into a very similar issue... Here's the code I used (modified to reflect the affected `$user->uid` as `0`):

```
<?php
$anon_uid = 0;
$admin_uid = 1;
// The next line makes it appear as though the relationship was deleted by the original
// user in the relationship. You might want to change the value though since Anonymous
// should normally be denied access to do this. For example, to make it appear as
// though each of Anonymous's relationship was deleted by user 1, change $anon_uid
// to $admin_uid (next line ONLY)
$anon_deletedby = user_load(array('uid' => $anon_uid));
$anon_friends = user_relationships_load(array("user" => $anon_uid));
foreach ($anon_friends as $friend) {
  user_relationships_delete_relationship($friend, $anon_deletedby);
}
?>

```

**PLEASE BE SURE TO BACK UP YOUR DATABASE AND TEST THIS IN A NON-PRODUCTION ENVIRONMENT FIRST.**

---
Tags: 7, views, users
---


title: Using drupal_add_content_region()

text:
# Question
Title: Using drupal_add_content_region()
I am trying to dynamically add content into a region.

In the preprocess function, I use the following code.

```
function firsttheme_preprocess_page(&$vars){
   drupal_add_region_content('dev', "I am reserved for development only");
}

```

In the template file, I print the region.

```
<?php if ($page['dev']) print render($page['dev']); ?>

```

Although I am setting some sontents in the dev region, it's always shown as empty array every time.

How do I fix this?

# Answer
As with most things in Drupal someone else has already been there and done it...

http://api.drupal.org/api/drupal/includes!common.inc/function/drupal\_add\_region\_content/7#comment-48353
> 1 votes

---
Tags: hooks, theming
---


# Question
Title: Is there a compelling reason to track sites.php with version control?
I'm wondering if sites.php is a file that should be tracked? I can see it being useful because domains tend not to change for any given site (not true for development, as I usually run a `shortname.local` site alias for ease). But then again, if you're not tracking the actual site folder, then the site folder name could vary from installation to installation potentially, making tracking sites.php potentially a useless cause...

I don't know, I guess I'm looking for guidance here. Typically I do not track the sites folder because it contains generated site files and sensitive database information, so maybe it doesn't make sense to track sites.php?

Looking for some tips from the seasoned pros out there.

# Answer
> 5 votes
We track it. You can have more than one entry in sites.php that points to the same site, so we have one for the production site and then a few more for development purposes.

The file is not sensitive itself, because if you give someone the ability to read the contents of .php files on your webserver, then you have bigger problems! I'd say try and find reasons NOT to keep it under version control.

I have to say Gisle's suggestion of manually logging changes to files seems to be a bit more effort than I'd normally want to put in, to get round a problem that's not really a problem for me to begin with!

# Answer
> 2 votes
I do not track the *sites* folder with version control (more or less for the same reasons you give). However, I have a manually kept log where I keep track of any *permanent* configuration changes I do to the site, including the *sites* folder and `sites.php`. It is not much extra work to keep such a log, and I've found this log more useful than version control because it only contains essential information while when I relied on an automatically generated log, it exposed a lot of short-lived tests and experiments that I no longer care about.

So *I* do not see a compelling reason to track `sites.php` with version control. What I do track (with git) below the *sites* folder is of course the custom themes/subthemes and custom modules that I maintain myself.

---
Tags: 7
---


title: Undefined index message in drupal

text:
# Question
Title: Undefined index message in drupal
When editing a view, I get the following message in the popup.

> Notice: Undefined index: advertising\_block in `eva_plugin_display_entity->options_summary()` (line 41 of/.../sites/all/modules/eva/eva\_plugin\_display\_entity.inc).

This view contains 2 displays: a view attached and a block (called advertising\_block). This error message appeared both before and after deleting the "advertising\_block" to which it seems to refer.

Any idea of what may be causing this error message and how to fix it?

# Answer
Basically, the EVA module is getting called with a bundle 'advertising\_block' that it doesn't know how to handle. If you used to have a block named 'advertising\_block', that would be a suspect.

The way to solve this is to (with devel installed) use the approach in webchick's Quick and Dirty Debugging. Right before line 41 of/.../sites/all/modules/eva/eva\_plugin\_display\_entity.inc, make a temporary hack.

First, install and enable the devel module.

The code there is:

```
  foreach ($this->get_option('bundles') as $bundle) {
    $bundle_names[] = $entity_info['bundles'][$bundle]['label'];
  }

```

so we'll change it to

```
  foreach ($this->get_option('bundles') as $bundle) {
    if ($bundle == 'advertising_block') {
        dpm(debug_backtrace(), 'Bundle advertising_block being requested');
    }
    $bundle_names[] = $entity_info['bundles'][$bundle]['label'];
  }

```

Now when we hit that page, we'll see the backtrace (who called this thing, maybe why), and will have a path forward.

When you're through with this debugging code, don't forget to revert to the original code and disable devel module.

And remember that debugging like this should be done on a local dev site, not on production. Some more strategies are at randyfay.com/debugging
> 2 votes

# Answer
add this in your settings.php

```
ini_set('error_reporting', 'E_ALL ^ E_NOTICE');

```
> 0 votes

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


# Question
Title: How can I use a views template to modify the titles of taxonomy links?
I have a view that shows a field which is a taxonomy term reference set to display each term as a link. The taxonomy names are quite long so I want to rewrite them using a views template.

I made a template like this:

```
foreach ($row->field_field_ad_purpose as $data):
  if ($data['rendered']['#title'] == 'Apples, oranges, pears, and strawberries'):
    $data['rendered']['#title'] = 'Fruits';
  print $output;

```

Using dpm(), I was able to confirm that the `#title` is in fact shortened. However, printing `$output` prints out the original title. I also tried printing `$data`, but this just gives `Array`. What is the function to call to print out the term as a link?

# Answer
You need to create another field with the 'path' and set this to not display by default within the views UI.

You can then get the 'path' variable in your template along with the 'title' variable and create your link using Drupals l() function.

```
   print l($data['rendered']['#title'], $path);

```

http://api.drupal.org/api/drupal/includes%21common.inc/function/l/7
> 2 votes

---
Tags: views, theming
---


# Question
Title: Attach a script to a particular node ID or view
In Drupal 7, you can use the following code to attach a script to a particular content type:

```
function THEMENAME_preprocess_node(&$variables) {
  if ($variables['type'] == 'INSERT_CONTENT_TYPE') {

        // include javascript
        drupal_add_js(path_to_theme() . 'INSERT_SCRIPT');

      }

    }

```

What code do you need to use to attach a script to a particular Node ID or a specific View?

I have tried swapping `variables['type']` with various items, but none seem to work.

# Answer
> 14 votes
Node ID:

```
function THEMENAME_preprocess_node(&$variables) {
  if ($variables['nid'] == 'INSERT_NODE_ID') {
    // include javascript
    drupal_add_js(path_to_theme() . 'INSERT_SCRIPT');
  }
}

```

View:

```
function THEMENAME_preprocess_views_view(&$variables){
  if ($variables['name'] == 'INSERT_VIEW_MACHINE_NAME') {
    // include javascript
    drupal_add_js(path_to_theme() . 'INSERT_SCRIPT');
  }
}

```

# Answer
> 1 votes
If you are using D6. Try using JS injector to insert custom javascript to a page or view.

# Answer
> 0 votes
If I understand well your question, why not display your script accoring the alias of your view or your node or view? (also is possible using the node ID)

I have tested these functions with `_preprocess_node` (nodes) an also with `_preprocess_page` (for views and nodes) in Drupal `6` and `7`.

this is for node with ID with `_preprocess_node`:

```
function seven_preprocess_node(&$vars) {
    if(isset($_GET['q'])){
        $nodeID = '9';
          if(arg(1) == $nodeID){
              drupal_add_js(path_to_theme() . '/test.js');
          }
      }
}

```

this is for node with alias with `_preprocess_node`:

```
function THEMENAME_preprocess_node(&$variables) {
    if(isset($_GET['q'])){
          $path = drupal_get_path_alias($_GET['q']);
          if(preg_match('#test_page#', $path)){
              drupal_add_js(path_to_theme() . '/test.js');
          }
      }
}

```

and this function with `_preprocess_page` will be useful for nodes and/or views (alias):

```
function THEMENAME_preprocess_page(&$variables) {
    if(isset($_GET['q'])){
          $path = drupal_get_path_alias($_GET['q']);
          if(preg_match('#test_page#', $path)){
              drupal_add_js(path_to_theme() . '/test.js');
          }
      }
}

```

this last function is only to show an example of a function seeking alias of your view/node or node ID:

```
function THEMENAME_preprocess_page(&$variables) {
    if(isset($_GET['q'])){
        $script = '/test.js';//script name
        $currentPath = drupal_get_path_alias($_GET['q']);//current alias
        $targetPath = '#test_view#';//alias to match (delimiter is #), is for example of your view's page.
        $targetNodeID = '9';//node ID to match
          if(arg(1) == $targetNodeID || preg_match($targetPath, $currentPath)){
              drupal_add_js(path_to_theme() . $script);
          }
     }
}

```

I hope information be useful.

# Answer
> 0 votes
Try this:

```
function THEMENAME_preprocess_node($node) {
    if ($node->nid == INSERT_NODE_ID) {
        // include javascript
        drupal_add_js(path_to_theme() . 'INSERT_SCRIPT');
    }
}

```

# Answer
> 0 votes
nothing worked for me, so i checked with 'preprocess' hook, that works fine as follows:-

```
function MYMODULE-or-THEME_preprocess(){
    if(isset($_GET['q'])){
    $nodeID = '232'; //NODE ID TO CHECK
          if(arg(1) == $nodeID){
     drupal_add_js(drupal_get_path('module', 'MYMODULE').'/js/myscript.js');
         }
    }
}

```

---
Tags: theming
---


# Question
Title: Cannot add content to panels pages (stuck in overlay)
When I try to edit the content of panels pages, I click the add content link in the drop down menu an drag and drop down menu. The progress indicator appears and turns for a while and then nothing happens. The screen remains with the semi transparent overlay (screenshot below).

Also, drag and drop for reordering the content does not work.

Assuming it is related with an ajax call I checked the chrome console but there seems to be no error.

I am using: panels 7.x-3.3 ctools 7.x-1.3 jQuery v1.8.3 jQuery UI 1.8.7 jQuery UI Draggable 1.8.7 jQuery UI Droppable 1.8.7

I have been searching for hours now but could not find a related post anywhere.

Any ideas?

(a note: I do not have firebug or facebook modules installed. they are reported to cause a similar problem)

# Answer
So it turned out to be a jquery version problem.

In case somebody else needs it, here is how I managed to solve it.

* Installed the jQuery Update module
* went to the module's configuration page (admin/config/development/jquery\_update)
* selected jQuery Version 1.7

and all my troubles faded away :)
> 6 votes

---
Tags: 7, panels
---


# Question
Title: How can I get the order ID from Commerce (using Rules)?
I need to call a function upon successful completion of an order, and that function needs to know the OrderID that called it.

I have setup a rule

Event: "Completing the checkout process"

Conditions: None

Actions: \[custom function\]

I am aware of two possible ways pass the order\_id.

1. Using a data selector (though I'm not exactly sure what this should be), and passing it through a 'value' argument -or-
2. Calling the function commerce\_cart\_order\_id($uid) from within my function.

commerce\_cart\_order\_id($uid) did not seem to return anything.

```
global $user;
$uid = $user->uid;
$order_id = commerce_cart_order_id($uid);
drupal_set_message(t('OrderID:  ' . $order_id), 'status');

```

Has anyone got any suggestions on what I might be doing wrong? Many thanks.

# Answer
> 1 votes
As you have mentioned, you want to act on completion of the order, so there is a hook of drupal\_commerce, which get called on completion..

```
hook_commerce_checkout_complete($order)

```

I have used this hook for some action at the order completion in my custom module. If you call this hook in your custom module then $order variable will have all the information related to order. Check this in your custom module --

```
function MYMODULE_commerce_checkout_complete($order){
  dpm($order);
}

```

---
Tags: commerce, rules
---


title: node access restrict ( Drupal 6 )

text:
# Question
Title: node access restrict ( Drupal 6 )
We have around 150 nodes of type "X". We want to show only 20 nodes out of that for all the users ( including anonymous ) except users having role "Y". For users with role "Y" will be able to see all the 150 nodes. How can I achieve this?.

# Answer
> 0 votes
There are two module to control node access by user type. Node\_Access\_1 & Node\_Access\_2. Use which ever suits you. You will have to set the permission by editing each node, as I have implemented one from it in D7. I have never tried for VBO with it, so can't answer about multiple change..

---
Tags: users
---


# Question
Title: Exposed Filters in Entity Type Reference
I have used and entity reference field in my content type Showrooms. The field references to another content type Cars.

Cars has a category field attached to it such as audi, mercedes, bmw etc. Each car has once category only. Now what i want is that the user can filter the cars on category. I have used a reference field, but it lists all the cars. I want the user to be able to filter it.

Should work some thing like this, the user first chooses the category and then from the other drop down should choose a car and that car should be referenced.

# Answer
> 1 votes
you can put your car categories in a taxomomy list and then use Hierarchical Select to filter the way you asked. quite straightforward.

---
Tags: entities
---


# Question
Title: How to get jquery working on Drupal 7 - for Newbies
I have been reading many tutorials online on how to get jquery working on drupal 7. Although there are many lines of code and examples, what i cannot find is what piece of code to put where (maybe it is obvious for most of the developers)

So, what I do is

1)I create a new custom block

2)Over there from drupal UI, I write my code

```
(function ($) {

  $(document).ready(function(){

    // jquery here

  });
})(jQuery);

```

3)I display the block, but the jquery is not loaded.

I am reading that I should be putting this code in template files , theme files, css files, info files and I do not know whatelse!

It is not clear to me in which file exactly and in which path I have to put the above code to work properly ?

Any advice?

Many thanks!

# Answer
A couple of things here:

1. If you can avoid entering javascript and PHP into the site via the UI it will possibly save you troubles down the line. If you have no alternatives it is ok but here are some reasons why it is not a great idea: https://drupal.stackexchange.com/a/2512/10729 (note that that is aimed at PHP, not js but most of the points still stand for js). The examples module has an example of creating custom blocks.
2. For attaching js, if you want it on all pages you can add it to your theme's info file. If you only want it in some places though, best to use drupal\_add\_js() so it is only on pages it needs to be. For attaching js behaviour to forms you can also use #attached attribute on your form items.
3. If you use $(document).ready(), it will fire your javascript when the page loads, however if the page is updated via ajax then your javascript will not fire again, so new markup won't be affected by whatever your javascript is. To handle these cases you should use drupal behaviors instead of document ready.

For example:

```
(function ($) {
  Drupal.behaviors.yourBehaviorName = {
    attach: function (context, settings) {
      // Do your thing here.
    }
  };
})(jQuery);

```

I recommend reading these pages:
Managing JavaScript in Drupal 7
Working with JavaScript and jQuery
> 11 votes

# Answer
In your **.js** insert like this code;

```
(function ($) {

  Drupal.behaviors.themename = {

    attach: function (context, settings) {

     // All our js code here
     alert('Hello jQuery');
     // end our js code

   }

 };})(jQuery);

```

In your theme **template.php** create **hook\_preprocess\_html** then using **drupal\_add\_js**

```
function themename_preprocess_html(&$variables) {
  drupal_add_js(drupal_get_path('theme', 'themename') . '/js/your.js', array(
    'scope' => 'footer',
    'weight' => '15'
  ));
}

```

Just change **themename**
> 7 votes

# Answer
your .js file should look like this :

```
(function ($) {
    Drupal.behaviors.cdgi = {
        attach: function(context) {

        //your code

        }
    }
}(jQuery));

```

use drupal\_add\_js() in your module to add this file in Drupal. good references here and here.

clear cache often ;)
> 3 votes

---
Tags: theming, blocks, javascript
---


# Question
Title: Specify which theme to use when rendering a page with drupal_render_page()
I'm looking to send out a node as an HTML email. I have the code working except for one part.

I'm using drupal\_render\_page() to render the page's content so it's ready for an HTML email. I thought I'd use a custom theme for this (to take advantage of Drupal's theming layer).

However, I can't seem to figure out how I would specify a specific theme to use. Every time I run it it runs the current theme.

I'm not sure if this make a difference or not, but I'm using the Batch API to generate/send the emails.

I've tried changing the $theme and $theme\_key globals in the batch callback, however that didn't seem to change anything.

I've also tried something like this in hook\_custom\_theme():

```
if (arg(0) == 'batch' && $_REQUEST['op'] == 'do') {
  return 'email';
}

```

However, this also doesn't seem to change anything and still renders the email using the "seven" theme.

I've also tried using hook\_batch\_alter(), however changing the theme changes it for the batch process, (I still want the batch to process in the seven theme, I just want the email to be rendered in a different theme).

Thanks!

# Answer
I discovered that menu\_get\_custom\_theme() only uses a custom theme if the menu does NOT have a "theme callback". In the case of the batch process, it does have a theme callback: \_system\_batch\_theme().

To specify what theme to use when rendering a batch process, I had to use hook\_menu\_alter() to change the theme callback to my own.

```
function MYMODULE_menu_alter(&$items) {

  $items['batch']['theme callback'] = 'MYMODULE_batch_theme';

}

```

Then I just needed to add a conditional

```
function MYMODULE_batch_theme() {

  // Use a Custom Theme
  if ($_REQUEST['op'] == 'do') {
    return 'email';
  }
  else {
    return _system_batch_theme();
  }

}

```

This fixes the problem by specify the custom theme in the theme callback rather than in hook\_custom\_theme() (which is ignored when a theme callback is present).

Thanks!
> 2 votes

---
Tags: 7, batch-operations, theming
---


# Question
Title: How do I find out which module loads which javascript file?
I have been experiencing script related problems and would like to go through all the script files by disabling/enabling, to find out which is causing the problem.

So I'd like to be able to find out which module loads which javascript file. Then I can go by enabling disabling the modules.

How can I do that?

# Answer
> 2 votes
*"If you look at the source of the page you can see the path for each script. This will identify where the script is."*

**Example**

Typically the script located at...

```
sites/all/modules/contrib/panels/js/panels.js

```

...would more often than not only be used by the module of the same name

```
sites/all/modules/contrib/panels/panels.module

```

...or possible an include file

```
sites/all/modules/contrib/panels/includes/SOME_FILE.inc

```

Obviously bare in mind that Drupal uses the jQuery library so references to errors might fallback to these files just because its been implemented wrong by the developer in the module. Its more than likely never going to be something wrong with the libraries.

```
/misc/jquery.js
/misc/jquery.once.js

```

# Answer
> 0 votes
You can get the list of all JS file called for a page to built by a function drupal\_get\_js(). Though I have never used this or checked but this is what documentation says..

---
Tags: 7, javascript
---


# Question
Title: Using wget to get the latest module version
I was contemplating building a quick bash script to wget all of the modules I use on Drupal sites but every time the module version changes, the link changes.

Take for example the views module. At the time of writing it's at version 7.x-3.0-rc3 and therefore the link is as such `http://ftp.drupal.org/files/projects/views-7.x-3.0-rc3.tar.gz`

If I were to add this to my bash script it'd obviously stop working as soon as the next version is released.

Is there a URL which I can use with `wget` which will always give me the latest non dev version of a Drupal module.

`[...]drupal.org/projects/views-7.x-stable.tar.gz` for example

I don't want to use GIT or CVS etc as this will mean anyone using the script will need to install said program first. I would just like to be able to pass this script around to developers in my office to quickly download and deploy the latest Drupal version and modules we use constantly.

# Answer
The latest stable is published on an XML file, so your script would need to query and parse it to get the proper URL. http://updates.drupal.org/release-history/project-list/all this returns ALL the projects release history, obviously very large. You can get a specific project with this URL http://updates.drupal.org/release-history/views/7.x where "views" is the project name and "7.x" is the version.

Or you could just use DRUSH. It's super easy to install and will make your life 100x easier and better. Drush is a command line PHP script that allows you to simply type things like `drush dl views` or `drush up views`. It can do a lot more too, it's truly amazing. http://drupal.org/project/drush
> 12 votes

# Answer
Dave Hall has a blog post on this very subject, with excellent example code, at http://davehall.com.au/blog/dave/2010/02/22/check-drupal-module-status-using-bash
> -1 votes

---
Tags: 7, deployment
---


# Question
Title: Generating Views Block to list Taxonomy Terms of nodes curently visible in a Views Page
I have a Views Page which lists nodes of the content type, Article. This page also contains pagination since I configured it to display no more than 6 articles per page.

So for example, if I have 10 articles, 6 of them would be displayed on page 1 and the remaining 4 would be on page 2. In addition, Article has a term reference field called Tags.

I was wondering if it's possible to have a Views block I can attach to my **original View** I mentioned earlier (a list of Article content type) that lists Tags belonging only Articles currently visible on the **original View** on one of the paginated pages.

Going again with my example, I want this Views block to display Tags from the 6 Articles when I'm on page 1. Likewise, I want this block to display Tags from the remaining 4 Articles when I'm on page 2.

Here's a little graphic of what I'm trying to do. https://i.stack.imgur.com/KXmwU.png

Also, I'm not sure if this info is relevant but I plan to use the Context module to attach this Views Block to the Views page.

I was thinking along the lines of Contextual Filters but I'm not quite sure what arguments I would use.

Any help is appreciated.

# Answer
Offhand i'm not sure how Context will help you do this ... off the top of my head this solution came to mind.

* In your 1st view make the Tag field a hidden field the view so the View knows about it.
* Use `hook_views_pre_render` to loop through the results (and maybe respect page offset and # of items per page -- you can get that from the `$view` object) and grab your view field Tag values and store them into an array.
* Still in `hook_views_pre_render` you can set `$view->attachment_after = $some_string;` where `$some_string` is like the list of your Tags.

In code it will look something like this:

```
function MYMODULE_views_pre_render(&$view) {
  if ($view->current_display == 'VIEW_ID') {
    $tags_on_page = array();
    // $_GET['page'] has page number.
    // $views->items_per_page has items per page count.

    $page_offset = intval($_GET['page']);
    // this is somewhat wasteful, but easier than a loop at the moment.
    $paged_results = array_chunk($view->result, $view->items_per_page, TRUE);

    // Build up the Tag list for X page of the results.
    foreach ($paged_results[$page_offset] as $i => $result) {
      $tags_on_page[] = $result->value; // save the taxonomy term name to the tags list.
    }

    // Take our tags and build a block of HTML to embed after the view.
    // Alternatively, maybe take these tag values and pass them as parameters
    // to a new view we attach after programmatically -- thats more work.

    // if you know the url prefix you've given these taxonomy terms use it here, or use something like entity_uri().
    $num_tags = count($tags_on_page);
    if ($num_tags) {
      for ($i=0;$i<$num_tags; $i++) {
        $term = $tags_on_page[$i];
        $tags_on_page[$i] = l($term, '/URL/ALIAS/BASE/PATH/TO/TERM' . $term);
        // or, ... $term may have a path value already ... I cant remember :).
        // $term = taxonomy_get_term_by_name($tags_on_page[$i]);
        // $term_path = entity_uri('taxonomy_term', $term[0]);
        // $tags_on_page[$i] = l($term[0]->name, $term_path);
      }
      $links = implode('<br>', $tags_on_page);
      $view->attachment_after = '<div class="myBlockAfterView"><h3>Related Tags</h3>' . $links . '</div>';
    }

  }
}

```
> 0 votes

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


title: Calendar display with custom table

text:
# Question
Title: Calendar display with custom table
I am trying to show a calendar page with records stored in a custom table, using the Calendar module.

The table has been integrated with Views using `hook_views_data`. I also implemented `hook_date_views_extra_tables` and `hook_date_views_fields` to identity the relevant date fields to the Date module.

So far, I can create a new View with Calendar format (style plugin). When I add the Date: Date contextual filter (argument), I am able to see the field I specified in the `hook_date_views_fields`. So far so good.

Now when I save the view and show it, no calendar shows. When I get back to edit the view, the Date argument has been replaced with a "Broken/missing handler" notice.

Has anyone succeeded to show a calendar from a custom table?

N.B. This issue was created for the same purpose but it looks like the OP did not pursue it (or at least did not update it).

# Answer
> 1 votes
The reason for this problem was that the date argument handler was crashing. I had placed the implementations of the date hooks inside mymodule.views.inc, instead of mymodule.module. Duh!

---
Tags: 7, datetime, views
---


title: Pass taxonomy terms from node to block

text:
# Question
Title: Pass taxonomy terms from node to block
just wanted to scope peoples thoughts on the best way to do this: I have a node which surfaces taxonomy terms. I need to pass them to a custom block (templated with block.tpl.php).

The terms can be see within the node using devel, but i'm unclear as to how best pass them into the custom block.

any thoughts would be greatly appreciated

# Answer
> 1 votes
```
/**
 * Override or insert variables into the block templates.
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("block" in this case.)
 */

function MYTHEME_preprocess_block(&$variables) {

  if ($variables['block_id'] == 'target_block_id') {

    //load node object
    $node = menu_get_object();

    // do something with node object

    // add variable to your block template file
    $variables['block_variable'] = 'something';
  }
}

```

Available block variables - Block variables

---
Tags: taxonomy-terms, nodes, blocks
---


title: How do I get the ID value from a URL

text:
# Question
Title: How do I get the ID value from a URL
example.com:8080/browse?category=137 is my URL for a taxonomy category page.

How am I supposed to take the category ID (137) from that URI?

# Answer
> 7 votes
You can take that id from get array, try

```
print $_GET['category'];

```

# Answer
> 3 votes
If you are using Drupal 7 then you can make use of existing function drupal\_get\_query\_parameters

But also you can use

> `$_GET['category']`

Make sure you use check\_plain() to be sure of save URL values.

---
Tags: taxonomy-terms, uri
---


# Question
Title: Pricing changes based on line item fields in the add to cart form
I've been using commerce\_custom\_product to add custom line items options to products I'm selling in the shop. The shop is selling servers and if someone when adding a server to their cart wants a bigger hard drive for instance they select it in the "add to cart" form. I want to alter the price of the line item based on which option they select

e.g.

20gb HDD $40 40 gb HDD $70

The hard drives and other things are not really properties of the product I'm buying. They are options I'm selecting for the product. This is why I looked at commerce\_custom\_product.

Ultimately this question comes down to How can I set the product price based on choices made in the Add to Cart form. Is commerce\_custom\_product the way forward with something else bolted in? I'm very happy to code if there is a hook I could use to grab the price from the referenced entity if I was to add price to the entities that get selected in the add to cart form

# Answer
> 0 votes
I think you want to stick with Variations for this. Otherwise you can use Rules to calculate a price

---
Tags: 7, commerce
---


# Question
Title: How to get contextual filter of a view from page.tpl.php?
this is my page view path /news/\[years\]/\[month\]

I want to get year and month from path, how can do it ?

Thank you.

# Answer
> 2 votes
You can use the arg() function.

> Returns a component of the current Drupal path.
>
> When viewing a page at the path "admin/structure/types", for example, arg(0) returns "admin", arg(1) returns "structure", and arg(2) returns "types".

In your case:
arg(1) = \[year\]
arg(2) = \[month\]

---
Tags: theming, views
---


# Question
Title: Can we call a custom block inside our hook_block_view()?
I have a module of type block.Now based on the user i want to display different blocks . So i have a written the module but my dilemma is if its possible to call a block(default) inside our custom block? Here's my code m trying !

```
<?php
/**
 * Implements hook_block_info().
 */
function sample_module_block_info() {
  $blocks['current_posts'] = array(
    'info' => t('Current Users Of the Drupal Website'), //The name that will appear in the block list.
    'cache' => DRUPAL_CACHE_PER_ROLE, //Default
  );
  return $blocks;
}
function sample_module_block_view($delta = '')
 {

 $block = array();
global $user;
  switch ($delta) {
    case 'current_posts':
      $block['subject'] = t('Logged in User Currently');
$block['content']=$user->name;
      break;
/**
 switch ($delta) {
 case 'current_posts':
global $user;
print "The current user is: ";
print $user->name;
if($user->name == "admin")
print " This Shit Works ";
*/
    }
  return $block;
}
   ?>

```

Now in block\['content'\] i want to display another block! Can somebody lead me to how to do this ? If possible ?

# Answer
> 2 votes
Yes, you can load any block

```
....
$block['content']= sample_module_block_content();
....
function sample_module_block_content(){
  $block = block_load('module_name', 'block_name');
  return _block_get_renderable_array(_block_render_blocks(array($block)));
}

```

# Answer
> 0 votes
Sample Code and works perfectly :-(Code to call a default block inside a custom module )

```
<?php
/**
 * Implements hook_block_info().
 */
function sample_module_block_info() {
  $blocks['current_posts'] = array(
    'info' => t('Current Users Of the Drupal Website'), //The name that will appear in the block list.
    'cache' => DRUPAL_CACHE_PER_ROLE, //Default
  );
  return $blocks;
}
function sample_module_block_view($delta = '')
 {

 $block = array();
global $user;
  switch ($delta) {
    case 'current_posts':
      $block['subject'] = t('Logged in User Currently');
$block['content']=call_block();
      break;
/**
 switch ($delta) {
 case 'current_posts':
global $user;
print "The current user is: ";
print $user->name;
if($user->name == "admin")
print " This Shit Works ";
*/
    }
  return $block;
}
function call_block(){
  $block = block_load('system', 'powered-by');
  return _block_get_renderable_array(_block_render_blocks(array($block)));
}

```

This is the module file and after that u need an info file of the module .

---
Tags: hooks, blocks, commerce
---