# Question
Title: Would a cached page be considered, solely by definition, RESTful?
I'm thinking about how to explain the definition of a RESTful interface and am wondering if a cached page in Drupal would, purely by definition be considered RESTful: http://en.wikipedia.org/wiki/Representational\_state\_transfer#Constraints

Obviously if I wanted to setup a truly RESTful interface I would use Services or Fago's RestWS modules.

But by definition if the page is cached in D7 (thus there is no state information) is there a difference in definition between returning an xml or json endpoint and cached html page? Would the fact that there is javascript on the page create a state that would make it by definition not RESTful?

Again this is purely intellectual so thanks for any of your thoughts.

# Answer
> 5 votes
If a page is cached or not is in my opinion *completely* irrelevant. Page caching is transparent to the user and the content, he doesn't know if it is and once the cache expires, he *might* get something different on the same page. A page could for example be a view that randomly displays a node. Enabling page caching (and the node only switches e.g. every 5 minutes) doesn't change anything.

RESTful is about having a 1-1 mapping between an URL and a resource (or maybe better: a representation of that resource, e.g. a different format). IMHO, it doesn't matter if..

* authorization is necessary to have access to that resource (anon vs. authorized users)
* Only a part of that resource is visible (e.g. someone with additional permissions might see more information)
* If the displayed information changes, as long as it's the same resource on the same URL (e.g., a node could have an access counter that increases every time you view it.)
* If there is some sort of caching involved, either page or partial caching.

# Answer
> 0 votes
as i see it for point **Client–server and Stateless**

*a logged in user will be using a cookie and break these rules*

also **Manipulation of resources through these representations (point 2. of Uniform Interface)**

*again, as fe. only logged in users can manipulate nodes, this rule cannot be applyed*

so, in my opinion, only an anonymous cached page can be considered RESTful.

> except; there would be a URI allowing user-access, like /u234/gwd8932p/node/32(/edit)

each endpoint is is considered valid, so also X(HTML).

javascript is the **Code on demand** as long as all content is *visible* in the X(HTML), and not pulled via AJAX.

but - i may be wrong ;)

---
Tags: caching
---


# Question
Title: How to get exact value of a field from database?
I want to get value of a field, but I need the value that is saved in database, not the value that may be changed by `hook_node_load`. Is there a way to do this?

If there is no function for this purpose, which query should I use to get the field value?

# Answer
I'm not sure there's an API function to get this directly; the field functions (like `field_get_items()`) seem to rely on a loaded entity object, which in the case of a node would have gone through the whole loading process.

If you want to get the value directly you'll find the data in the `field_data_field_*` tables. A query like the following would get the data for a node of type 'article', assuming a text field called 'field\_my\_field' with a column name of 'value'. It also assumes the field is not multiple; if it is you'll need to remove the last line of the query and loop through `$val` instead:

```
$val = db_select('field_data_field_my_field', 'f')
  ->fields('f', array('field_my_field_value'))
  ->condition('entity_type', 'node')
  ->condition('bundle', 'article')
  ->condition('entity_id', $node->nid)
  ->execute()
  ->fetchField();

```

If you've got node revisions turned on for the content type in question you'll probably need to alter this to query the `field_revision_field_my_field` table instead, and use the node revision id (`vid`) instead.
> 3 votes

# Answer
There are quite a few more places that a field or entity could be changed, other than just `hook_node_load()`.

You might poke through the `field_attach_load()` function for some insight into which hook you want to support to catch fields before they're fully loaded.

Everywhere you see a `module_implements()` or any function call with `_invoke_` in it, that's the field system calling a hook. There are a bunch. :-)

If you drill down, like maybe through `_field_invoke_get_instances()` and then `field_read_instances()`, you end up seeing:

`hook_field_read_instance()`

Whether you want to implement this depends on why you need the info and what you plan to do with it.
> 2 votes

---
Tags: 7, nodes
---


# Question
Title: How to modify the existing field in a form?
I wanted to modify the existing fields in a form. I tried using hook\_form\_FORM\_ID\_alter but I could only add new fields; I could not alter the properties of existing field. I wanted to add ajax properties to some existing fields.

I wanted to alter the content add form which is created by Content Type. I wanted to add an Ajax property to the content creation form. I couldn't figure out a way to add this while creating the content type. Could anyone please help on how to do this? It's very urgent.

This is the DPM for the field.

```
field_mstyle (Array, 6 elements)

#type (String, 9 characters ) container
#attributes (Array, 1 element)
#weight (String, 2 characters ) -3
#tree (Boolean) TRUE
#language (String, 3 characters ) und
und (Array, 18 elements)
    #entity_type (String, 4 characters ) node
    #bundle (String, 12 characters ) pz_main_menu
    #field_name (String, 12 characters ) field_mstyle
    #language (String, 3 characters ) und
    #field_parents (Array, 0 elements)
    #columns (Array, 1 element)
    #title (String, 10 characters ) Menu Style
    #description (String, 0 characters )
    #required (Boolean) FALSE
    #delta (Integer) 0
    #type (String, 6 characters ) select
    #default_value (Array, 1 element)
    #multiple (Boolean) FALSE
    #options (Array, 4 elements)
    #value_key (String, 5 characters ) value
    #element_validate (Array, 1 element)
    #properties (Array, 4 elements)
    #after_build (Array, 1 element)

```

# Answer
You'll usually find the elements for fields buried in the form and you'd alter them like so:

```
$form['field_my_field']['und'][0]['value']['#ajax'] = array(
  // ajax settings
);

```

I strongly recommend installing the Devel module and using the `dpm()` function to perform debugging. You can use it to print any variable to the standard message area, and it allows you to inspect arrays and objects.

You could easily find out where abouts in the `$form` array the fields you're looking for are by including a line like this in your form alter function:

```
dpm($form);

```
> 5 votes

---
Tags: forms, ajax
---


# Question
Title: different drop down list for different nodes
I am using drupal 7.10.I have a content type bank details which is for entering bank details like bank name,address,contact details etc.,Now for each bank i need a drop down list which shows a list of agents of that particular bank.Note this is for each individual bank node.need help on this.Thanks.

# Answer
Views \+ Node Reference. Create new Views, that handle arguments of current node and filter agents by required bank.
> 1 votes

---
Tags: nodes
---


# Question
Title: How do I theme my module output (specifically the nodes coming out of EntityFieldQuery)?
I'm using EntityFieldQuery to get node IDs that match certain criteria in my module. At the end, I am doing: `return node_view_multiple($nodes, 'full');` in the *page callback* function (which itself is called from hook\_menu).

If I use `node--content-type.tpl.php`, I override the display everywhere. Ideally, I would like an array containing Node information that is sent to the tpl file, (**like a controller returning display array to a view in CodeIgniter**), which I can loop through and create a custom display.

How do I go about this?

# Answer
> 1 votes
Instead of doing a full node view you can make a custom node view like

```
return node_view_multiple($nodes, 'module_name');

```

That will enable you to create custom logic for this view type and setup field display as well if needed.

To define your own view mode you need to add it using `hook_entity_info_alter`

```
/**
 * Implements hook_entity_info_alter().
 */
function hook_entity_info_alter(&$entity_info) {
  $entity_info['node']['view modes']['module'] = array(
    'label' => t('Name'),
    'custom settings' => TRUE,
  );
}

```

---
Tags: 7, theming, entities
---


title: apachesolr filters do not work

text:
# Question
Title: apachesolr filters do not work
I have installed apachesolr module and built the index for it. now i can search normally but when i filter the result using any enabled filter, the result DOES'T change and i get the same result of searching for the key. for example i searched for `business` and then filtered the result using taxonomy `tid:36` and i got the same result before filtering!!
I have var\_dump the $query that has been generated at line 215 in apachesolr\_search.module and part of the result is shown below

```
object(Solr_Base_Query)#17 (13) {
  ["id"]=>
  int(1)
  ["fields":protected]=>
  array(0) {
  }
  ["fields_added":protected]=>
  array(0) {
  }
  ["fields_removed":protected]=>
  array(0) {
  }
  **["filterstring":protected]=>
  string(6) "tid:36"**
  ["field_map":protected]=>
  array(0) {
  }
  ["subqueries":protected]=>
  array(0) {
  }
  **["keys":protected]=>
  string(8) "business"**
  ["base_path":protected]=>
  string(24) "search/apachesolr_search"
  ["solr":protected]=>
  object(Drupal_Apache_Solr_Service)#16 (20) {....

```

also the filter doesn't appear in **CURRENT SEARCH** block. the block still showing

```
**CURRENT SEARCH**
Search found 38 items

* (-) business

```

Also I have made a `var_dump` for params array that has been generated in `function apachesolr_search_execute` in apachesolr\_search.module at line 212 and the result was:

```
array(13) {
  ["fl"]=>
  string(71) "id,nid,title,comment_count,type,created,changed,score,path,url,uid,name"
  ["rows"]=>
  int(10)
  ["facet"]=>
  string(4) "true"
  ["facet.mincount"]=>
  int(1)
  ["facet.sort"]=>
  string(4) "true"
  ["hl"]=>
  NULL
  ["hl.fragsize"]=>
  NULL
  ["hl.simple.pre"]=>
  NULL
  ["hl.simple.post"]=>
  NULL
  ["hl.snippets"]=>
  NULL
  ["hl.fl"]=>
  NULL
  ["spellcheck.q"]=>
  string(8) "business"
  ["spellcheck"]=>
  string(4) "true"
}

```

nothing for `fq=tid:36`
any idea of what i might be missing? or how to fix it?
Thanks for your help

# Answer
You should consider using Search API module, which can handle Solr and facets, and enables you to use Views to create the search page and has a very good UI for creating search index with facets ect.

I've used it several times and have been pleased with the result.
> 1 votes

---
Tags: 6, search
---


# Question
Title: Using Panels - Node Template.. How do i pass additional arguments for my blocks?
I have content types: Project, News, and Country.

I have a node template that displays details of a **Project**. This node template displays a view, which displays all the **News**. I want to filter all the news by the project's **Country**.

**Project** has a cck field: country\_id. How do i pass it's value to my News view?

---

tl;dr: using a panel node-template, how do i use the node's cck field as argument?

# Answer
You need to use content pane for the view to make it accept arguments.

Then when you insert the content pane, you should be able to use the node and all fields on the node using a token system to pass any variable to the view pane. How you setup the content pane determines which types of variables it will accept.
> 3 votes

---
Tags: panels, views
---


# Question
Title: Custom form that will change the hyperlink inside the email for a chosen radiobutton
I would like to alter the content of an email sent to the user after someone choice form radio button list. The altered content of the email would be a hyperlink to a particular version of a software. How do I do it within the submit button with Drupal 7 ? Thanks

# Answer
To send an email with Drupal, you should first use `hook_mail` to define the email and then `drupal_mail` to send it with any variables. There is extensive docs on this on the Drupal API site.
> 0 votes

---
Tags: entities
---


title: Error when deleting some node

text:
# Question
Title: Error when deleting some node
After pressing the delete button the following message appeared:

> The website encountered an unexpected error. Please try again later.

How can I solve this problem?

when deleting field The system log says:

> PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table '\[name\].field\_deleted\_data\_5' doesn't exist: SELECT field\_deleted\_data\_50.entity\_type AS entity\_type, field\_deleted\_data\_50.entity\_id AS entity\_id, field\_deleted\_data\_50.revision\_id AS revision\_id, field\_deleted\_data\_50.bundle AS bundle FROM {field\_deleted\_data\_5} field\_deleted\_data\_50 WHERE (field\_deleted\_data\_50.deleted = :db\_condition\_placeholder\_0) AND (field\_deleted\_data\_50.bundle = :db\_condition\_placeholder\_1) LIMIT 10 OFFSET 0; Array ( \[:db\_condition\_placeholder\_0\] =\> 1 \[:db\_condition\_placeholder\_1\] =\> patient\_info ) in field\_sql\_storage\_field\_storage\_query() (line 577 of C:\xampp\htdocs\[name\]\modules\field\modules\field\_sql\_storage\field\_sql\_storage.module

# Answer
> 5 votes
It sounds like your problem is that you have delete a field on your node, which makes Drupal rename the table storing the field data to `field_deleted_data_ID`. The error you are getting is that one of such tables is missing, and the delete fails since the query to delete the data creates a SQL error.

I know of two ways to solve this.

* Recreate the table deleted.
* Delete the field info from `field_config` and possibly `field_config_instance`.

---
Tags: 7
---


title: Change the output of the search results

text:
# Question
Title: Change the output of the search results
I'd like to change the output of the search result page.

For example, I've got 3 different content types: foo, bar, etc. I'd like to group my search results by these content types, so that for every content type the first three or so results are shown followed by a link: "View more results for content-type foo" which will lead you to a page where all results of this specific content type are shown.

I've done some researching and couldn't find a module which does something like this. I guess i have to write my own module, but I don't know where to begin. Do you have any tips for me (whick hooks to implement, etc...)

# Answer
If you only have 3 types and you don't plan on changing often, the easiest way to do that might be to create views of those three content types and use views\_embed\_view.

You could potentially override the search results in your theme using search-results.tpl.php. A more complex, and possibly better way would be to write a custom module that implements hook\_menu\_alter and redirects the default search callback to a custom view in your module.

I have done something like that before and it's not a trivial undertaking (take a look at the apachesolr\_search module if you want a complete example).

Something like (untested)...

```
function mymodule_menu_alter(&$menu) {
  if (isset($menu['search/mymodulesearch/%menu_tail'])) {
    // redirect default search to this module's view
    $menu['search']['page callback'] = 'mymodule_search_view';
    // create a menu linkspecifically for this view
    $menu['search/mymodulesearch/%menu_tail']['page callback'] = 'mymodule_search_view';
    $menu['search/mymodulesearch/%menu_tail']['weight'] = -20;
  }
}

function mymodule_search_view() {
  $keys = search_get_keys();

  // do something with views_embed_view here
}

```
> 1 votes

# Answer
i think that correct code will be:

```
function custom_preprocess_search_results(&$variables) {
global $base_path;
drupal_add_library('system', 'ui.tabs');
drupal_add_js('jQuery(document).ready(function(){jQuery("#tabs").tabs();});', 'inline');
$variables['search_results'] = '';
// get a list of node types
$nodeTypes = node_type_get_types();
// loop through results, group by type
$resultTypes = array();
foreach ($variables['results'] as $result) {
    $resultTypes[$result['node']->type][] = $result;
}

// create fieldsets for each type
    $output = '<div id="tabs">';
$i = 0;
$output .= '<ul>';

foreach ($resultTypes as $resultType => $resultTypeResults) {
    $i++;
    $value = "";
    // loop through entries
    foreach ($resultTypeResults as $result) {
        $value .= theme('search_result', array('result' => $result, 'module' => $variables['module']));
    }
    $output .=  '<li><a href="#tabs-'.$i.'">';
    $output .=  $nodeTypes[$resultType]->name.'</a></li>';

}
$output .= '</ul>';

$i = 0;
foreach ($resultTypes as $resultType => $resultTypeResults) {
    $i++;
    $value = "";
    // loop through entries
    foreach ($resultTypeResults as $result) {
        $value .= theme('search_result', array('result' => $result, 'module' => $variables['module']));
    }

    $output .=  '<div id="tabs-'.$i.'">';
    $output .=  $value;
    $output .=  '</div>';

}
    $output .= '</div>';

     $variables['search_results'] = $output;

```

}
> 1 votes

---
Tags: 6, search
---


title: Preview info on mouse over on an image

text:
# Question
Title: Preview info on mouse over on an image
How can I get the effect like on StackExchange where user information is displayed when you hover over their avatar?

I have a site that only has images on the front page, and would like the user to be able to get some information about the image before they click through.

I am using Drupal 7.

# Answer
Also you can use qTip

> qTips are stylish tooltips that can be configured and styled (more to come in later releases) to fit nearly any website's design.
> 1 votes

# Answer
Sounds like something the Popup suite should be able to help you with.

> The popup suite allows builders to popup tooltip-like text, nodes, blocks, menus, forms, views and php-generated content.

I can't help much more I'm afraid as I've not used it, however I'd imagine you should just be able to create a block View containing user information and then expose this block as a popup when you hover/click on the username or user picture.
> 0 votes

---
Tags: 7, tooltips
---


# Question
Title: Can't seem to get my plugin class include to load?
If I keep my plugin class in the mymodule.module, then the plugin works fine. However moving it out to mymodule.context.condition.inc prevents the condition from working.

I have added file\[\] entry to mymodule.info and I have added the following to my hook\_context\_plugins:

```
function mymodule_context_plugins() {
  $plugins = array();
  $plugins['mymodule_context_condition_bonus_discount'] = array(
    'handler' => array(
      'class' => 'mymodule_context_condition_bonus_discount',
      'parent' => 'context_condition',
      'path' => drupal_get_path('module', 'mymodule'),
      'file' => 'mymodule.context.condition.inc',
    ),
  );
  return $plugins;
}

```

As mentioned, if I shift the code into the .module file, and remove the 'path' and 'file' lines from hook\_context\_plugins, then the condition is recognized by context and runs without issue.

SOLVED:

Looks like my class definition should not have had a capital "C" in "Class". Quite frustrating since I'm using drupalcs which complains about the lower case "class".

# Answer
Looks like my class definition should not have had a capital "C" in "Class". Quite frustrating since I'm using drupalcs which complains about the lower case "class".
> 1 votes

---
Tags: 7
---


# Question
Title: hook function not deleting nodes when calling node_delete
I have a cron job where I need to do a `node_delete()`.

From what I can tell the delete occurs okay if I run the cron job manually from the status report page, but if I try to run the cron from inside a call to a `module_cron` function it looks like the delete fails.

Is there some way to give the cron the access to delete nodes with `node_delete`?

# Answer
> 2 votes
A scheduled cron runs as uid 0, the anonymous user, and therefore probably can't delete anything. When you run cron from the admin menu, it uses your current session, so you can delete things.

If you google for "drupal run cron as uid 1" you will see some workarounds. Most involve switching users inside your `hook_cron` and then restoring the session when you are done.

What should be possible is to invoke `drush -u XXX cron` from your crontab instead of the the typical `wget` method. Some searching will dig up the proper way to call it (you need to get the environment and Drupal basedir set right). I would not run as uid 1, though. Pick (or create) a user with sufficient permissions to do what you need.

What would also be possible is to create a script that bootstraps, loads the proper user, and then does your task. Lock this down in your `.htaccess` and call it from your crontab.

# Answer
> 0 votes
For deletion of a node by using hook\_delete, it is necessary that the author(user) of that node is present in the db. To achieve consistency, one should delete nodes first and then its user. If you donot want to delete node but only want to delete a user you should use hook\_user and in delete case, set uid of the node to 1, as uid = 1 is for super admin. So we will not face orphaned nodes in the database. Hope so, it will help you.

---
Tags: nodes, cron
---


# Question
Title: How to iterate through Drupal.settings in a js file when there are lots of variables?
Am trying to create a health service locator using Google maps API on my Drupal 7 site. (FYI, I cant use location module or open layers, because, Create a hospital locator in drupal 7 )

OK, so now I have a form, which takes the users location, type of service (eg, hospital, pharmacy etc) and the proximity around which they wish to find the result, using Google Maps API and Google Places API I fetch the results (details about those near by places such as hospital) in JSON format from Google. The fetched data includes each place's name, address, rating, phone number, latitude, longitude etc. now I store those values in `form_state['storage']` and then sends it to the JS file using the `drupal_add_js()` method.

The below code is sending the values,

```
<?php
for($i=0;$i<$length;$i++)
 {
  drupal_add_js(array('a'.$i =>array(
             'lat'=> $form_state['storage']['results'][$i]['geometry']['location']['lat'],
             'long'=> $form_state['storage']['results'][$i]['geometry']['location']['long'],
         'name'=>  $form_state['storage']['results'][$i]['name'],
         'rating'=>$form_state['storage']['results'][$i]['rating'],
         'vicinity'=>$form_state['storage']['results'][$i]['vicinity'],
         'formatted_address'=>$form_state['storage']['results'][$i]['formatted_address'],
         'international_phone_number'=>$form_state['storage']['results'][$i]['international_phone_number'],
         'website'=>$form_state['storage']['results'][$i]['website'],
)),'setting');

}
?>.

```

the details of first place is in a0, second place detail is in a1 etc.

FYI, each place details are in `Drupal.settings.a0`, `Drupal.settings.a1` etc. I mean, I can access those variables in js file using,

`Drupal.settings.a0.name` and `Drupal.settings.a0.website` similarly for second place, `Drupal.settings.a1.name` etc.

Now my problem is I need to iterate through these different places.

I can iterate through different variables of one particular place usin the below for loop,

```
for(var x in Drupal.settings.a0)
{
 alert(Drupal.settings.a0.x);
}

```

But, I cant iterate through different places, like a0, a1 etc. I mean I cant attach a variable to drupal.settings..!

I tried tried putting all places in an array, i.e, a0,a1,a2 are in an array named `arr[]` (I have the total no. of places in `Drupal.settings.my_vars.length`) then, I iterate through this array and tried attaching arr\[i\] to `Drupal.settings` as `Drupal.settings.arr[i].x` but it doesn't work.

How can I do it...?? Is there any better way of achieving it...??

Thanks in advance.

# Answer
> 1 votes
I got the answer...! The below code works..!

```
var i = 0, j=0;
while(Drupal.settings["a" + i])
{
  for(j in Drupal.settings["a" + i])
  {
    if(Drupal.settings["a" + i].hasOwnProperty(j))
    {
      alert(Drupal.settings["a" + i][j]);
    }
  }
  i++;
}

```

But **I would like know what exactly is hasOwnProperty(j)**...?? (I got this answer in drupal forum)

# Answer
> 2 votes
You can add your module name to settings like this

```
$locations = array();
for($i=0; $i < $length; $i++) {
  $locations[] = array('a'.$i =>array(
    'lat'=> $form_state['storage']['results'][$i]['geometry']['location']['lat'],
    'long'=> $form_state['storage']['results'][$i]['geometry']['location']['long'],
  );
}

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

```

and loop is js like

```
for (var x in Drupal.settings.mymodule) {
  // ...
}

```

---
Tags: 7, javascript
---


# Question
Title: Some of my pictures and fonts are not loading after uploading to host
I've just uploaded my website to my host. There was a 500 Internal Server Error at first, I looked into my htaccess file and after a lot of struggling with it I commented this line: `Options +FollowSymLinks` and then it worked but still some of my pictures and fonts are not loading, also I have some errors in my pages like:

```
Warning: ini_set() has been disabled for security reasons in drupal_environment_initialize() (line 702 of /home/simamedi/public_html/includes/bootstrap.inc

```

and

```
Warning: ini_set() has been disabled for security reasons in include_once() (line 290 of /home/simamedi/public_html/sites/default/settings.php

```

Sorry, I'm quite new with these things, there's a live version of my website at www.simamedia.com.

# Answer
Seems like `ini_set` is disabled by your hosting provider. There is a thread on drupal.org that may help.

Seems like your best option is to contact your hosting provider directly and see if there's anything they can do for you.

This might help as well.

> I had the exact same problem, and by reading the posts here and Googling around I found out that this error is caused by ini\_set being disabled by the hosting provider.
>
> Unless you have root access, you cannot edit the php.ini file directly, but at least on my hosting the support gave me these instructions to circumvent the problem:
>
> Create a "php.ini" file in your `public_html` directory and put one line of code exactly:
>
> `disabled_functions =`
> 2 votes

---
Tags: 7
---


title: Drupal 6 hook for field access

text:
# Question
Title: Drupal 6 hook for field access
I want to use my own code to determine if a user has edit access on certain fields. `hook_field_access` for Drupal 7 looks right. Is there a comparable hook for Drupal 6?

# Answer
A hook with exactly the same name exists for CCK in Drupal 6, it just doesn't seem to be all that well documented.

It's invoked from the `content_access()` function and has the following signature:

```
function MYMODULE_field_access($op, $field, $account = NULL, $node = NULL) {

}

```
> 2 votes

---
Tags: 6, hooks, entities
---


title: Duplicate node on content creation

text:
# Question
Title: Duplicate node on content creation
Each time any node is being created, Drupal creates two copies of the same node, both in the default language.

What can be the reason of this duplication?

# Answer
This is not the normal Drupal behavior. In this case, what you need to do is start disabling modules one at a time.

Disable a module that you think might be causing the problem (just take a guess) and then create a piece of content to see if two pieces of content are created. If you disable a module and then create content and you only get one piece of content, you know you have found the problem module.

Once you find the problem module, try to locate the source of the problem in the module configuration. If you can't find it yourself, try asking again on this site.

Without knowing what module is causing the problem, it is very hard to answer your question, as there are too many potential modules that can cause problems.
> 1 votes

# Answer
The problem was in Ubercart SKU token in the Pathauto patterns; it appears to be an array.
> 0 votes

---
Tags: 7, nodes
---


title: Cannot log in in to my site

text:
# Question
Title: Cannot log in in to my site
I am having some problems when I try to log in to my drupal site. When I visit http://mysite/user, i am getting redirect to the login page and in my url appears something like this:

user?name=user&pass=111111&form\_build\_id=form-iCrzIe6KBq1g5MoA3z0JeBI98QU8q2f-FvfcIcp3Cvk&form\_id=user\_login&op=Log+in

I'm trying to find the problem, but I don't know what to do.

When i restore the site(from my last backup) i can do the login, but when i restart my machine, the problem comes back.

I hope you could give me a hand with this problem.

Regards

# Answer
I would check /sites/default/settings.php and look into your `$cookie_domain =` setting - does it match your domain?
> 2 votes

---
Tags: redirection, users
---


# Question
Title: How to keep Views 2 RSS feed output from stripping out video, embeds, etc.?
I've got a basic blog built on Views 2 on a D6 site, with a couple displays built using the views style plugin 'RSS Feed'. Our content team frequently posts various embeds using iframes or flash objects which work fine, except when viewed through an RSS reader where these items (and other basic HTML tags like or ) are stripped out.

I've already tried creating a separate template for my view from the default template:

```
  <item>
    <title><?php print $title; ?></title>
    <link><?php print $link; ?></link>
    <description><?php print $description; ?></description>
    <?php print $item_elements; ?>
  </item>

```

but I'm not able to modify the $description variable or catch it before the input format filter is applied. What is the best way to do this?

# Answer
Figured this out -- client request was to not eliminate any of the html markup (embeds, videos, emphasis tags, etc.) even though some of the RSS readers would continue to strip it out on their own. I worked through this by creating a views-view-row-rss.tpl.php for my specific view and then adding the following code in:

```
<?
 $index = $variables["view"]->row_index;
 $nid = $variables["view"]->result[$index]->nid;
 $node = node_load($nid);

 $teaser = check_markup($node->teaser);

 $description = "<![CDATA[".$teaser."]]>";

?>
  <item>
    <title><?php print $title; ?></title>
    <link><?php print $link; ?></link>
    <description><?php print $description; ?></description>
    <?php print $item_elements; ?>
  </item>

```

Hope this is helpful to someone else, welcome any suggestions on improving this.
> 1 votes

---
Tags: views, 6
---


# Question
Title: Can I update directly from 7.7 to 7.12?  Or do I have to do 7.7 to 7.8, 7.8 to 7.9, etc?
I just updated my Drupal website from 7.7 to 7.12, but there were a lot of issues when running update.php.
I was wondering if it is possible to update Drupal 7.7 directly to 7.12, or you have to get 7.8, 7.9, 7.10 and 7.11 before you can update to 7.12.

# Answer
> 4 votes
You should be able to go right from 7.7 to 7.12. The messages from update.php depend on changes to the database schema from version to version made by drupal and other modules, and they are normal.

You may be interested in drush. It allows you to run updates with the pm-update command and automatically runs update.php for you. It also saves backups in your home directory. There is a website, http://drushmake.me/, that allows you to build out sites with `drush make` if you are using drush version 5.

# Answer
> 1 votes
When updating from a major version (e.g. Drupal 6) to the latest release one the same major version, you can update directly to the latest available release.

When updating from a major Drupal version (e.g. Drupal 6) to another major version (e.g. Drupal 7), it is better to first update to the latest release of the already installed Drupal version, and then update to the latest release of the other major version.

---
Tags: updating
---


# Question
Title: Views: displaying related (referenced) content in a block
I tried solving the following with "node\_reference" and "entityreference" modules but failed.

I have the content types **recipe** and **cook**. A recipe has a mandatory field which points to a cook.

When Drupal renders a recipe I want to have a block on the sidebar (implemented via "views") which will be displaying info on the recipe's cook.

How can the block know which recipe is being rendered on screen in order to use the relationship and pull the cook's data as fields which I'll use for display within the block?

thanks

**More info**: The problem is that in the block I'm getting all referenced (from recipes) cooks and not just the one cook for the specific recipe. So for the following data:

```
recipe#1 -> cook#1
recipe#2 -> cook#1
recipe#3 -> cook#1
recipe#4 -> cook#2

```

When I visit **any of the recipes** the block displays data from:

```
cook#1
cook#1
cook#1
cook#2

```

# Answer
> 1 votes
1. Create a Block views display.
2. Add "Filter Criteria" of `Content: Type` and select (tick) your "Recipe" content type.
3. Add "Relationship" (may need to expand "Advanced" fieldset on your Views edit screen), and for your **Cook reference field** that exists in your "Recipe" node type. Afterwards, any fields such as `Content: Title` should have a Relationship dropdown on their settings screen. Make them use this new Relationship you just added. (I beleive you got up to this part judging from other answers' comments. Here's the key part:)
4. Add "Contextual Filter" and select `Content: Nid` field, and on the field settings set "WHEN THE FILTER VALUE IS NOT AVAILABLE" to "Provide default value" and set the "Type" to "Content ID from URL".

Now when you visit a Recipe page that has this block somewhere, or if you put a Recipe content's Nid into the Views preview arguments box you should get the Cooks for that Recipe.

# Answer
> 1 votes
You would need to add a relationship from the reference field in views (under advanced \> relationships). This will extend the scope of fields available to the view include those of the referenced node (Cook).

However this will as you state show all cooks as it will come from all recipes. In order for the block to know how to filter out all irrelevant cooks (ones not referenced) you will need a contextual filter which knows what recipe you are currently on.

On this contextual filter you can specify the relationship to the one you have already created, then you will need to let the block view know which recipe you are on. You do this with the setting "provide default value" and "Content ID from URL". This will tell the view which content you are on and hopefully apply the filter. Sorry I do not have access to D7 right now for a better explanation

---
Tags: 7, views
---


# Question
Title: Way to show changes to a particular node to users
I'm currently looking for a way to show changes that occured on a node and its related nodes.

Currently we are using the diff module and it works great except that it is a bit too advanced on what we show them (ex: html changes).

It there some way or modules to show revisions of a node and it's related nodes in a much simpler way?

# Answer
You could try Revisioning (integrates with Diff) for both Drupal 7, and Drupal 6.

> Revisioning is a module for the configuration of workflows to create, moderate and publish content revisions. You use it in scenario's like this:
>
> * Authors write content that prior to being made publicly visible must be reviewed (and possibly edited) by moderators. Once the moderators have published the content, authors should be prevented from modifying it while “live”, but they should be able to submit new revisions to their moderators.
> * We shouldn't have to grant these roles “god-like” powers (e.g. Drupal 6's "administer nodes" permission) to implement this.
> 1 votes

---
Tags: 7
---


title: Empty lines in index.php file

text:
# Question
Title: Empty lines in index.php file
I had my Drupal 6 running for 2 yrs now. Suddenly it started to give parse errors on index.php page. I opened the file and saw that there were 100-200 empty lines after php closing tags. There is no chance that some one can have changed the file as access is with me only. What may be cause for this? Does any changes in server like upgrade of php version may cause this. I haven't changed the index.php file and it was running perfectly fine till date. The website is hosted on some other server.

# Answer
> 2 votes
If your index.php file is different from the default one, then it has been changed from somebody. Updates to modules don't alter the content of that file. If there is a module that tries to alter the content of index.php, that is not the correct behavior for that module.

I would check that the permissions of the system user used to run the server, and PHP, don't allow it to alter any file contained in the Drupal root directory, and in its sub-directories.

In Drupal 6, the content of index.php is the following one. It is 39-line long, it includes an empty line after `drupal_page_footer();`, and it doesn't have any closing tag (`?>`).

```
<?php

/**
 * @file
 * The PHP page that serves all page requests on a Drupal installation.
 *
 * The routines here dispatch control to the appropriate handler, which then
 * prints the appropriate page.
 *
 * All Drupal code is released under the GNU General Public License.
 * See COPYRIGHT.txt and LICENSE.txt.
 */

require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$return = menu_execute_active_handler();

// Menu status constants are integers; page content is a string.
if (is_int($return)) {
  switch ($return) {
    case MENU_NOT_FOUND:
      drupal_not_found();
      break;
    case MENU_ACCESS_DENIED:
      drupal_access_denied();
      break;
    case MENU_SITE_OFFLINE:
      drupal_site_offline();
      break;
  }
}
elseif (isset($return)) {
  // Print any value (including an empty string) except NULL or undefined:
  print theme('page', $return);
}

drupal_page_footer();

```

# Answer
> 1 votes
I would imagine the server has either had an upgrade for its running PHP config, or some files have been modified/potentially hacked.

Have you been keeping core updated?

---
Tags: 6
---


# Question
Title: Can I only traverse a DatabaseConnection object once?
I have a database query result, and I want to go through the records twice. However, the second time I go through it, nothing happens. It seems you can only iterate through this object once?

My code looks like this:

```
$query = db_select( ... );
$result = $query->execute();
if ( $result->rowCount() > 0 ) {
  foreach ( $result as $record ) {
    ... processing happens here
  }
}

// now loop through again, to mark records as processed, upon success.
foreach ( $result as $record ) {
  ... additional processing here
}

```

And the additional processing doesn't happen.

As a work around, I added `$records = $result->fetchAllKeyed();` before the initial processing, and then the result object had no records!

I found nothing in the documentation about resetting the object or anything.

Is this how the object works? Can I reset the iterator again, or must I fetch the keys initially to have an array that I can iterate over many times?

# Answer
This is expected behaviour; Drupal wraps around PDO and this is how PDO query functions behave also. Have a look at Is it possible to rewind a PDO result for a more in-depth discussion.

The standard way to get around this would be to use either `fetchAllKeyed()` as you've mentioned, or `fetchAll()` instead. The latter will produce an array of object results that can be iterated over as many times as you want.

```
$query = db_select( ... );
$result = $query->execute();
if ( $result->rowCount() > 0 ) {
  $data = $result->fetchAll();

  foreach ($data as $item) {
    // do something with data
  }

  foreach ($data as $item) {
    // do something with data again
  }
}

```
> 4 votes

---
Tags: 7, database
---


# Question
Title: How can I access this site as the administrator?
I have a dev site that I cannot access that contains content ad structure I want to extract. To gain access I created a new dev website and copied over the contributed modules and theme I am using. I then imported the database containing the data. When I go to the custom home page there is no login (I had not yet added it to the panel containing the home page display). To access the site, I must do one of two things:

1. Access the site using Drush. I tried using Drush user-login which returns a link `"http://default/user/reset/1/..."` It is not clear how to use the link. Using it directly as-is leads to an unknown website search. Using it as `example.com/default/user/reset/1/...` leads to a page not found error. Having never done this before, I am not sure what to expect.
2. If I could change the theme to a standard one such as Bartik through the database or other means I would then have access to a login block. Where is the current theme stored?

Any other suggestions gratefully accepted:)

# Answer
I think `default` is substituted for the site name in your drush result, try http://example.com/user/reset/1 which would be the standard password reset page for a user with a `uid` of 1 (the admin user).

If that doesn't work the default theme is set by the `theme_default` variable...you can edit the `variable` table in the database manually and set the value column for that variable to whatever theme you want.
> 1 votes

# Answer
my favorite set of commands :

```
drush sqlq "select name from users where uid=1;"

```

returns a name of the admin user (i tend to set different names for reasons of security and then forget them :)

```
drush upwd admin --password=NewSafePassword

```
> 1 votes

---
Tags: users, drush
---


# Question
Title: preventing a date form element from displaying 'day', 'month', and 'year' labels?
I have a D7 form with a date element on it. I want it not to display 'day', 'month', and 'year' elements. I looked at `'#display_title' => FALSE` but that doesn't work.

Can I disable the display in the form definition, or must I do this elsewhere?

# Answer
> 1 votes
I think the property you're looking for is `#title_display`, not `#display_title`. Also you wouldn't set it to `FALSE` but one of these:

* before
* after
* invisible
* attribute

In your case you'd want to set it to `invisible`:

```
$form['element']['#title_display'] = 'invisible';

```

That will render the label, so your form remains accessible, but hide it from display.

---
Tags: 7, forms
---


# Question
Title: Why is my form themed as table not posting data correctly, or displaying correctly?
I have created a form in the admin.

```
$form['things'] = array(
  '#prefix' => '<div id="things">',
  '#suffix' => '</div>',
  '#tree' => TRUE,
  '#theme' => 'table',
  '#header' => array(t('Field Label'), t('Field Name'), t('Location'), t('Stuff')),
  '#rows' => array(),
);

```

I then add each row to it like:

```
foreach ($type_fields as $field_name => $attrs) {
  $stuff = array(
    '#type' => 'textfield',
    '#default_value' => $attrs['stuff'],
  );

$form['things']['#rows'][] = array(
  array('data' => 'label'),
  array('data' => $field_name),
  array('data' => $field_name),
  array('data' => $stuff),
);

```

}

The form looks great! But the first problem is the value assigned to `#default_value` is not showing up in the form. When I change it to `#value` the correct value DOES show up. So I wonder how this should be done? The Drupal documentation says `#value` should not be used with forms although it is functioning exactly how I would expect it to function.

The main problem is when I fill in some test data in one of the textfields and submit it: I do not see any of the submitted values in my `_submit` function.

Neither `$form` nor `$form_state` contains any of the values I input into the text fields.

I wonder if this is because I am rendering `#theme => "table"`? Has any one ran into this issue? Any Ideas on changes I can make that would allow me to see the values I am inputting when I post the form to the `_submit` function?

# Answer
The problem is that your textfield elements are located under the `#rows` property of your render array.

Drupal sees any array key beginning with `#` as a property/attribute, and any array key not beginning with that as an element that needs to be recursively attended to. As such the children you've got under `#rows` will be ignored by the form builder.

Since `theme_table` will run on the render array, your form elements *will* actually be rendered out to the screen, but the form won't have any knowledge of the values (as they are not technically children of the form).

In my experience the best way to do this sort of thing is to use a specific theme function on the element:

```
function MYMODULE_theme() {
  return array(
    'MYMODULE_textfield_table' => array(
      'render element' => 'element'
    )
  );
}

function theme_MYMODULE_textfield_table($vars) {
  $element = $vars['element'];

  $rows = array();
  foreach (element_children($element) as $key) {
    $rows[] = array(
      array('data' => 'label'),
      array('data' => $element[$key]['#extra_data']['field_name']),
      array('data' => $element[$key]['#extra_data']['field_name']),
      array('data' => render($element[$key]))
    );
  }

  $header = array(t('Field Label'), t('Field Name'), t('Location'), t('Stuff'));
  return theme('table', array('header' => $header, 'rows' => $rows));
}

```

Then in your form function you would use code like the following

```
$form['things'] = array(
  '#prefix' => '<div id="things">',
  '#suffix' => '</div>',
  '#tree' => TRUE,
  '#theme' => 'MYMODULE_textfield_table'
);

foreach ($type_fields as $field_name => $attrs) {
  $form['things'][] = array(
    '#type' => 'textfield',
    '#default_value' => $attrs['stuff'],
    '#extra_data' => array('field_name' => $field_name)
  );
}

```

After that your textfields should be registered in the form and you should be able to see the value in the `$form_state` array as normal.
> 14 votes

---
Tags: 7, forms
---


# Question
Title: Getting a better handle on APC Cache Bins / code for settings.php
I've got APC up and running on my VPS and have installed the APC module on my Drupal 7 site. I followed the documentation here and added this code to my settings.php file:

```
$conf['cache_backends'] = array('sites/all/modules/apc/drupal_apc_cache.inc');
$conf['cache_default_class'] = 'DrupalAPCCache';
//$conf['apc_show_debug'] = TRUE;  // Remove the slashes to use debug mode.

```

However, on my site's status page under APC, it says:

```
APC has been running for 3 min 54 sec. Currently caching 0 entries (0 bytes).

```

To me the *"0 entries"* indicated that there was no cache being created / used. I did some digging around and it looks like there might be additional code I need to add but cannot find documentation anywhere.

I found this snippet but not really sure if I need it or what part it I am supposed to use and what it does, I could not find any documentation for this. I suspect this is what makes the cache work.

```
'page_cache_without_database' => TRUE,
        'page_cache_invoke_hooks'     => FALSE,
        'page_cache_maximum_age'      => 3600,
        'cache_lifetime'              => 0,
        /* my note -- noticed "cacherouter" in the path below
         so I am guessing this needs to be adapeted to the path for APC?? */
        'session_inc'      => './sites/all/modules/cacherouter/session.inc',
            'cache_default_class'               => 'DrupalAPCCache',
            'cache_class_cache'                 => 'DrupalAPCCache',
            'cache_class_cache_block'           => 'DrupalAPCCache',
            'cache_class_cache_bootstrap'       => 'DrupalAPCCache',
            'cache_class_cache_content'         => 'DrupalAPCCache',
            'cache_class_cache_filter'          => 'DrupalAPCCache',
            'cache_class_cache_form'            => 'DrupalAPCCache',
            'cache_class_cache_menu'            => 'DrupalAPCCache',
            'cache_class_cache_page'            => 'DrupalAPCCache',
            'cache_class_cache_pathdst'         => 'DrupalAPCCache',
            'cache_class_cache_pathsrc'         => 'DrupalAPCCache',
            'cache_class_cache_session'         => 'DrupalAPCCache',
            'cache_class_cache_session_user'    => 'DrupalAPCCache',
            'cache_class_cache_update'          => 'DrupalAPCCache',
            'cache_class_cache_users'           => 'DrupalAPCCache',
            'cache_class_cache_views'           => 'DrupalAPCCache',
            'cache_class_cache_views_data'      => 'DrupalAPCCache',
      );

```

Any help on this matter would be appreciated.

The information about the APC extension returned from `phpinfo()` are the following ones.

# Answer
> "APC has been running for 3 min 54 sec. Currently caching 0 entries (0 bytes)."

This message suggests that your APC is running for each php request separately ultimately not caching anything at all.

I had a similar issue and it required to set up PHP once again but in a different mode.

APC works fine for multiple processes with apache/2 + php 5.3.x + php-fpm + fcgi in FPM/FastCGI mode.

PHP 5.3.x is configured with following options --enable-force-cgi-redirect --enable-fastcgi --enable-fpm

In APC section of my php info I can see:

APC Support = enabled Serialization Support = php MMAP File Mask = /tmp/apc.something | where something is a random 6-character string

Please check your phpinfo

In PHP Configure Command you should have: '--enable-fastcgi' and '--enable-fpm'

In Server API : **FPM/FastCGI**

Check if you have cgi-fcgi section and if you can find **php-fpm** set to "active"

NOTE: There might be another solution if you use php 5.2.x or older.
> 6 votes

# Answer
APC should only be used for smaller parts of the cache, that dont change frequently. So probably not pages for example. (the actual bins where it is wise to use APC may vary depending on the site ... for example vars or menu).

Indeed, before you start caching data, first fine-tune your settings for caching scripts (so turn of that module).

You should use the script apc.php to see how much memory was used to cache the scripts and make sure you give APC enough memory (the default setting - 32M in your case is not necessarily enough) - otherwise the cache can be even worse - slowing the site down by trying to cache again and again. If you are limited on resources, dont be afraid to give it a fair share - it pays off (a tuned apc can get you lower amount of RAM per pageview).

I was also playing with not caching some directories (a crazy module with a lot files or the admin parts of views for example). Also, remember that in the default setting it is trying to cache ANY php file on the VPS ... even running two drupals side by side can be problematic (newly visited code is pushing the older out of the cache) - so i suggest limiting it to one drupal.

this is a useful resource to see http://php.net/manual/en/apc.configuration.php and one with relation to drupal : http://xerosphere.net/optimizing-apc-for-drupal
> 3 votes

---
Tags: 7, configuration, caching
---


# Question
Title: How to create node reference fields in Drupal 7?
I am puzzled. This was a very valuable option in D6 CCK, but since it moved into core, I can't find the option to create a noderef field (found a term reference field, though). I know it must be out there, where is it?

# Answer
> 11 votes
The project that maintains the Drupal 7 versions of the "node reference" and "user reference" field types is References.

Part of the code of CCK has been ported in core code, but some code is still living in third-party modules. CCK itself has a version for Drupal 7, which contains the code to update from Drupal 6 to Drupal 7 (among other things).

# Answer
> 7 votes
I found this summary very helpful.

I would skip References, it looks like it is on its way to being deprecated.

For simple D6 style user and node references use Entity Reference. This module is required by Drupal Commerce so as long as that project is alive and thriving so will entityreference.

If you looked at entity reference and your needs are more complicated check out Relation. You can come up with a very complicated entity relationship scheme using relation, but I wouldn't go down this road unless you know you need the flexibility.

---
Tags: 7, entities
---


# Question
Title: How to convert a D7 db_query object to string?
I am trying to perform the following:

```
$office_ids = db_query('SELECT OFFICE_ID FROM sage.OFFICE');
foreach($office_ids as $office) {
  ...
  $path = 'office-' . (string)$office;
}

```

However, I am getting the following error:

```
Recoverable fatal error: Object of class stdClass could not be converted to string in main() (line 31 of /var/www/drupal7/create_nodes_office.php).

```

How can I cast an object returned by 'db\_query' into a string?

Thanks.

# Answer
> 1 votes
I can't see any benefit to doing that, are you sure you're not trying to get the `OFFICE_ID` value like this?:

```
$office_ids = db_query('SELECT OFFICE_ID FROM sage.OFFICE');
foreach($office_ids as $office) {
  ...
  // Depending on your database settings this might actually be lower case, i.e. $office->office_id
  $path = 'office-' . $office->OFFICE_ID;
}

```

---
Tags: 7
---


# Question
Title: Block-Placement in a Feature via Context
I have got a Feature consisting of a few boxes and a context which puts those boxes in the right regions. That works if I install drupal and my theme and activate the feature.

But it does not work if i install it using drush site-install and my installation profile which contains my theme and my feature. I guess this is because the theme gets activated after the feature and so the feature does not know the regions while activating. What would you recommend to solve this? I could remove my feature as a dependency and activate it manually after my theme in myprofile.install, but is there a "cleaner" approach?

# Answer
> 1 votes
i think doing it in profile.install is clean enough :)
you only set the theme to default in there anyway, dont you ?

# Answer
> 0 votes
I'm guessing you mean "blocks" rather then boxes... It that is the case, you need to also download and Features Extra: http://drupal.org/project/features\_extra

Once that is available, enable fe\_block. That will add a machine name to your blocks. Fill in the machine name, and once done with that, you will see those blocks "available" when creating/updating a feature.

---
Tags: 7, features, theming, distributions
---


title: IE9 & Drupal Form with in iFrame

text:
# Question
Title: IE9 & Drupal Form with in iFrame
I know, wrap your head around it! Heh. I am having an issue in IE9 when trying to submit a form button via Drupal 7 & Drupal Commerce.

Example: http://www.um-me.com/frame.html

I have the following Drupal form source code

```
<form class="commerce-add-to-cart commerce-cart-add-to-cart-form-8" enctype="multipart/form-data" action="/band/4/band-ninjas?fb=TRUE" method="post" id="commerce-cart-add-to-cart-form-8" accept-charset="UTF-8">
    <div>
        <input type="hidden" name="product_id" value="8" />
        <input type="hidden" name="form_build_id" value="form-oJeTHBh1Qn5myvhzMEgLvG5B6zY0vN7So0iQ4M3bazY" />
        <input type="hidden" name="form_token" value="psKsdV22J3T3ybyHXCJifIVlmdjhmlIM8u8iun9WLvQ" />
        <input type="hidden" name="form_id" value="commerce_cart_add_to_cart_form_8" />
        <div id="edit-line-item-fields" class="form-wrapper"></div>
        <input type="hidden" name="quantity" value="1" />
        <input type="submit" id="edit-submit" name="op" value="Add to cart" class="form-submit" />
    </div>
</form>

```

This is taken directly from Drupal. I am using it as a method to test. The actual live (also non working in IE9 version) of this is here: https://www.facebook.com/dijitl/app\_187714134672420 (click the buy button)

This works in all of the other major browsers, but for some reason it does not work in IE. I have tried a "normal" non-drupal form within an iFrame and it worked fine in IE, which leads me to believe that Drupal needs something from the form that IE is not giving it.

# Answer
This looks like a security problem to me. I examined the headers being sent by IE and the session variable in the cookie doesn't appear to be getting set/transmitted. This is because IE has strict rules about cookies in iFrames, whereas Firefox does not. Without the session variable, your cart is not being saved. I would take a look at this related question: https://stackoverflow.com/questions/389456/cookie-blocked-not-saved-in-iframe-in-internet-explorer and apply the solution presented there. It should solve your problem.
> 3 votes

---
Tags: 7, commerce, forms
---


title: Reminder action for users

text:
# Question
Title: Reminder action for users
I'm using drupal 7.
Simply i need to remind some user every 28th to do something.
What the best module to make a reminder for users?

# Answer
You could use the Rules module to do this.
> 0 votes

---
Tags: 7
---


title: Show last created node in views

text:
# Question
Title: Show last created node in views
I'm using Drupal 7. I have created two content types (A & B); content type B is referenced from content type A.
I want to create a view, I need to filter the nodes of content type B by showing the last node only (by date), for every node from content type A.

How can I achieve this?

# Answer
You need to create a relationship in Views. Then filter by creation date descending, and limit results to 1. 'Relationship' is how Views does a SQL JOIN.

It's non-trivial to describe, so I'll just link to a tutorial: http://drupaleasy.com/blogs/ultimike/2009/07/using-views-relationships-arguments-attachments
> 1 votes

---
Tags: views
---


# Question
Title: How do I add an ID to the ul tag of a menu?
I am able to add unique ids to menu links by either adding code to my theme's template file or by using a menu module; however, I would like to add a unique id to the ul tag that encapsulates the menu li links. The reason that I would like to implement this is to style the menu as a whole instead of the menu's individual links. My ultimate goal is to take the whole menu and float it to the right in the header-top region of drupal. I am rather new to Drupal so, perhaps there is another way to achieve this?

I originally attempted custom css styles using the skinr module without success. The skinr module was able to move the menu's title to the right, but the menu's links were still located at the left of header-top.

My setup consists of Drupal 7

*UPDATE* I was able to add a custom CSS class "user-menu" to the user-menu block. Next I added a custom css to mix-and-match-style.css

css code:

```
.user-menu ul li {
     padding: 0;
     float: right;
}

```

The css code seems to float: right the menu, but the links are not ordered properly once floated to the right. The correct order of the links should be "My account | Log out". When the list is floated to the right the order changed to: "Log out My account |"

Is that a bug or am I not understanding something?

# Answer
> 2 votes
You can make use of `theme_menu_tree`

```
function theme_menu_tree($variables) {
  return '<ul class="menu">' . $variables['tree'] . '</ul>';
}

```

http://api.drupal.org/api/drupal/includes%21menu.inc/function/theme\_menu\_tree/7

You can print this menu tree

```
template_preprocess_menu_tree

```

hereis api

Pre process the menu tree OR Call the menu theme to print it as you want. Thats all.

---
Tags: routes, theming
---


title: Flag a node n days after its creation

text:
# Question
Title: Flag a node n days after its creation
Similar to Drupal Answers, I'm creating nodes that are questions. Once I create a question node, I want to have it flagged as 'unanswered' if a user doesn't flag it as 'answered' within 10 days. I have Flags module setup so I can click 'answer/un-answer this question' on the node itself and Views displays the unanswered questions. I'm thinking that the Rules module will be of assistance here, but I do not see a way to start a timer (for lack of better words) in Rules once a node has been created.

Thank you.

# Answer
> 2 votes
You'll need to enable Rules Scheduler, which is a sub-module included as part of the Rules module.

You can watch a screencast on how to use Rules Scheduler from Node One here.

---
Tags: 7, rules, flags
---


title: Need block content for each menu items

text:
# Question
Title: Need block content for each menu items
I need to have a separate block for a each menu items in my menu (Add item section).Is there any drupal module can help me or i should write the custom module.Please suggest the possible ways to do.

# Answer
There is no module you can use with your situation. Possible way.

1. Create separate menu and place them in each block.

Please describe your scenario so that we can discuss more.
> 0 votes

---
Tags: 6, routes
---


# Question
Title: Will managed files be deleted if no corresponding entry exists in file_usage?
I am using the services module to implement a REST API. One resource allows POSTs with uploaded files. During a services pre-process function I save the file to the temp directory. During a services post-process function, I move the file to a private directory, call file\_usage\_add, and save the host entity. When a validation error occurs between saving the temp file and moving the temp file to a permanent location, I am not explicitly deleting the temp file. I thought drupal cron would take care of this for me, since no entry for this file exists in file\_usage. However, it doesn't appear that cron is taking care of this for me. Any thoughts as to why this is?

When reviewing file\_managed, I see the temporary file that I'd like deleted. When reviewing file\_usage, I don't see any corresponding record.

Update -- One additional piece of info: in most cases, the file is actually missing. I believe this is due to OS reboot clearing out the /tmp directory. Regardless, would system\_cron still remove the file\_managed entry for a file if the actual file were no longer found?

This problem arose since I started uploading files from a native mobile app. The filename is the same every upload. There are some cases where the temp filename doesn't exist in the /tmp directory, but a record in file\_managed still exists with a URI of that filename. So I'm getting an integrity error when the file\_managed table is being saved. I plan on updating the app to create a random filename. In the meantime, I'd like to clean up the database and surrounding "glue" logic that manages these files. If system\_cron will do it all for me then great. But from what I can tell, system\_cron is not removing old, completely unused (and unreferenced) records in file\_managed.

# Answer
Drupal automatically deletes temporary files in system\_cron().

Permament files which have no file\_usage are not deleted, however.
> 8 votes

---
Tags: 7, files
---


# Question
Title: Modify Drupal's search to show custom fields
I have some fields (say, pictures or whatever) in my custom `content-type` and I want them to appear in search results. How do I do that?

I know how to edit template files such as `search-result.tpl.php` provided by the search module. In this page, there is a single variable called `$snippet` which contains search result but as a rendered HTML output. How do I modify it/show my custom fields in search results?

I would like to have full control to contents of the files, rather than just rendered HTML for them. My Search display page requires customization a lot, so without getting each field individually, I won't be able to produce desired output.

# Answer
> 1 votes
Try the Display Suite module. There you can change the appereance of a content type in different view modes. One of these view modes is for example the search result.

# Answer
> 0 votes
This page shows the info you need to customize the indexing of your fields.

As for the output, this one should lead you on the correct path.

---
Tags: 7, search
---


# Question
Title: Load published nodes of certain content type
I have to load nodes of certain content type that are published.

Any built in function already available for this purpose?

# Answer
To load a bunch of nodes based on custom parameters, you have to use EntityFieldQuery. It replaces the `$conditions` array `noad_load_multiple` used.
> 2 votes

---
Tags: 7, nodes
---


title: How do I print a view table?

text:
# Question
Title: How do I print a view table?
I am using Drupal 7 with the Print module installed.
I used this module to print nodes, but how can I print a view table?

Is there a module that I can use?

# Answer
> 2 votes
If you're familiar with the Print module, you could simply embed the view you're displaying into a normal node and use Print to print the page. I didn't try this but I see no reason it wouldn't work.

In your node's tpl.php, do something like this :

```
print views_embed_view('your_view', 'the_display_you_want');

```

# Answer
> 2 votes
Most people just use a stylesheet to exclude layout for printing. it does not rely on any particular module.

The idea is simple, you include a stylesheet in your theme which removes the layout from your site, typically by using `style:display:none;` etc. You also size the font and remove images where possible to save ink.

You can read a really good tutorial here: http://www.alistapart.com/articles/goingtoprint/

---
Tags: 7
---


# Question
Title: Is there any harm is manually modifying file_managed status?
I'd like to manually change the status column of a record in file\_managed. The file URI is located in a permanent location. I simply forgot to change the status to 0 before performing file\_save. I have no need to for all the hooks to get called associated with saving a file. So is it safe to manually update the status field in a file\_managed record?

Along the same line, if there are no references to a particular fid in file\_managed (ie no corresponding records in file\_usage and no other fid references), is it safe to remove the file\_managed record altogether?

# Answer
No there's no harm in modifying the table manually, as long as you know what you're doing.

If there are no references to the file in the `file_usage` table, and you don't need the file any more, it's perfectly safe to simply delete the line from the `file_managed` table. Alternatively you could set the `status` for that file to zero in the table, and let it be deleted automatically on Drupal's cron run.

The advantage of doing it that way is that the physical file is also deleted automatically so you don't have to clean up yourself.
> 11 votes

---
Tags: 7, files
---


# Question
Title: Doubt with display a query using Custom Field Module in View
I have installed the CustomField module. I have a view and I'd like to add a new column in a table in the view. The content of this column is a result of a query to a table different to node. Is this possible with this module?

I am using Drupal 6.

# Answer
> 0 votes
You can set up relationships in views to pull data from other tables should you have to. There's a screencast from Drewish here on how they work and how to set them up.

Basically, you'd need to set up a relationship based on a part of the current data in the row. After this, more data is exposed to you in the fields section of views.

If I'm misunderstanding your question and you'd just like to embed a view withing a view, then check our the Views Field View module.

> This module allows you to embed a view as a field in a view.
>
> This view can accept arguments from fields of the parent view using tokens.

---
Tags: views, 7
---


# Question
Title: Custom forms for custom post types in D7
I am sub-theming Bartik and have a content type called "support\_query" with 3 fields... "title" (which comes with all content types), "field\_support\_body" and "field\_support\_date" (which is a simple date field from the Date module).

I would like to create a custom form so users can send me queries of this custom post type... what's a good way to do something like that?

# Answer
You should use your content type's form, customized to suit the basic user.

You'll have to give the allowed users role the right permission (like \`Create *the content type*').

Then you'll have to change the form to mask all irrelevant information. There are many ways to do this :

* Implement a module with a \`hook\_form\_alter'. Flexible but involves coding.
* Use a module or a combination to achieve the same goal. This one for example seems to be interesting.
> 0 votes

# Answer
You could just give anonymous users permission to create nodes of this content type.

Here's what I'd do:

1. Give users permission to create \*support\_query\* nodes.
2. Give the node/add form an alias (you can set this at `admin/config/search/path`) for the *support request* content type (for example, alias it to *www.example.com/support-request*)

After this you can do some pretty useful things...here are a few examples:

* Use Views to create reports of submitted support requests,
* Use the Flag module to set flags on the content (e.g. received, assigned, in progress, completed to name but a few)
* Set some Rules up to e-mail the user who submitted the support request when it is flagged at each different stage (e.g. e-mail a user when their request has been assigned to an employee)
> 0 votes

# Answer
Use Webform module

> Webform is the module for making surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has and extensive API for expanding its features.
> -2 votes

---
Tags: 7, forms
---


# Question
Title: How to hide Default values using Drupal Behaviour
I have created a form using the web form module. In this form i have 3 field. Name, Email and Phone. I have set the default values for Name as Name , Email as E-mail and Phone as Phone (Done this using the form settings).

Now the scenario is, when the user clicks on the Name field , The default values has to go off. I tried this using jQuery but it didnt work. So i thought of using Drupal Behaviours with jQuery.

This is my code

```
(function (jQuery) {
 Drupal.behaviors.amendor = {
    jQuery('edit-submitted-phone').focus(function() {
      alert('Chekcing the values');
      if (jQuery('edit-submitted-phone').val() == 'edit-submitted-phone'.defaultValue) {
        jQuery('edit-submitted-phone').val('');
      }
    });

    jQuery('edit-submitted-phone').blur(function() {
      alert('setting the values');
      if (!jQuery('edit-submitted-phone').val()) {
        jQuery('edit-submitted-phone').val('edit-submitted-phone'.defaultValue);
      }
    });
  };
})(jQuery);

```

# Answer
To start with, as you're namespacing jQuery you can use the `$` instead of jQuery inside the `(function (jQuery) { ... });`

Secondly, you're not pointing to classes or ID's in your jQuery. I'm pretty sure that `edit-submitted-phone` should be `#edit-submitted-phone` in every instance in your code.

If this doesn't work, then let me know and I'll see what else I can come up with.
> 2 votes

# Answer
There's a module called Compact Forms that does this for you.

If you still want to do it yourself, I'd suggest **against** using the `defaultValue` attribute since this can screw up the form processing if you didn't put necessary logic in the validate and submit handlers (which is more work) and it's generally not a nice way to do this imho.

Instead, since you can select any attribute with `jQuery.attr()`, I'd suggest creating your own custom attribute in the `hook_form_alter` and assign the default values there. And just check the current values against that attribute like so:

```
if (jQuery('#edit-submitted-phone').val() == jQuery('#edit-submitted-phone').attr('my-custom-attr')) {
  jQuery('#edit-submitted-phone').val('');
}

```

And finally as Chapabu mentioned, you're missing the vital parts of your selectors, which is the ID (`#`) or the Class (`.`) selectors just like you'd write in a CSS document.
> 0 votes

---
Tags: forms, javascript, webforms
---


# Question
Title: The best way to synchronize old host and new host when migrating a Drupal site?
I'm planing to migrate my live site from the current shared host to another shared host. I'm thinking to use Backup and Migrate module or importing/exporting mysql by phpmyadmin.

However I'm concerning about the new users who register on my site and their content profile node. Because on both old and new host users will be registered for some while (maybe 2 weeks?). And in this period there probably will be duplicated User ID and Node ID with different data on both hosts.

Is there any way to prevent this or synchronize both old and new site for some time?
Or is it safe to import eventually the data of discrepancy from the old one to the new one just changing uid and nid after name server propagation is completed?

# Answer
> 0 votes
if i get it right, you are afraid it would get 2 weeks for people (or their computers) to notice the change of DNS ? (is that the only reason for running two sites in paralel ?). That shouldnt be necessary. You should be able to set the TTL (time to live) on your current DNS records and then (after some time - 24hours minimum) change it to the new IP adress and it shouldnt take more than a day for everyone to realise. (see http://www.dnswatch.info/articles/dns-update \- other records).

Anyway, if you still think you want people to work on 2 sites :). You could setup the next value for the ID on the important tables (node, user, comment, file ?),

```
 ALTER TABLE tbl AUTO_INCREMENT = 100;

```

probably on the new database so that it would be possible to merge the two databases afterwards. But it still is quite complicated - you cant just use backup migrate - you cant replace the databse, you have to MERGE it.

Probably something like deploy could be of help, but rather harder to set up if its just for the few days.

# Answer
> 1 votes
I think you're on the right track. It is nearly impossible to implement a migration project and not plan for incremental updates. The migrate module supports that with its "update" function (as shown in the screen shot).

That said, there shouldn't be a problem of duplicate UIDs after the initial migration of data, unless you are letting people create accounts on both the legacy system and the new instance.

# Answer
> 1 votes
I might be way off here, but since we know that DNS update takes only up to 24 hours at most, why not just put an upgrade notice on the old site and disable new content and user creation for a couple of hours while the migration is progressing?

# Answer
> 0 votes
Create and import the database in the new server, Use this db from the shared hosting changing the data in setting.php so all the new changes will be in one database. Then you change the dns for your domain name and should be ok. Or do the opposite: leave the db in the shared hosting and use it from the new server, then put the website offline for 5 minutes and import the new database.

Be careful because you will work with one db, and the changes will affect both website.

---
Tags: 6, migrations, backups, database
---


# Question
Title: How to properly add multiple form elements in a loop?
I have a form where I need to loop through an array and display multiple form elements in a specific area.

Example:

```
$form_layout = 'Some html';
$form_layout .= '<div>';

foreach($something as $key => $value) {
    $form_layout .= 'some html';
    $form_layout .= 'some html';

    // I need this to be displayed in between the above and below code
    // in the layout
    $form['awesome_element'] => array(
        '#type' => 'textfield',
        '#size' => 5,
        '#value' => 0
    );

    $form_layout .= 'some html';
    $form_layout .= 'some html';
}

$form_layout .= '</div>';
$form_layout .= 'Some html';

$form['some-other-awesomeness'] = array(
    // ...
    '#prefix' => $form_layout,
);

```

Doing it like the example puts the textfields after all the other page elements. I have tried using #prefix and #suffix but that breaks the layout even worse.

Any ideas on what I should do?

Edit: For clarity...

If I had layout elements such as a div tag I need my form elements, such as textfields, to be inserted in between those div tags.

So I need it to output something like this:

```
<div>
FORM ELEMENT
FORM ELEMENT
FORM ELEMENT
</div>

```

Instead it is outputting something like this:

```
<div></div>
FORM ELEMENT
FORM ELEMENT
FORM ELEMENT

```

Hopefully that is more clear, sorry if the above is confusing. Looking at code for the last 20 hours.

Edit2: added some visual stuff to make it easier to understand

# Answer
Could you do something like the following:

```
$form['openingdiv'] = array(
  '#markup' => '<div>'
);

//Do all your foreach stuff here

$form['closingdiv'] = array(
  '#markup' => '</div>'
);

```

(Sorry it's a bit simple..I'm tired :-p)
> 2 votes

---
Tags: forms
---


# Question
Title: Modules or install profile for scholarly peer review
Are there any modules or installation profiles available to create a peer-review system, such as used by academic journals and conferences? I've found lots of discussions on Drupal.org but no actively maintained modules.

Update: here is an example of a commercial system showing the kinds of features I'm looking for.

# Answer
Depending on what you would like to do, there are two potential approaches.

On the simple end, you have fields on content types that only certain roles can edit. For example, you can have a field called **vetted** and two roles, **author** and **expert**. When an **author** makes a new node, **vetted** would get set to some default value, like **not verified**. Your **expert** users can then read and review the nodes, and sets the **vetted** field as appropriate, say **verified** or **needs further review**.

One the more complex end, you can use workflow. Two modules that do this are Workflow and Workbench. With this, you can set up just about any editorial review process that you want. Both can also be combined with Drupal actions to occur on state transitions. Just keep in mind that workflow can be a pain to set up, and often there are real work scenarios that don't always work into rigid workflow rules.

As for existing systems, Open Atrium may potentially fit the bill. It is more designed for team collaboration, but based on what clients have said, it may work for something more conference oriented.
> 1 votes

---
Tags: 7
---


# Question
Title: How to translate a menu item in Main Menu with a path to a page View
I'm sure I've done before, but I'm working in a fresh drupal installation and I guess I missed some configuration related to translation.

> ```
> 1) I created a new View which generate a Page.
> 2) I set No menu for Menu  (see image 1)
> 3) I set /inmuebles for Path  (see image 1)
> 4) In the Main Menu I added 2 links one for each language (english and spanish)  (see image 2)
> 5) Each link are set to the correct language (see image 3)
> 6)The problem: both link are shown in both languages. (see image 4)
>
> ```

Of course I need the links to be shown **ONLY** in their respective languages.

**Image 1**

**Image 2**

**Image 3**

**Image 4**

# Answer
> 1 votes
I was a problem related to Superfish module which I'm using to generate the main menu. Here is the patch for the superfish module patch

---
Tags: routes, i18n-l10n
---


# Question
Title: Programmatically created nodes are not appearing under table 'nodes'
I have written a PHP script for the programmatic creation of nodes:

```
<?php

define('DRUPAL_ROOT', getcwd());
$_SERVER['REMOTE_ADDR'] = "localhost";
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// Get a list of Office ID's
$office_ids = db_query('SELECT OFFICE_ID FROM sage.OFFICE');

// Loop through and edit each user
foreach($office_ids as $office) {

  // Create a new node object
  $node = new stdClass();

  // Set our new node content type
  $node->type = "office";

  // Set the node title
  $node->title = "Office " . $office->office_id;

  // Set the language
  $node->language = LANGUAGE_NONE;

  // Set the UID of the author of the node; or use $node->name
  $node->uid = 1;

  // Set node details
  $node->body[$node->language][0]['value'] = $bodytext;
  $node->body[$node->language][0]['summary'] = text_summary($bodytext);
  $node->body[$node->language][0]['format'] = 'filtered_html';

  $path = 'office-' . $office->office_id;
  $node->path = array('alias' => $path);

  if($node = node_submit($node)) {
    node_save($node);
    echo "Node with nid" . $node->nid . " saved!\n";
  }
}

```

When I run the above script, I can see my NIDs incrementing (and I assume this means my nodes are created), however when I go and check in the 'nodes' table in the database, I see nothing added.

Does anything know what could be wrong?

# Answer
> 2 votes
The `$node` object you pass to `node_save()` wouldn't get it's `nid` member populated unless the node has been successfully saved to the `node` table in the database.

The auto-increment ID actually comes from the database table so if the `$node` object has a `nid`, you can pretty much guarantee the record has been successfully inserted into the table.

Make sure that the software you're using to view the table doesn't have some sort of paging turned on, meaning that only the first x number of records are actually showing in your results. Most MySQL UI software (PHPMyAdmin, Navicat, etc.) limit the number of results you see in a table by default; if you want to see more you need to change the setting.

If you want to do a quick check run the following query on your database:

```
SELECT MAX(nid) FROM node

```

Note down that number, then run your code again. Finally run the above query one more time. If the `nid` you get the second time around is greater than the one from the first time round, you know the record has definitely been added to the database.

---
Tags: 7, nodes
---


# Question
Title: How do I create a static block programmatically?
I want to create a static block using a module. I do not want to use the Views module to create a block. Could anyone explain me how to create a static block programmatically?

I have already checked the example modules in Drupal, but it didn't help me much. I have started Drupal module development every recently and I am struggling to do this.

# Answer
The important hooks in the Block example module are `hook_block_info()` and `hook_block_view()`. The info hook defines your block in the system and the view hook creates the output (html) for your block.

Every module, including yours, will have at least a .info file and a .module file. Drupal.org has some more documentation about .info files that you may find helpful when getting started with modules. Yours really just needs the `name` and `core` entries.

The .module file is where you'll implement your hooks. First, implement `hook_block_info()`, replacing 'hook' in the function name with the name of your module, e.g., `my_module_block_info()`. It should look something like the following.

```
function my_module_block_info() {
  $blocks['your_block'] = array(
    // info: The name of the block.
    'info' => t('Your Block Name'),
  );

  return $blocks;
}

```

Then, implement your `hook_block_view()` hook to define the static content.

```
function my_module_block_view($delta = '') {
  // The $delta parameter tells us which block is being requested.
  switch ($delta) {
    case 'your_block':
      // Create your block content here
      $block['subject'] = t('Title of first block (example_configurable_text)');
      $block['content'] = 'Your block content, or the result of a function that returns the content';
      break;
  }

  return $block;
}

```

Once you have that in place, you can put your block in any region as you would any other block in Drupal.
> 21 votes

---
Tags: 7, blocks
---


# Question
Title: Add a Drupal site wide contact form to the maintenance page
How do I add the Drupal site wide contact form to the maintenance page?

I'm currently using a custom maintenance-page.tpl.php template page in my theme.

# Answer
I would try to override the default template file through maintenance-page.tpl.php and then use template\_preprocess\_maintenance\_page to alter the variables stack and basically add the rendered form as a variable. But I don't know what would happen if you submit the form while in maintenance.
> 2 votes

# Answer
I'm not sure if this is possible directly in Drupal. On my sites, I use an external form for this job. That is, it's not a Drupal form. You could use e.g. http://www.free-php.net/410/recaptcha-contact-form/. Just put the ContactForm folder in your Drupal root folder, and you'll be able to link to yoursite.com/ContactForm/contact.php from your maintenance page (edit your maintenance-page.tpl.php file to do this). (Well, there is some minor configuration to do, and you may want to edit the style.css as well. For instance, I did not like the text-transform that's used here...)

A benefit is that the mentioned form actually uses reCaptcha to stop spam, and you'll be able to use the keys you've already created for your site, as the form is placed within your Drupal root folder.

Works for me, even if a solution through Drupal would've been preferable (less extra configuration...). Hopefully someone finds this helpful.
> 1 votes

---
Tags: 7
---


title: Amazon like sort box on taxonomy page

text:
# Question
Title: Amazon like sort box on taxonomy page
I have a taxonomy term page that lists certain nodes. I would like to include custom sort options like the one on amazon's search results page, at the top. It is a drop down with sort options, unlike the usual clicking on a table column. I have searched but found no resources on implementing this in drupal. Any ideas on how I can implement this? Thx

# Answer
> 1 votes
The most easy way to get this taken care of is use the Views module. Set up a view that queries for nodes based on the term as an argument. This will give you what you already have, however, it will also allow you to use exposed filters to get more granular with the results based on the values of the exposed fields.

If you would like to learn more about exposed filteds and views, check out this video, which is not the best video in the world, but highlights using exposed filters in Views, which should hopefully get you on the right track.

As a summary, what your doing is replacing Drupal's built in taxonomy view pages with a view instead and allowing views to handle the querying and filtration of the data respectively.

Happy Programming!

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


# Question
Title: Show block on specific pages URL attribute
I am looking to show a certain block on a page only when a certain url attribute (using alias)

For example:

I have pages /foo/\*

I want to show the The block when viewing /foo/\*?showblock

Where * is a wildcard.

I have tried typing this into my "Show block on specific pages" portion of the block settings, but the block never shows. Any ideas? Thanks!

# Answer
> 2 votes
You can use PHP visibility on your block settings to achieve this. Drupal block's visibility does not provide the functionality to display blocks based on parameters after ? (aside from ?q= of course) so you need to do this with custom PHP.

Set your block visibility to use PHP as the markup and place this in your code:

```
<?php
// Show the block if the 'showblock' attribute is available
if (!empty($_GET['showblock'])) {
  return TRUE;
}
return FALSE;

?>

```

Happy Programming!

# Answer
> 2 votes
It's definitely worth looking at the Context module. This should help you no-end with problems like this.

That said, TheRealWebGuy has a better answer if this is just a one-off, but it's always better to know these things :-)

---
Tags: 6, blocks
---


# Question
Title: How to place multiple form elements from a loop
I have a table that will have multiple table rows that are generated dynamically using a foreach loop. In these rows will be textfields using the Drupal forms API.

Example:

```
$f = '<table>';
$f .= '<tr><td>Something...</td></tr>';

foreach($somethingAwesome as $val){
    $f .= '<tr><td>';

    $form['blah'][$val] = array(
        '#type' => 'textfield',
    );

    $f .= '</td></tr>';
}

$f .= '<tr><td>Something else...</td></tr>';
$f .= '</table>';

$form['woot'] = array(
    '#type' => 'whatever',
    '#prefix' => $f
);

```

This winds up outputting the form elements after the table in the page. This is not what I am expecting.

The output looks something like:

```
Something...
Something else...

Textfield
Textfield
(etc...)

```

It should look like this:

```
Something...

Textfield
Textfield
(etc...)

Something else...

```

I have tried using the #prefix in the textfield form elements but that produces some odd unexpected (at least for me) behavior.

I am using Drupal 7, if that makes any difference.

Edit: Added that I am in fact adding the $val to the $form element in the foreach loop

# Answer
> 1 votes
You could try this if I understand correctly:

```
$header = '<table>';
$header .= '<tr><td>Something...</td></tr>';

$form['header'] = array(
  '#markup' => $header;
)

$i = 1;

foreach($somethingAwesome as $val){

    $form['blah_' . $i] = array(
        '#type' => 'textfield';
        '#prefix' => '<tr><td>'
        '#suffix' => '</td></tr>'
    );

$i++;
}

$footer = '<tr><td>Something else...</td></tr>';
$footer .= '</table>';

$form['footer'] = array(
    '#markup' => $footer,
);

```

This should give you the output:

Something...

TEXTFIELD TEXTFIELD TEXTFIELD

Something else...

You'll need to do something to differentiate each `$form['blah']` part too, otherwise you'll be running a `foreach` loop that overwrites that specific part of your form on every iteration.

You're running your `foreach` loop in the place where you *want* it, but all of the data you want surrounding the form is being put into one variable, and then added in one go as a prefix. Suffix will add data to the end.

**General Reference (in case you didn't know):**

FormAPI Reference

**Specific References:**

#prefix

#suffix

---
Tags: forms
---


# Question
Title: In Views, how can I show only the results for content that has been tagged with two taxonomy terms?
I'm using Drupal 7:

I have a taxonomy term view that uses two contextual filters (i.e. taxonomy/term/%/%). Under 'Relationships' I have selected: 'Content: Taxonomy terms on node'. Under this relationship I have selected two vocabularies. Under 'Contextual Filters' I have selected: '(terms) Taxonomy term: Term ID'. Within the contextual filter I've selected 'Display contents of "No results found"' under 'WHEN THE FILTER VALUE IS NOT IN THE URL'.

The reason for two contextual filters is because the content is tagged with two term reference fields each of which correspond to a different taxonomy vocabulary.

The problem is that the results I get are not filtered by the second taxonomy term.

For example, if some content has been tagged with 'board of directors' (tid = 29) and 'people' (tid = 34) then everything that is tagged with 'board of directors' displays under taxonomy/term/29/34 even if they have not been tagged with 'people'.

How can I configure my view so the results are filtered according to two taxonomy terms?

# Answer
> 1 votes
I'm not sure why are you using Relationships for this. Simply, from "Contextual Filters" section, create a "Content: Has taxonomy term ID". In that filter's settings -\> "More" settings -\> Check "Allow multiple values" which:

> If selected, users can enter multiple values in the form of 1+2+3 (for OR) or 1,2,3 (for AND).

i.e. go to `view_path/29,34` will filter results by both terms.

Hope this helps.

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


title: render add to cart using views

text:
# Question
Title: render add to cart using views
Is it possible to use views to render block with add to cart button, then add a contextual filter, so I can use it in panels?

For testing, I tried to make a simple view consisting of add to cart buttons and use it on a product page, but it displays nothing.

The same is with displaying pictures attached to product. I can see them when creating view in view UI but how do I pull out data from product so I can display them on product page using using views or just placing a block on a page.

Any help would be appreciated. Thank you

# Answer
Self answered by user1031742

I had to enable permissions for viewing product - namely: View any Product product. Otherwise any content pulled from product would be forbidden to all users but administrator.
> 0 votes

---
Tags: views, commerce
---


# Question
Title: Is there a way to stop comment_node_view from firing?
I need to use the Commentsblock module, but it is turning out to be pretty buggy. I've got an issue in the queue with a patch for comments not displaying for anonymous users.

Now I've got a second issue posted about how paging is broken, but I'm stumped on how to fix it so wanted to see if anyone else had an idea.

Here is the issue: http://drupal.org/node/1513910

My question is: Is there a way to prevent the comment\_node\_view function from executing?

Or....should I be going about this an entirely different way (backup plan is to use Views to display comments in a block, but I can't think of a way to respect threading so would like to avoid that if possible).

# Answer
> 1 votes
You can implement `hook_module_implements_alter()` and stop the hook being run for the comment module:

```
function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'node_view') {
    unset($implementations['comment']);
  }
}

```

Once you clear the cache `comment_node_view()` won't be called any more.

---
Tags: comments
---


# Question
Title: $_SESSION vars created outside of Drupal lost when navigating to a Drupal served page
I'm building a **Facebook iframe app** in Drupal.

I'm using an initial simple PHP script (non-Drupal driven) to handle the Facebook open auth side of things - this script is getting the Facebook user's name, id, profile pic etc. This script stores those values to session vars. Then it redirects the user to a page served by Drupal.

My understanding looking at the D7 `session.inc` is that pre-existing session vars should be maintained when Drupal session start is called. But if I `print_r()` the `$_SESSION` array, it is empty.

So essentially a plain PHP script saying:

```
session_start();
$_SESSION['name'] = 'bob';

```

sets the session correctly. But when then adding a redirect (`header()`) to a Drupal served page I can no longer get that name variable and the session is empty.

Any suggestions/tips?

Thanks, Steve

# Answer
> 4 votes
A really good source related to your question from drupal.org's forum:
**Struggling with Session Variables (the `$_SESSION` array) when redirecting to external php scripts**

The key for codes outside Drupal's full control to work is to save PHP's current working directory, change it to Drupal's, requiring the needed file to bootstrap Drupal (`includes/bootstrap.inc`), pass the appropriate `$cookie_domain` variable (*"the domain to be used for session cookies"*!), bootstrapping Drupal, and then change the current working directory back to the original. After this, you can write your own codes and use Drupal's functions, mess with its session variables, etc. - of course, depending on the bootstrapping mode of Drupal.

The code to achieve it looks like this (you have to change `$your_drupal_directory` variable to yours, usually this is in the root, but its path can be different \[e.g. if it's in a subdirectory\]):

```
// ...

/**
 * @see http://drupal.org/node/575002
 */

// store current working directory
$currdir=getcwd();
// which is your Drupal directory? (usually it's in the root, but can be different)
$your_drupal_directory = $_SERVER['DOCUMENT_ROOT'];
// change PHP's current directory to Drupal's
chdir($your_drupal_directory);
// including bootstrap file...
require_once("./includes/bootstrap.inc");

// The domain to be used for session cookies. (see: http://api.drupal.org/api/drupal/developer!globals.php/global/cookie_domain/7)
$cookie_domain = $_SERVER['HTTP_HOST'];

// DRUPAL_BOOTSTRAP_SESSION: initialize session handling.
drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);

// the code above should be enough for your task, but if you want Drupal to be "fully loaded, validate and fix input data", you could try the following too (see: http://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/drupal_bootstrap/7)
// drupal_bootstrap( DRUPAL_BOOTSTRAP_FULL );

// change PHP's current directory BACK to the original
chdir($currdir);

// ...
// YOUR OWN CODE COMES HERE
// ...

```

---
Tags: 7, sessions
---