# Question
Title: How to check if page exists using page alias in D7?
In D7, how do I check whether a page exists by page alias? I've found some guy asking the same very question but I have problems with using menu\_valid\_path() (or drupal\_valid\_path() in D7) function. It always returns TRUE, no matter how weird a path I pass to it. Here is a sample code:

```
if(drupal_valid_path($GLOBALS['base_url'] . '/contacts')) //this exists
{
    print_r('Exists!');
}
if(drupal_valid_path($GLOBALS['base_url'] . '/weird_alias')) //this doesn't exist
{
    print_r('Exists!');
}

```

I get two "exists" despite the fact that /weird\_alias page doesn't exist and returns a "page not found" error. I'm extremely reluctant to use drupal\_http\_request() because there are a lot of unnecessary things like headers, timeouts etc. Shouldn't there be an easier way to check internal paths?

# Answer
If you look at the code for `drupal_valid_path()` it passes the alias through `url_is_external()`, which considers paths with a `http://` prefix to be external. The function defaults to allow access to these sorts of paths and simply returns that fact; it does not check whether the 'external' url exists.

Since you're adding `$GLOBALS['base_url']` to the alias it will appear to be external; you just need to pass the alias into the function without the base URL attached:

```
if(drupal_valid_path('weird_alias')) {
  // This code is never run
  print_r('Exists!');

}

```
> 7 votes

# Answer
Just try this

```
if(drupal_valid_path('contacts') == 1) //this exists
{
    print_r('Exists!');
}
if(drupal_valid_path('weird_alias') == 1) //this doesn't exist
{
    print_r('Exists!');
}

```
> 2 votes

---
Tags: 7, uri, path-aliases
---


title: Show links depending on role's name

text:
# Question
Title: Show links depending on role's name
I want to show a custom link for each role on my site. To do so, I will put PHP code in my page.tpl.php. I want to add an if statement that checks if the current user's role is equal to something, then print the link.

How can I get the current user role?

# Answer
```
global $user;
if($user->roles[1] || $user->roles[2]){
//Do Something
}

```
> 3 votes

---
Tags: 7, navigation
---


# Question
Title: 128 character limit in Drupal text fields
I maintain a small module on Drupal.org and I'm having a few problems fixing this issue:

http://drupal.org/node/917340

Is this limit of 128 characters imposed by Drupal Core? Can I do anything in my module's code to work around this limit? Or is it best to suggest that users of my module use something like http://drupal.org/project/maxlength or http://drupal.org/project/skip\_validation?

# Answer
> 6 votes
Maybe my brain isn't in gear, but in your code you have `'#maxlength' => 128,` everywhere... Changing that to 4096 worked here and allowed a really long message. Changing `textfield` to `textarea` and removing `#size` and `#maxlength` worked as well.

---
Tags: forms
---


# Question
Title: Change workflow default state with hook_form_alter()
How can I programmatically access and alter the Workflow module settings with `hook_form_alter()` on a node edit form?

I can see the Workflow\] module settings in its own field-set on the node edit form, but I cannot find any mention of it when I look at the output of `dd($form)`, `dd($form_state)`, or `dpm($form)`.

I would have expected to find it somewhere similar to the following.

```
$form['edit_workflow']['value'];

```

# Answer
$form\['workflow'\] is accessible using #after\_build within the Form API.

```
function hook_form_alter($form, &$form_state) {
    $form['#after_build'][] = '_manage_workflow';
}

function _manage_workflow($form, &$form_state) {
    $form['workflow'] = ''; //Do workflow alterations here...
    return $form;
}

```
> 0 votes

# Answer
It seems your implementation of hook\_form\_alter() runs before the one provided by the Workflow module. Implement hook\_module\_implements\_alter() to change the order in which implementations of hook\_form\_alter() are executed. Alternatively, give your module a higher weight than the Workflow has.

Beware that this approach does not work for changing the order of implementations of hook\_form\_FORM\_ID\_alter() specifically. Implementations of hook\_form\_FORM\_ID\_alter() are always executed in the same order as those of hook\_form\_alter(). This is due to the way how drupal\_prepare\_form() calls drupal\_alter().
> 0 votes

---
Tags: 7, forms, workflows
---


title: Admin module for content managers

text:
# Question
Title: Admin module for content managers
I am building a drupal website for a customer (=content manager) of mine. Normaly I would just adjust the permissions for the content manager so he can change what he needs to. But it would be much simpeler if I could provide a menu with shortcuts of the actions he needs.

To keep everything clean I would like to use rubik and the admin menu.

Is there a way to hide all the "admin" links for the content manager and add some custom menu links my own ? So I can provide a "custom" content management system for his needs without all the drupal possibilities (which I only need).

# Answer
> 2 votes
Try the Quickbar module.

> This is a simple administration toolbar. It allows you to take any menu and assign it to a role. This menu will be displayed at the top of your page as an administration toolbar.

Most of this module is taken from \[the\] Admin \[m\]odule version 1.x. It also uses some features from the Toolbar module.

# Answer
> 1 votes
The links to actions the user doesn't have access to won't appear if I'm not mistaken.

However, you might be better off using the toolbar instead of admin\_menu and adding a couple links to management menu.

Try and login as that user, you will see a much less-cluttered toolbar because of permissions :)

---
Tags: 7
---


title: Menu callback rendering node xxx

text:
# Question
Title: Menu callback rendering node xxx
I want to render node/7 on /mymodule/info. I don't want to use path to cover it. What callback function shall I use?

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

  $items['mymodule/info'] = array(
    'title' => t('My module'),
    'description' => t('My module description'),
    'page callback' => ?????????,
    'type' => MENU_CALLBACK,
   );

  return $items;
}

```

# Answer
> 1 votes
You have to call the same callback issued from `node/%node` menu i.e. node\_page\_view :

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

  $items['mymodule/info'] = array(
    'title' => t('My module'),
    'description' => t('My module description'),
    'page callback' => 'node_7',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function node_7(){

include_once(drupal_get_path('module','node') . '/node.pages.inc');

return node_page_view(node_load('7'));

}

```

# Answer
> -1 votes
Try

```
function mymodule_menu() {
  $items = array();
  $items['mymodule/info'] = array(
    'title' => t('My module'),
    'description' => t('My module description'),
    'page callback' => 'rendernodeseven',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function rendernodeseven() {
    print_r(node_load(7));
}

```

---
Tags: 7, nodes, routes
---


# Question
Title: hook_field_formatter_view doesn't get called
I'm kind of new to this formatter, widget system, so i hope you can help me out. I'm trying to add a new widget to field type list\_text, so i have added a info hook like this

```
function market_field_widget_info() {
  return array(
    'product_list' => array(
    'label' => t('Product List'),
    'field types' => array('list_text'),
    'settings' => array('size' => 40),
    'behaviors' => array(
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
    ),
  ),
);

```

And to my widget i have added a widget form hook like this

```
function market_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

  if ($instance['widget']['type'] == 'product_list' && arg(0) == 'node' ) {

  $node = node_load(arg(1));

  $options = array();
  foreach($node->field_products['und'] as $item ) {
    $entity = entity_load('field_collection_item', array($item['value']));
    $options[$item['value']] = $entity[$item['value']]->field_title['und'][0]['value'];
  }

  $element['product'] = array(
    '#type' => 'select',
    '#title' => t('Vare'),
    '#options' => $options,
  );
return $element;
}

```

And this works great, i get the information into the selector that i want, but when it is posted nothing is displayed, so i added a view to it

```
function market_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  switch ($display['type']) {
    // This formatter simply outputs the field as text and with a color.
    case 'default_list':
      foreach ($items as $delta => $item) {
        $element[$delta]['#markup'] = "TEST";
      }
      break;
  }

  return $element;
}

```

But still nothing, am i missing something here? I have tried putting in a die, but its like the view hook is never called, hope you can help.

Best regards

# Answer
In order for `hook_field_formatter_view()` to be called you also need to implement `hook_field_formatter_info`, to let the field system know about your custom formatter.

There's a good article called Creating new field formatters in Drupal 7 that has a step by step guide.
> 7 votes

---
Tags: 7, entities
---


# Question
Title: How to prevent Drupal from automatically truncating blog entries?
When you enable the Drupal 7 Blog module, the *blog* page (http://mydrupal.tld/blog) displays truncated blog entries. It looks like Drupal truncates after the end of the first paragraph (`<p>`). In order to see the entire blog entry, you have to click on its title or on the *Read more* link.

I'd like to save that click to my visitors by displaying full length blog entries directly on the *blog* page.

It seems that `print render($content);` performs the truncation, but I couldn't find anything in the method's API about that.

Any idea ?

# Answer
The length of the body text for a node teaser is set in the "Manage Display" section for the content type's fields.

Just go to http://mysite.com/admin/structure/types/manage/blog/display/teaser, and change the format/format settings (i.e. "Trim length") until the teasers look exactly like you want.
> 3 votes

---
Tags: nodes
---


# Question
Title: Is there a firm or preliminary decision on which modules will leave Core for 8?
I seem to recall I've seen a more than one discussion about breaking out certain less than maintained modules from Core. They would presumably be moved to contrib instead. Currently I can't find any information on this topic.

# Answer
There is an issue report for that (\[Meta\] Make core maintainable), but nothing has been decided yet. As you can see, there are different opinions about what to remove, and what to keep.
catch, the latest maintainer added to Drupal 8, expressed his opinion on that; the same did Dries, chx, Crell, and eaton (just to cite some of them). There is an agreement about some of the modules to remove, but there isn't a complete agreement.

That issue report is not marked as postponed, and a new issue report has been opened (Establish heuristics for core feature evaluation).
> 3 votes

---
Tags: 8
---


title: Is there something like block_field?

text:
# Question
Title: Is there something like block_field?
I need to be able to include block in the content of a node. I use display suite to accomplish this, but just wondering if is there something like block\_field?

# Answer
You can use the http://drupal.org/project/blockreference. It's a standard on our projects now. It also works well with the http://drupal.org/project/bean module
> 2 votes

# Answer
I just discovered this module which lets you insert a block directly into content via a `[block]` tag.

If you prefer the field way, I think display suite is the way to go, which is hat you did already.

Maybe CCK blocks could be of use, but as it is, I'm not sure what use case you're trying to cover so maybe it's OT.
> 1 votes

---
Tags: entities, blocks
---


title: PHP 5.4 and Drupal 7

text:
# Question
Title: PHP 5.4 and Drupal 7
I have heard that PHP 5.4 is faster than PHP 5.3.

Would it be ok for Drupal 7 to run under 5.4, or various contributed modules may start to break the site?

Anyway, If I use APC opcode cache, maybe 5.4, would not offer any benefit at all?

Thanks

# Answer
> 28 votes
I have begun running Drupal 7 on PHP 5.4 myself with only minor problems in the form of notices and warnings.

On top of 7.12, you will need these two patches to fix the issues causing PHP to complain:

http://drupal.org/files/menu-link-save-1338282-15-d7.patch

http://drupal.org/files/database-query-clone-1414412-11-d7\_0.patch

One of these patches has already been applied to -dev, so will be in 7.13, and the other is likely going in soon. In all cases that I can immediately think of, the bad practice causing 5.4 warnings has been bad use of array keys.

The first version of this looks like this:

```
$some_key = function_call();
return $some_array[$some_key];

```

Some times, the function call will return an array or an object, neither of which is a valid array key. In PHP 5.3, what actually, and silently happens, looks like this:

```
$some_key = function_call();
return $some_array[(string)$some_key];

```

PHP 5.4 however, warns that this may not be what you want. The second version is exactly the same, but the other way around.

```
$some_key = 'a_valid_key';
$may_be_a_string = function_call();
return $may_be_a_string[$some_key];

```

which yields an error message like

> Illegal string offset 'a\_valid\_key'

whenever `$may_be_a_string` is actually a string, not an array, since the only valid string indexes are integers.

As the problems are easy to understand and the fix is (mostly) easy to apply, I've found that in several cases, -dev versions are already updated, or patches posted in the queue, that are likely to quickly go in due to their simple nature.

After some testing, I don't feel like 5.4 is "dangerous" to run in production, and I have begun running my small and personal sites on it already. I would encourage other to do the same, so we can avoid the historically slow uptake of new PHP versions.

At the time of writing, APCs latest version, 3.1.9, **does not** work with 5.4. I have successfully built and used it from git though.

Using APC will likely reduce the performance benefit of upgrading the PHP version, but not remove it.

# Answer
> 2 votes
You should avoid PHP 5.4 as there is no stable APC for it. Performace for PHP 5.3 + APC would be greater than 5.4.

---
Tags: 7, performance
---


# Question
Title: Possible to create fields without admin?
> **Possible Duplicate:**
> Assign Fields programatically to custom node defined by custom module

Is it possible to create fields in code without using admin in Drupal 7?

# Answer
> 2 votes
Yes. Since fieldable things in D7 are called "bundles", you essentially 1. create the field and 2. attach it to the bundle that uses it (could be a content type, etc.) I wrote this function to quickly create and attach fields in my module's .install file:

```
function _add_field_to_bundle($field_name, $cardinality, $type, $label, $entity_type, $bundle, $field_settings=array(), $instance_settings=array()) {

  $new_field = array(
    'field_name' => $field_name,
    'cardinality' => $cardinality,
    'type' => $type,
    'settings' => $field_settings,
  );
  field_create_field($new_field);

  $field_instance = array(
    'field_name' => $field_name,
    'label' => $label,
    'entity_type' => $entity_type,
    'bundle' => $bundle,
    'settings' => $instance_settings,
  );

  field_create_instance($field_instance);
}

```

To use this function to attach a thumbnail image field to a (node) content type:

```
_add_field_to_bundle('field_thumbnail', 1, 'image', 'Thumbnail', 'node', 'content_type');

```

# Answer
> 0 votes
See The following functions.

http://api.drupal.org/api/drupal/modules%21field%21field.crud.inc/function/field\_create\_field/7 http://api.drupal.org/api/drupal/modules%21field%21field.crud.inc/function/field\_create\_instance/7

There is an example here http://api.drupal.org/api/drupal/modules%21field%21field.crud.inc/function/field\_create\_field/7#comment-19499

---
Tags: entities
---


# Question
Title: How to I hide menu items based on its access to different roles?
I have a site with the following users

1. Administrator
2. Author
3. Normal user(authenticated user)

and the modules used for the following task are Nice Menu, Menu token and Print.

The site contains of books and the option shown for every book page is shown in fig.

1. Administrator and Authors will have access to every option.
2. Authenticated user is not able to Edit Page and access the Page History.

By configuring the print module and using tokens I have accomplished the task, but it shows an "Access Denied" error when an authenticated user tries to select that option.

Is there a way to hide the "Edit Page" and "Page History" option for authenticated user and keep it visible to Admin and Authors?

Thank you in advance, Ajit

# Answer
We do this with the Menu Per Role module.

> This module allows you to restrict access to menu items1 based on user roles. It depends on the Drupal core menu.module—just activate both modules and edit a menu item as usual. There will be a new fieldset that allows you to restrict access by role. The fieldset also appears in the node edit form.
> 3 votes

---
Tags: 7, routes, navigation
---


# Question
Title: How do I force rebuilding/generation of files generated by an imagecache preset?
I edited the actions on one of my imagecache presets, but it has only generated a few pictures (instead of hundreds) of pictures.

I am using the preset to in a view to show thumbnails that belong to nodes of a specific content type with the help of a module called teaser thumbnail. All the thumbnails on the first page of the view have been generated correctly, but beyond that, none of the thumbnails have been generated.

I am using Drupal 6.25 with public file system on a shared hosting server.

So the main question is how do forcefully rebuild/re-generate the pictures associated with preset?

Edit : I have already used the 'Flush' function on the preset.

# Answer
Imagecache images are generated on the fly when a browser requests them, rather than when you create the preset or flush the images.

Basically, this is how the process works.

When a URL 404s, the request gets punted to `/index.php` and handled by Drupal.

The imagecache module has a `hook_menu()` entry that handles all of the requests to `sites/default/files/imagecache` (or whatever `file_directory_path()` returns for your site).

The callback for this checks for the requested filename. If the file exists (ie, the derivative has been generated and exists in the filesystem), it gets served up. Otherwise, the module makes the derivative, saves it to the filesystem, and then serves it up.

So, the net result is that you don't need to explicitly generate the derivatives. When a page that has them on it is requested, they will be automacically generated.

If you would like to pre-generete them for performance reasons, then my suggestion would be to write a bash script to find all of the images in your `sites/default/files` directory, and then wget them with the proper imagecache preset path name.

If you are looking at a page and the thumbnails aren't being shown, then you have another problem. Checking the system report would be the first place to check. Typically, the webserver can't write to the filesystem or your image toolkit is messed up.
> 3 votes

---
Tags: views, media, nodes
---


# Question
Title: Alter a select form using preprocess function
For some reason I want to alter the value of a select list in an exposed form of views .

I've added this code to the template.php and also Clear the cache :

```
function mytheme_preprocess_views_exposed_form(&$vars) {
  $myviewID = 'views-exposed-form-ouvrage-page';
    if ($vars['form']['#id'] == $myviewID){
      foreach($vars['form']['field_categorie_tid']["#options"] as $option_term){
        $optionterm = $optionterm."test";
       }
     }
}

```

After this with devel themer I can see the changes that I've mad but when I clear the cache the changes dosen't take in the select list

am I missing something ? I'm new with preprocess function

# Answer
In your `foreach` loop, `$option_term` is a *copy* of the current variable returned from the iteration. If you want to change the original variable (i.e. what's in `$vars['form']['field_categorie_tid']['#options'][index]`) then you need to pass it by reference:

```
foreach($vars['form']['field_categorie_tid']["#options"] as &$option_term){
    $option_term .= 'test';
}

```

Or refer to the array member explicitly like so:

```
foreach($vars['form']['field_categorie_tid']["#options"] as $key => $option_term){
    $vars['form']['field_categorie_tid']["#options"][$key] .= 'test';
}

```

I generally prefer the second method as passing variables by reference in this way can sometimes cause some strange behaviour.

You also had a slight code error, the variable is called `$option_term` in your loop declaration but `$optionterm` in the loop body.

Just FYI, template preprocess functions are really not the best place for this sort of code. You would be far better off using `hook_form_alter()`.
> 2 votes

---
Tags: 7, theming
---


# Question
Title: Alter the username label in the login block
I want to alter the username label. Instead of *username*, I want to change it to *User ID*.

I've written the following code to perform this function, but I'm not sure how to implement it. When I implement it in the page that contains the login block, nothing happens.

```
function lae_form_user_login_form_alter(&$form, &$form_state, $form_id) {
 $form['user-login-form']['edit-name']['#title'] = t('User ID');
}

```

Will this actually work? If it will, how do you implement it?

# Answer
> 3 votes
Your code needs to go inside a custom module. Assuming your module is called `lae` then you just need to make one or two small changes to your code:

```
function lae_form_user_login_form_alter(&$form, &$form_state, $form_id) {
  $form['name']['#title'] = t('User ID');
}

```

The `edit-` prefix that you get from the element's ID in HTML is actually provided by Drupal automatically, it's not the name of the key in the form array that identifies the element. Also the elements (at least for this particular form) will normally be at the root of the array so you don't want to reference `$form['user-login-form']['edit-name']` (as it most likely doesn't exist).

I would advise downloading and installing the Devel module and using the `dpm()` function to print a nice representation of your form array to the screen, so that you can inspect it and see the correct array keys you'll need to target to effect a certain element.

```
// Add this to your form alter function:
dpm($form);

```

# Answer
> 0 votes
You can use the String Overrides module.

> Provides a quick and easy way to replace any text on the site.
>
> ### Features
>
> * Easily replace anything that's passed through `t()`
> * Locale support, allowing you to override strings in any language
> * Ability to import/export \*.po files, for easy migration from the Locale module
> * Note that this is not a replacement to Locale as having thousands of overrides can cause more pain then benefit. Use this only if you need a few easy text changes.

---
Tags: 7, forms
---


# Question
Title: My horizontal navigation menu disappeared
I can't be specific which event might have caused this to happen. Too much could have happened between me noticing the problem and the first time the problem could have occurred.

Here's what I'ved checked so far but got me no results in bringing back my main menu

* logged in as the administrator and made sure all of the permissions where switched on.
* rolled back to the database and code folder from appr. 24 hours ago.
* See if block called 'main menu' is still in the appropriate region under admin-\>structure-blocks. This is the case.
* Placed the block 'main menu' in a different region to see if the html would show there. Nothing showed.
* Moving a block different than 'main menu' (in this case the stock 'navigation menu') into the region where I want 'main menu' to show. Navigation menu came up fine. This confirms that nothing is wrong with the region in question.
* Went and see under admin-\>structure-\>blocks where I clicked 'configure' of the 'main menu' block. All visibility settings were normal and shouldn't be causing dissapearing.
* Compared the page.tpl.php file to other page.tpl.php of websites that does show the horizontal nav menu and everything looked fine.
* installed menu\_block module. Nothing changed.
* Made a menu from scratch, which worked. Until after a few refreshes menu items started disappearing again. And yes, cleared caches, disabled caching, checked visbility settings checked permissions again and again.
* Checked if the blocks were set to correct theme.
* Discovered query logging in the `devel` module. Not that I very well know how to interpret it but what I can share maybe are the queries that take longer than those standar 5ms

---

**Here are the query logs that take more than 5ms**

* `11.72 5 DrupalDatabaseCache::getMultipleP A E
SELECT cid, data, created, expire, serialized FROM cache_bootstrap WHERE cid IN (:cids_0)
default`
* `9.19 1 language_listP A E
SELECT * FROM languages ORDER BY weight ASC, name ASC
default`
* `33.16 5DrupalDatabaseCache::getMultipleP A E
SELECT cid, data, created, expire, serialized FROM cache_bootstrap WHERE cid IN (:cids_0)`
* `11.552 5DrupalDatabaseCache::getMultipleP A E
SELECT cid, data, created, expire, serialized FROM cache_menu WHERE cid IN (:cids_0)
default`
* `16.17 5DrupalDatabaseCache::getMultipleP A E
SELECT cid, data, created, expire, serialized FROM cache WHERE cid IN (:cids_0)
default`
* `21.08 2DrupalDefaultEntityController::loadP A E
SELECT revision.vid AS vid, base.uid AS uid, revision.title AS title, revision.log AS log, revision.status AS status, revision.comment AS comment, revision.promote AS promote, revision.sticky AS sticky, base.nid AS nid, base.type AS type, base.language AS language, base.created AS created, base.changed AS changed, base.tnid AS tnid, base.translate AS translate, revision.timestamp AS revision_timestamp, revision.uid AS revision_uid FROM node base INNER JOIN node_revision revision ON revision.vid = base.vid WHERE (base.nid IN (:db_condition_placeholder_0))
default`
* `18.67 5DrupalDatabaseCache::getMultipleP A E
SELECT cid, data, created, expire, serialized FROM cache WHERE cid IN (:cids_0)`
* `8.11 2metatag_metatags_load_multipleP A E
SELECT 1 FROM metatag LIMIT 0, 1`
* \`21.72 1\_system\_date\_format\_types\_buildP A E

SELECT dft.type, dft.title, dft.locked FROM date\_format\_type dft ORDER BY dft.title default\`

* `18.2 1system_date_format_localeP A E
SELECT format, type, language FROM date_format_locale
default`
* `18.11 1i18n_menu_initP A E
SELECT ml.*, m.*, ml.weight AS link_weight FROM menu_links ml LEFT OUTER JOIN menu_router m ON m.path = ml.router_path WHERE (ml.menu_name IN (:db_condition_placeholder_0, :db_condition_placeholder_1, :db_condition_placeholder_2, :db_condition_placeholder_3, :db_condition_placeholder_4, :db_condition_placeholder_5, :db_condition_placeholder_6, :db_condition_placeholder_7, :db_condition_placeholder_8, :db_condition_placeholder_9)) AND (ml.link_path IN (:db_condition_placeholder_10, :db_condition_placeholder_11)) AND (ml.language IN (:db_condition_placeholder_12, :db_condition_placeholder_13))
default`
* `20.36 1DrupalDatabaseCache::getMultipleP A E
SELECT cid, data, created, expire, serialized FROM cache_admin_menu WHERE cid IN (:cids_0)`
* `25 1DrupalDefaultEntityController::loadP A E
SELECT base.fid AS fid, base.uid AS uid, base.filename AS filename, base.uri AS uri, base.filemime AS filemime, base.filesize AS filesize, base.status AS status, base.timestamp AS timestamp, base.type AS type FROM file_managed base WHERE (base.fid IN (:db_condition_placeholder_0, :db_condition_placeholder_1, :db_condition_placeholder_2, :db_condition_placeholder_3, :db_condition_placeholder_4, :db_condition_placeholder_5, :db_condition_placeholder_6, :db_condition_placeholder_7))`
* \`42.8 1PagerDefault::executeP A E SELECT COUNT(\*) AS expression FROM comment c WHERE (c.nid = :db\_condition\_placeholder\_0) default\`\`
* `6.79 1PagerDefault::executeP A E
SELECT c.cid AS cid, SUBSTRING(c.thread, 1, (LENGTH(c.thread) - 1)) AS torder FROM comment c WHERE (c.nid =`
* `16.25 1node_tag_newP A
SELECT 1 AS expression FROM history history WHERE ( (uid = :db_condition_placeholder_0) AND (nid = :db_condition_placeholder_1) ) FOR UPDATE
default`
* `8.681node_tag_newP A
UPDATE history SET timestamp=:db_update_placeholder_0 WHERE ( (uid = :db_condition_placeholder_0) AND (nid = :db_condition_placeholder_1) )
default`
* `19.761_block_load_blocksP A E
SELECT b.* FROM block b WHERE (b.theme = :db_condition_placeholder_0) AND (b.status = :db_condition_placeholder_1) ORDER BY b.region ASC, b.weight ASC, b.module ASC
default`
* \`8.021block\_block\_list\_alterP A E SELECT module, delta, rid FROM block\_role default\`\`
* `4.671node_block_list_alterP A E
SELECT module, delta, type FROM block_node_type
default`
* \`35.741i18n\_block\_block\_list\_alterP A E SELECT module, delta, language FROM i18n\_block\_language default\`\`
* `6.2425DrupalDatabaseCache::getMultipleP A E
SELECT cid, data, created, expire, serialized FROM cache_menu WHERE cid IN (:cids_0)`
* `5.9125DrupalDatabaseCache::getMultipleP A E
SELECT cid, data, created, expire, serialized FROM cache_menu WHERE cid IN (:cids_0)
default`
* `27.471menu_tree_check_accessP A E
SELECT n.nid AS nid FROM node n WHERE (n.status = :db_condition_placeholder_0) AND (n.nid IN (:db_condition_placeholder_1, :db_condition_placeholder_2, :db_condition_placeholder_3, :db_condition_placeholder_4, :db_condition_placeholder_5, :db_condition_placeholder_6, :db_condition_placeholder_7, :db_condition_placeholder_8, :db_condition_placeholder_9, :db_condition_placeholder_10)) AND (n.language IN (:db_condition_placeholder_11, :db_condition_placeholder_12))
default`
* `17.2925DrupalDatabaseCache::getMultipleP A E
SELECT cid, data, created, expire, serialized FROM cache_menu WHERE cid IN (:cids_0)
default`
* `15.441devel_node_access_block_viewP A E
SELECT na.* FROM node_access na WHERE (na.nid IN (:db_condition_placeholder_0, :db_condition_placeholder_1)) ORDER BY na.nid ASC, na.realm ASC, na.gid ASC
default`
* `12.542DrupalDatabaseCache::getMultipleP A E
SELECT cid, data, created, expire, serialized FROM cache_metatag WHERE cid IN (:cids_0)
default`
* `5.862DrupalDatabaseCache::getMultipleP A E
SELECT cid, data, created, expire, serialized FROM cache_metatag WHERE cid IN (:cids_0)
default`
* `6.815DrupalDatabaseCache::getMultipleP A E
SELECT cid, data, created, expire, serialized FROM cache WHERE cid IN (:cids_0)
default`
* `8.711DrupalDatabaseCache::getMultipleP A E
SELECT cid, data, created, expire, serialized FROM cache_variable WHERE cid IN (:cids_0)
default`
* `19.161DrupalDatabaseCache::getMultipleP A E
SELECT cid, data, created, expire, serialized FROM cache_token WHERE cid IN (:cids_0)`
* `11.871menu_local_tasksP A E
SELECT menu_router.* FROM menu_router menu_router WHERE (tab_root = :db_condition_placeholder_0) AND (context <> :db_condition_placeholder_1) ORDER BY weight ASC, title ASC
default`
* `21.811_node_revision_accessP A E
SELECT COUNT(vid) FROM node_revision WHERE nid = :nid`
* `8.5225DrupalDatabaseCache::getMultipleP A E
SELECT cid, data, created, expire, serialized FROM cache_menu WHERE cid IN (:cids_0)`
* `5.891commerce_product_ui_commerce_product_type_infoP A E
SELECT * FROM commerce_product_type`

# Answer
Alright, so the site got set to another language somewhere in the middle of configuring it. Menu items were set in the previous language resulting in them not being displayed in the new system language.
> 0 votes

---
Tags: 7, routes, blocks
---


title: deleting nodes from a view

text:
# Question
Title: deleting nodes from a view
I have created view which displays a list of nodes. I made a custom module with a function which calls db\_query() to delete the specified node in the list. I made a Global:Custom Text field in the view which I made into a link to point to that function. The link works perfectly, the node is deleted from the database table, but now the view still lists a blank line (where that node used to be) which still has the Global:Custom Text field there. How can I get rid of this line completely?

# Answer
Why not use the Views Bulk Operations module? This is a great module for updating and deleting nodes from Views.
> 2 votes

---
Tags: views, 7
---


# Question
Title: How can I loop through entity reference values?
My content type "Export" has an entity reference to the type "country" (i.e. you assign countries to the export). I wish to do something like the following

```
$countries = $node->field_exporter_countries['und'][0]['value'];

foreach ($countries as &$value) {
   print $value;
}

```

### Edit

I also tried this. But i get the wrong titles back.

```
$nodes = entity_load('node', array_keys($countries));
foreach ($nodes as $n) {
  print $n->title;
  print "<br /> ";
}

```

# Answer
> 3 votes
According to the `entityreference_field_schema()` function, the column name for an entity reference field is `target_id` (not `value`). That said, to extract the node ids you should probably use something like this:

```
$nids = array();
foreach ($node->field_exporter_countries[$node->language] as $index => $item) {
  $nids[] = $item['target_id'];
}

$nodes = entity_load('node', $nids);

// etc...

```

# Answer
> 2 votes
I don't have Drupal in front of me at the moment so this is pure guestimation, but I think you're actually looking at doing something like the following:

```
$countries = $node->field_exporter_countries[$node->language];

foreach ($countries as $key => $data) {
  print $data['value'];
}

```

Note that I've used `$node->language` instead of `und` as a personal preference, but there are other benefits.

# Answer
> 0 votes
Generally if you have a field, and you want to format its output a certain way, you implement a field formatter.

And if you do implement a new field formatter, Drupal will call `hook_field_formatter_view()` for you, with `$items` as a handy array to turn into a renderable array.

---
Tags: entities
---


title: Cache front page for logged in users

text:
# Question
Title: Cache front page for logged in users
I'm having a performance crisis with my front page. I have the standard drupal cache enabled which works great for anonymous users, but my front page is practically unusable for logged in users.

The front page doesn't contain any user-specific information, so it would be great if the front page was always cached version for all users.

Actually, there is a user account link in the header which is user-specific, but I'd be willing to forgo that (display as anonymous) for the quick, all-encompassing solution. I'm working on a real caching solution for logged in users, but I'd like a quick fix like this.

# Answer
AFAIK there is no easy way of getting a cached page as though the user was anonymous.

The easiest solution is probably to cache the elements of the front page, but that's hard to say without knowing how it's built and what's elements it consist of.
> 1 votes

---
Tags: 6, caching
---


title: How to create a view with no data

text:
# Question
Title: How to create a view with no data
I have a content type with a number of fields, one of which is state (pending/active/complete). Users can also be assigned to a piece of content. Eg Frank is linked to content titled "Blah" with state "active".

I want to create a view that shows users who ARE NOT linked to any content with the state field "active".

So far, I figured I can show a list of users and then using relationships, I pull up and reference the content.

It is easy enough to show users linked to content that has the state field "active", but for the life of me, I cannot figure out how to show users who ARE NOT linked to content with state "active".

Any ideas?

# Answer
Thank you all.

In the end I added a new field to the user as Jimajamma suggested, which counts the number of state (active) nodes that user has. I used Rules to add and subtract from the number to keep it current. Views then filters, only reporting on users with 0 state (active) nodes.
> 1 votes

# Answer
From what I'm able to understand, you want to be able to see users that are not linked to that piece of content type. Thus, could you possibly just create a view that uses a contextual filter for users NOT of that content type?
> 0 votes

# Answer
I'd say go the other way round:

Create a view of Users and add a relation to the nodes.

Then, in your filter, set your state field to Pending or Inactive. You can select multiple values IIRC.
> 0 votes

# Answer
One way I can see this being done easily is to have another field linked somehow to your user that is incremented when the user is assigned or otherwise has active content. In D6, this could be as simple as having an integer field in a content profile. Using permissions you could set it up so the user can't change or edit it and then whenever a user is assigned a piece of active content, this gets incremented. When that content is no longer active, or assigned to another user, it gets decremented. This logic could easily be put inside nodeapi(). Then you could use a view to look for users with this field being zero. You could also look for overworked users, too :)
> 0 votes

# Answer
If I can understand correctly, you just want a view of users not connected to "active" content right?

Here's what I would do:

1. Create a User view
2. Add an entity reference relationship for your user reference field (I'm assuming this is how you are linking users)
3. Add two filters (normal, not contextual) for field\_state; first one is "is not one of: active" which will display users linked to pending/complete content and second one is "is empty" which will display users who are not connected to anything
4. Create a new filter group (click the arrow next to "add" and select "rearrange") and change the operator to OR
5. Put those two filters you created in this OR group, and you should be good to go.

This worked for me on a new test bed I made just now, so it SHOULD work for you too. But I am not sure how complicated your site currently is so your mileage may vary. Let me know if it works.
> 0 votes

---
Tags: views
---


# Question
Title: How do I translate the Webform module form?
I really see no way of translating the Webform module. Is anyone else facing this issue?

I know it is possible with locale (for the same node), or creating another node, but I really want to use the first option.

# Answer
> 7 votes
The Webform front-facing form was given the ability to be modified (and thus translated) in this issue: Make Webform multilingual (i18n) aware through contributed modules. That enhancement is already included in the latest versions of Webform, but that improvement is merely at the API-level; Webform module doesn't provide any translation abilities itself.

The add-on module that provides translation abilities for Webform is called Webform Localization, but it is currently only available as a sandbox project here: http://drupal.org/sandbox/GDrupal/1407100

The author of the module just recently (2 weeks ago) received the green-light to turn the module into a normal fully-promoted project, which will make it more easily accessible on Drupal.org.

The Webform Localization module provides two modes of translation, one that uses separate nodes and syncs certain webform settings between the nodes; and one that uses a single node and makes the strings available to translate through the i18n\_strings module. The single-node approach is also what I've been advocating and I've tested that it works with this module. Only the single-node approach keeps all of the results from all languages aggregated together, with separate nodes the results are separate for each language.

# Answer
> 1 votes
Does this post at drupal.org help at all?

From what I understand, Webforms are not directly translateable yet, so you'll have to create multiple versions of your form and assign them as belonging to the required language.

---
Tags: webforms, i18n-l10n
---


title: Using Drush make to install a profile

text:
# Question
Title: Using Drush make to install a profile
I use make files for a number of different flavours of sites that I build, then manually insert my own profile into the site/profiles/ directory. Can drush make download and automatically insert the profile folder into the correct place?

Thanks

Kieran

# Answer
> 9 votes
Sure. Take a look at the file drupalorg\_testing.make.bootstrap in the drupalorg\_testing project. The relevant part is:

```
projects[drupalorg_testing][type] = "profile"
projects[drupalorg_testing][download][type] = "git"
projects[drupalorg_testing][download][revision] = "master"

```

Usually, when building a profile, you will download only Drupal core and the profile in the bootstrap makefile, and put all of your other modules in the makefile that is bundled in the profile. If you are making a makefile that makes use of someone else's profile, then you may include your additional modules in your top-level (bootstrap) makefile.

If you ever want to move a module from one location to another, you'll want to use the registry rebuild tool. It will fix up the system table to account for the module's new location.

---
Tags: 7, drush
---


# Question
Title: Drupal 7 - dynamic, collapsible, navigation bar/block/thing in the sidebar first
Because a picture tells more than 1000 words.
Click here to see the image --\> OPEN IMAGE
On the left side, you will see what I need.
On the right side, you see what I already have.

**The question:**

Is there a possibility for showing all the chapters in a navigation block (or something simular) like a navigationtree ? with collapsible nodes and meanwhile if you click on some of those chapters, the main page changes?

perhaps with jquery?
But I can't find any good documentation whereby I can say, That's what I need.

I hope that someone can help

Kind regards.

Dieter

# Answer
> 2 votes
You can use DHTML Menu or Accordion Menu to get the desired effect.

IMO, DHTML Menu is simpler to use.

---
Tags: routes, navigation
---


# Question
Title: Filter a view basing on a relationship to the current user
This question is similar to Filter View based on current user profile info (from Content Profile Module).

I have an elevated user role (*Facilitator*) that's associated via profile to a location (whose content type is *Space*) and should see a list of pre-authorized users who have matching profile locations that they can authorize or deny. I've built a view using the *Views Bulk Operations* module; I have a custom action to change the user role, all of which is working. I can't figure out how to filter the pre-authorized students by their location matched to the location of the currently logged-in user. Do I have to make a custom filter for this?

The data relationship looks like *User -\> Profile -\> Space*. A profile can have multiple associated spaces. I want the view to only show users whose associated spaces match one or more of the associated spaces of the currently logged-in user. In general they don't need to be locations; they could be interests, or favorite colors, for example.

# Answer
The only way to do this within views is the following:

1. Make View of using User type
2. add a Relationship to a Profile2 type (in my case 'Student')
3. Add Contextual Filter of type profile:student:location
4. select "provide default value"
5. type: "php code"
6. Use the following code:

```
global $user;
$profile = profile2_load_by_user($user->uid,'facilitator');
if (!$profile) { return ''; }
if (!isset($profile->field_location['und'])) { return ''; }
$locations='';
foreach ($profile->field_location['und'] as $location) {
  $locations.=','.$location['nid'];
}
return substr($locations,1);

```
7. Under "More", Set "Allow Multiple Values" to TRUE
8. Save your Contextual Filter

Using PHP in this manner, you can load the current User and get associated values to filter by. This may be useful in many other contexts and circumstances.
> 2 votes

---
Tags: 7, views
---


# Question
Title: Filter a view with information from the currently logged-in user profile (from the Content Profile module)
I have the *Content Profile* module installed. With this module, each user has one to many locations that are attached to them.

These locations are created via the *Locs* content type. I have another content type (*todays\_spot*) which has a single location, dynamically created via the *Locs* content type.

I'm pulling some of the *todays\_spot* data out via a view, but I need to filter it so it only displays data if the user's locations match.

How can I achieve this?

# Answer
See Filter a view basing on a relationship to the current user for a Drupal 7 solution. The same principle applies here.

Create an argument for the related *loc* on *todays\_spot*.
Choose the the right relationship (*node*, I think), and select *Provide default argument*.
Use *PHP code* for your default argument.

You'll need to modify the code to match your system, but it should resemble the following code.

```
// This code uses the Profile2 module. Something similar will work
// with the Content Profile module; you'll need to inspect the module
// to find a function similar to profile2_load_by_user().

global $user;
$profile = profile2_load_by_user($user->uid,'facilitator');

if (!$profile) {
  return '';
}

if (!isset($profile->field_location['und'])) {
  return '';
}

$locations = array();
foreach ($profile->field_location['und'] as $location) {
  $locations[] = $location['nid'];
}

return implode(', ', $locations);

```

Don't forget to select *Allow multiple terms per argument* before saving your new argument.
> 1 votes

---
Tags: 6, views
---


# Question
Title: How can I display a node create form in a Panel pane?
I'm trying to build a Panel page with two columns that are stacked side-by-side. I need the left hand column to display node/add/story, and the right hand column to display node/add/page. How can I do this?

# Answer
> 1 votes
One simple solution is installing formblock. But that won't allow to save the nodes at the same time.

If you dont mind programming, this should be of help.

---
Tags: panels
---


# Question
Title: Is it possible to change the location and size of the blocks/tabs in Drupal?
This is my first time using Drupal. so I am not too familiar with it. My question is that is it possible to change the location, size etc. of blocks/tabs that are available as default through Drupal? The blocks/tabs I am talking about are shown in the following snapshot.

# Answer
> 2 votes
I assume, you are referring to "regions" as "block/tabs". If that is the case, you can add/change the regions in your theme\_name.info file and page.tpl.php file.

You may find this Link useful.

---
Tags: blocks
---


# Question
Title: How to redirect on node save to fill out extra fields attached to terms
I've added a mandatory email field to terms in a vocabulary I have called Instructor. This field is displayed on my content type as an autocomplete term reference. Because it is an autocomplete field, it will save new non-existing tags. I am curious how I can redirect to a page on node save (and subsequently term save) so that users can fill out the email fields?

Better yet, is it possible to limit autocomplete tags to existing terms, and then add a local action for "add a new instructor" where users have to fill out all fields?

# Answer
I've found there's a new module called Entity Connect which adds a button to entity reference fields for creating new references on the fly. The module sends the user to the entity creation page (add term, etc) allowing you to fill out all necessary fields, then redirects back to the original node form.

This works great. Now the only thing necessary now for my use case is to figure out how to programmatically add taxonomy terms based on the value(s) of the entity reference field.
> 0 votes

---
Tags: 7, taxonomy-terms, entities, redirection
---


# Question
Title: How can I stop cron from deleting images I need
I have an image that is being deleted by the drupal 7 cron.

This is not good for us and I am trying to figure out how to prevent this.

As I am new to drupal I am not sure even where to begin but I am pretty sure we add the image via the core image module if that helps.

Please if anyone could help I would be most appreciative and sorry if this Q is too noob for here :)

The image is the only one in it's containing folder too.

# Answer
> 1 votes
Try using

```
<?php
$file->status |= FILE_STATUS_PERMANENT;
$file = file_save($file);
?>

```

While you save the file

**References**

hook\_insert

---
Tags: 7, cron, media
---


title: Global math expression in a views

text:
# Question
Title: Global math expression in a views
I added a global math expression field to a views(table display) i just want to sub two fields values,but the the result it's not exact what i want.
Example for that(9000 - 5000 = 4).
How can i change the format or something like that to convert the result to 4000?
Thanks.

# Answer
> 6 votes
Your problem is the number format of your fields. Turn off the comma that delineates thousands.

# Answer
> 0 votes
You should only need to have `[field_bt_total] + [field_pa_total]` in there--nothing else (no f=, no ;)--and that **should** produce `9000` as the result....assuming of course your `field_bt_total` really does equal `5000` and your `field_pa_total` really does equal `4000.`

# Answer
> 0 votes
As an alternative, you could consider to use the Computed Field module to compute the value, so you can simply add the result to your view just like any other field.

---
Tags: 7, views
---


# Question
Title: Drupal 7 custom block.tpl.php for specific region
I am new to drupal 7 and really struggling with this one:

http://drupal.org/node/104319

I have a region called navigation

in my .info `regions[navigation] = Navigation bar`

for this region I want to use a custom tpl.php file. I have tried

```
  block-navigation.tpl.php

```

like in the example, and put it at the theme root and in the templates folder with no luck. I've cleared the cache and insured that a standard working block.tpl.php is in place. To no avail.

ANSWER:

I needed BOTH a region--navigation.tpl.php AND a block--navigation.tpl.php with a double `--` both times.

**1000 views** on this question earned me the popular question badge. But you guys can't find it in your heart to **upvote** it more than **1** time. Laaaammmmmeeee....

# Answer
To use a custom tpl.php file for "navigation" region, you should use region--navigation.tpl.php
> 4 votes

---
Tags: 7, blocks, theming
---


title: Metatags for Views page?

text:
# Question
Title: Metatags for Views page?
> **Possible Duplicate:**
> Meta tags on Views in Drupal 7

Tried metatags module, it is great, but can only set meta for Content, Tax, Front, etc, not for Views.

How to set metatags info for Views page? programmatically or by module

Thanks.

# Answer
> 1 votes
You can use Meta tags quick The Meta tags quick module allows you to specify Meta tags based on path for your views

Interesting article on Meta tag generation here

---
Tags: views, meta-tags
---


# Question
Title: In which tables and columns data is stored for Story and Page?
I am using Drupal 6.25 with Postgres 8.4. I want to create stories from backend. To which tables and columns should I insert values so that one story is shown on my drupal site?

# Answer
This is Drupal way to insert a new node from code.

```
<?php
// add node properties
$newNode = (object) NULL;
$newNode->type = '{NODE_TYPE}';
$newNode->title = '{NODE_TITLE}'
$newNode->uid = {USER_ID};
$newNode->created = strtotime("now");
$newNode->changed = strtotime("now");
$newNode->status = 1;
$newNode->comment = 0;
$newNode->promote = 0;
$newNode->moderate = 0;
$newNode->sticky = 0;

// add CCK field data
$newNode->field_{YOUR_CUSTOM_FIELD_1}[0]['value'] = '{DATA_1}';
$newNode->field_{YOUR_CUSTOM_FIELD_2}[0]['value'] = '{DATA_2}';

// save node
node_save($newNode);
?>

```

Best of luck with Drupal.

You will need to refer Creating Drupal 7.x modules
> 3 votes

---
Tags: database
---


# Question
Title: List all the taxonomy terms in a particular vocabulary in Drupal 6.
My task is to display all the terms in a particular vocabulary. It should also display all the sub-terms along with their parent terms.

For example the taxonomy page for a particular vocabulary is like

Term 1

Term 2

Term 3

```
Sub-term 1 of Term 3

Sub-term 2 of Term 3

Sub-term 3 of Term 3

```

Term 4

Term 5

Term 6

Sub term 1 of Term 6

Sub term 2 of Term 6

I need an exact display of taxonomy terms as above (without edit, just to list all the terms in a tree order). Is it possible with views or whether I have to do coding? I tried this thing with views by giving term- weight filter, taxonomy parent term relationships etc, received duplicate values and found it very complex.

# Answer
> 2 votes
You can use `taxonomy_get_tree()`

**Parameters**

**$vid:** Which vocabulary to generate the tree for.

**$parent:** The term ID under which to generate the tree. If 0, generate the tree for the entire vocabulary.

**$depth:** Internal use only. Now deprecated and isn't used. It is left here only because of compatibility issues.

**$max\_depth:** The number of levels of the tree to return. Leave NULL to return all levels.

API here

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


# Question
Title: How to display the table select query values in the same form in drupal 7?
Just newly working on Drupal 7. Using Form API I created a text field with one submit button. I need to pass the text field's value in the select query as a parameter. I need to output the result set of the select query in table layout. Please help me out by providing a set of codes.

# Answer
This is actually very easily done out of the box with form-api, you just have to know how to use it. You have to read up on drupal 7 forms, especially the validate and submit functions/hooks. A quick and dirty example to output form values in submit function (called after function form\_\*_validate() hook) is shown below.

```
function form_example_tutorial_7_submit($form, &$form_state) {
  drupal_set_message(t('The form has been submitted. name="@first @last", year of birth=@year_of_birth',
    array('@first' => $form_state['values']['first'], '@last' => $form_state['values']['last'], '@year_of_birth' => $form_state['values']['year_of_birth'])));
}

```

Of course, you can also show messages like this in the validation step. You would need to change above code to use whatever variables you want shown.

Tons of very helpful form api code examples here.

If videos are more your thing, these explains the basic basics ok.

Cheers!
> 1 votes

---
Tags: forms, database
---


title: populate taxonomy from another taxonomy

text:
# Question
Title: populate taxonomy from another taxonomy
I have 2 exposed filters in a search page "drop down lists", I want to populate the second exposed filer "taxonomy" from the first one:

example vehicle {car, plane, ship} and the second should be {BMW, Honda, etc} only if vehicle car is selected in the first drop down list.
thanks

# Answer
> 0 votes
Found the solution for this, I used Hierarchical Select and it worked like a charm.

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


title: How to find elements in a render array

text:
# Question
Title: How to find elements in a render array
I just spent a lot of time finding an element in a render array. I usually use `dpm()` to print the array, and then expand the options until I find what I'm looking for.

On larger arrays that's cumbersome. When I use `print_r()`, I can do a text search, but then it's hard to see the structure of the array and find the path to the element.

What other methods can you suggest?

# Answer
> 9 votes
There is extension module for Devel: Search Krumo. It uses Javascript to find text in Krumo/dpm messages and open array in those places.
Looks like this:

## Update

After 22 Apr 2012 you should use `sdpm()` function to see search box.

# Answer
> 5 votes
One of the big problems with render arrays is that there are often a bunch of read-only copies of the information that you're looking for. If you want to actually *change* the render output, you have to find the right one. I usually use dpm(), and then view page source and search through the output there, flipping back and forth between the two displays until I find what I need.

If you want to dump the contents of a render array for a given path to the terminal (e.g. to pass it through grep), you could do something like this:

```
drush ev '$router_item=menu_get_item("node/7"); require_once(DRUPAL_ROOT .
"/" . $router_item["include_file"]);
$render_array=call_user_func_array($router_item["page_callback"],
$router_item["page_arguments"]); print_r($render_array);'

```

You could also just 'view page source' in your browser and use the clipboard, of course, but the above might be the start of a Drush command to view render arrays.

**Update:** I found a really good article on this subject: The Scary Render Array -- probably the best treatment of render arrays I have seen so far. I should have also mentioned the devel\_themer module upfront; it does a good job at "zooming in" on the section of the render array you are interested in.

---
Tags: theming
---


# Question
Title: Error when moving from local host to live server
I am getting the following error after deploying a website on server.

> PDOException: SQLSTATE\[42000\]: Syntax error or access violation: 1231 Variable 'sql\_mode' can't be set to the value of 'NO\_AUTO\_CREATE\_USER' in lock\_may\_be\_available() (line 167 of /httpdocs/includes/lock.inc).

Basically, I created a Drupal website on local server. After finishing it, I generated the database script and ran it on the live server using phpMyAdmin. Then, I uploaded the files on server and changed the *settings.php* file for the database credentials.

Once I tried to access the website, I got that error.

Updating phpMyAdmin would fix the issue, but I am running a dedicated server and I don't want to update phpMyAdmin. I am looking for a work-around.

# Answer
When creating database exports, the tables are usually locked to ensure that there are no attempts to access or change data within the tables while they are being exported and imported. Those locks will usually be released at the end of the import process. That obviously did not happen for your database.

Most likely your database import in phpmyadmin timed out and did not complete the import process. Check the tables available in phpmyadmin and see if there are the same number of tables as on your local server. If the data appears to be properly intact on the production server, then you will need to manually unlock the tables.
> 2 votes

# Answer
The best way I've found to export a local Drupal database and reimport it into a live database is to use Drush on the local server by entering the following code in the root of the installation you want to export.

```
drush sql-dump --gzip --result-file=pathto/yourdb.sql

```

I suggest making that path in the code above relative to the root of your Drupal install. Upload all the files to your server, then in the root of the Drupal install on the server use MYSQL to import the database.

```
gzip -d yourdb.sql.gz
mysql -h "your host" -u "username" -p "db name" < pathto/yourdb.sql

```

make sure to remove the quotes in the code above, and also you can remove the "-h your host" section if your mysql is hosted on localhost.

After that just make sure your settings.php file has the right configuration and you should be set. I've found using MYSQL to import databases is generally more reliable than phpMyAdmin, especially when DB files become large. Let me know if that works for you.
> 2 votes

---
Tags: deployment
---


# Question
Title: Are there alternative ways to creating themes in Drupal 7?
Specifically I'm looking for something as simple as having the HTML/CSS/JS theme ready as static files and then just filling in the dynamic parts using PHP/Drupal. This is more or less how WordPress and other CMSs do it.

Are there any modules or other theming engines that do this?

Thank you.

# Answer
The short answer is "no." At least not at the level you are looking for.

A .info file is always required for a Drupal theme, this is how Drupal recognizes that the theme exists. Adding CSS and JS within this file is important because of CSS/JS caching which is important for site performance and other reasons. You should read the Drupal Theming Guide for more information, if you haven't.

There is, however, no requirement for template.php in a theme. If you do not want to utilize RDF on your site, you can disable the core RDF module.

There are other Theme Engines for Drupal, but they have all been abandoned in favor of PHPTemplate in Drupal 7. There are also a number of contributed base themes for Drupal, which are helpful for getting started with theming more quickly.

Unfortunately, the theming approach of Drupal is often a shock for users coming from other CMSes, especially Wordpress. The inherit flexibility and functional power in (and legacy of) Drupal core necessitates an extremely complex theming layer. You are not going to find a Wordpress-like experience in Drupal 7.
> 2 votes

# Answer
You can try creating sub-themes by following the procedure given here. Modifying is easier then creating a new theme from scratch(my experience).
> 1 votes

---
Tags: theming
---


# Question
Title: How to use jquery to show divs based on select box?
This is a follow on to my previous question. I didn't want to make ajax calls for this and instead loaded all the term field text with views\_get\_view\_result(). Then I looped over the results and created divs within the node add/edit form.

I know have for every term option in the select box a hidden div:

```
<div id=help123 style="visibility:hidden;">help text for termid 123</div>

```

I added a

```
scripts[] = custom.js

```

to my module.info file with:

```
(function($){
$("#edit-field-disc-topic-und").click(function(){
    var option = document.getElementById("edit-field-disc-topic-und").value;
    document.getElementById(option).style.visibility ="visible";
})
})(jQuery);

```

Should I post this on Stackoverflow instead?

# Answer
you ommited the drupal.behavior, that s probably why it doesnt do anything. And i would suggest working with classes instead changing style. In your css you create a style with visibility:hidden, apply it to each element and then remove it on click. (and add it again once you clicked on something else ...)

document.getElementById doesnt make much sense there ... you can write it better like this :

```
(function($){
Drupal.behaviors.taxdescGetDesc = {
  attach: function (context) {
    $("").click(function(event)){
    option = $(event.currentTarget).val();
    $('#'+option).removeClass("hidden");
  }
}

```
> 1 votes

---
Tags: 7, javascript
---


# Question
Title: Client-side validation module, fields required only if certain values in other fields are set
We've built a form using WebForms and are using the Client Side Validation module for AJAX/jQuery validation.

One field on the form needs to only be mandatory if a certain country is selected in the drop down.

We've got as far as being able to customise the styling (the jQuery side of things) to hide/show the required field notice, but we can't seem to dynamically alter the validation rules that the module is working to.

How can we achieve this?

# Answer
You can always create a custom rule for Client Side Validation, check clientside\_validation.api.js for instructions, but you'll need some coding experience, otherwise feel free to open a feature request and we'll see what we can do.
> 1 votes

---
Tags: webforms, forms
---


# Question
Title: Creation + Drag and drop of groups of fields with CCK
I have an image field with unlimited number of values but they relate to each-others in sets like this:

```
1a
1b
1c
2a
2b
3a
3b
3c
3d

```

My goal would be to create a text field before the first image of each set and to be able to drag and drop each set without effecting the order inside each set.

It would look like this:

```
Header for 3
3a
3b
3c
3d
Header for 1
1a
1b
1c
Header for 2
2a
2b

```

Is there a module that provides a similar functionality? Unfortunately multi-groups doesn't cut it for me because it just pairs the text field with the image field...

# Answer
> 1 votes
Take a look at field collection module.

You could create a field collection with a text field (Number of values: 1) and an image field (Number of values: Unlimited). Then you should set your field collection field also to unlimited values so you can add as many sets you want.

Nevertheless field collection is a little buggy, but give a try first.

---
Tags: entities, media
---


# Question
Title: Get User ID (not current) in a overridden views.tpl.php
I'm using Drupal 7. I'm creating a view based on profile. It will show a list of all the people. Now I'm overriding the file views-view-unformatted--MYVIEW-page.tpl.php and I would like to add in the class of the row the ID of that user. If I write

```
global $users;
$user->uid;

```

of course it's giving me the id of the current user and not the uid of that profile.

I would like to create something like this: FIRST EXAMPLE:

```
    <?php
    $this_uid = I NEED THIS TOKEN;
    ?>
<ul>
    <?php foreach ($rows as $id => $row): ?>
      <li class="<?php print $classes_array[$id]; print " ".$this_uid;?>">
        <?php print $row; ?>
      </li>
    <?php endforeach; ?>
</ul>

```

I could create a custom text field in the view a put all the field inside the `<li>` tag like: SECOND EXAMPLE:

```
<li class="[user]">[name] [gender]</li>

```

and the file tpl.php will become

```
    <ul>
<?php foreach ($rows as $id => $row): ?>
            <?php print $row; ?>
        <?php endforeach; ?>
</ul>

```

But in this way I will lose the default row classes...

How can i get the first example? Do I need to create a view based on user instead of profile? Or should I use the second example?

Thanks in advance.

# Answer
You should have a `$views` variable available with an array similar to `$rows` called `$view->result[]` that contains the unrendered/raw view results and just as long as you have a field in your output that has the uid in it, you will be able to access it directly here. (It can be a hidden field if you don't want it rendered later on) Put a `drupal_set_message('<pre>' . print_r($view->result, true) . '</pre>');` or its equivalent in your template to take a look at it, but basically you should be able to use something like `$view->result[$id]->FIELDNAME` to access it or any other raw data.
> 1 votes

# Answer
Use views PHP field, set it as hidden, then use PHP to save needed value in this field. After that, views template will be able to get that value.

Make sure you clear cache and rebuild theme registry.
> -1 votes

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


title: How to upload multiple files at once?

text:
# Question
Title: How to upload multiple files at once?
We need to upload multiple files of different types, is there a module that will check for valid mime types and upload only the valid files, (based on site settings, eg: png, doc, jpg, txt) ?

# Answer
clientside\_validation (drupal-6 and drupal-7) performs some additional client-side checks, including checks on uploaded file extensions (but not MIME Types). (And, as @tim.plunkett mentioned in the comments, mimedetect is useful for server-side MIME Type validation, but the file must be uploaded to the server in order to be validated.)

For uploading multiple files, consider the following:

* **swfupload (drupal-6; Flash)**
* plupload (drupal-6 and drupal-7; Flash and several other technologies supported; new/under development)

For uploading multiple **images**, additionally consider these:

* **image\_fupload (drupal-6; uses swfupload above)**
* jifupload (drupal-5 and drupal-6; free; uses Java applet)
* aurigma (drupal-6; software purchase / service subscription required)
> 26 votes

# Answer
We've had excellent luck with Plupload. It bends over backwards to achieve cross-browser compatibility, using Silverlight, Flash, HTML5, and falling back to classic HTML4 'select file' widgets depending on the browser's capabilities.

The Drupal integration module is a bit rough, but we've used it successfully on a number of large projects to populate Image Fields. In Drupal 7, I believe they've pulled most of the UI and turned it into a pure API module that can be used by tools like Media simply to handle the uploading work. If you want to do anything particularly funky, you'll probably have to write a bit of custom code to handle where the upload widget gets displayed, but it's very solid.

We've managed to tie into its internal events to handle quite a bit of post-processing, and checking for MIMEtypes/kicking back validation errors could probably be done without too much tinkering.
> 5 votes

# Answer
Here's my comparison wiki in the Similar Module Review group. http://groups.drupal.org/node/155764

Dumping the content here as it is now...

**Aurigma Mass Uploader for CCK (6.x-2.0)** The Aurigma Uploader for Imagefield module integrates the commercial Aurigma Image Uploader with Drupal. Multiple images are uploaded in a single batch into a multiple imagefield.

**Image FUpload (6.x-3.0-rc2)** Image FUpload (Multiupload) which is an addition to image and CCK's imagefield module, gives the ability to every user who is allowed to upload images by using image module or imagefield module, to upload multiple images with one simple click. All selected images are uploaded via a flash module (swfupload) and are automatically processed.

**Plupload integration (6.x-1.x-dev, 7.x-1.0-beta3)** Provides integration between for the Plupload widget to upload multiple files and Drupal. Plupload is a GPL licensed multiple file uploading tool that can present widgets in Flash, Gears, HTML 5, Silverlight, BrowserPlus, and HTML4 depending on the capabilities of the client computer.

**SWFUpload (6.x-2.0-beta8)** The SWFUpload module for Drupal provides a widget for CCK's Filefield and uses the SWFUpload library to allow multiple file uploads simultaneous.

**jUpload for Imagefield (6.x-1.x-dev)** Have you ever wished you could upload a group of images at once to an imagefield? The jUpload for Imagefield module (jifupload) integrates the JUpload Java applet with the ImageField module for CCK. Multiple images are uploaded in a single batch into an imagefield set for multiple values.

Different approach, same outcome...

**ImageField zip support (6.x-1.0-beta2)** This is a helper module for ImageField. When uploading multiple images for imagefields with multi-values, this module adds the ability to upload multiple images in zip files instead of individually.

**Imagefield Import (5.x-1.5, 6.x-1.10)** Imagefield Import allows users with the proper permissions to import a large number of images into a CCK content type which contains a filefield or an imagefield. The module can grab titles and descriptions using EXIF or IPTC. Note: To use this module you must be able to upload images to your server via FTP, SCP, or other methods.
> 4 votes

# Answer
Another one for images that isn't supported very well but does work is ImageField zip support
> 2 votes

# Answer
If you can put these files into a zip, and you want/have to use core Upload module, you can try Multiple Upload Alone (Drupal 6.x).
> 2 votes

# Answer
**HTML5 Upload** http://drupal.org/sandbox/z7/1348240

> This modules should be regarded a streamlined solution for batch-uploading of images (and other files) for Drupal 7 in modern (HTML5 compliant) browser, nothing more.

Didn't try yet but the code is clear and compact.
> 0 votes

---
Tags: forms, files
---


title: Plus or minus sign using Apache Solr

text:
# Question
Title: Plus or minus sign using Apache Solr
When I enable Apache solr, everything works perfectly fine except for the following scenario.

When I do a keyword search using character *-* (minus symbol), or *+*, I get the error:

> The Apache Solr search engine is not available. Please contact your site administrator.

Do you know why this happens?

# Answer
You need to be using Apache Solr 3.1 and have the edismax plugin enabled to allow for these boolean operator queries. You should see this in your Solr logs as 'an unknown query type' error. This should be an option in the ApacheSolr Drupal module since this patch but if not (or if you're running Apache Solr 1.4.x) you can check out this ticket on the solr forum for instructions on how to patch your solr and solrconfig.xml to allow for edismax queries.
> 1 votes

---
Tags: search
---


# Question
Title: Why do I have to add main-menu under features[] in the theme info file?
I have seen other themes that just define regions and then use drupals theme() function in the **page.tpl.php** to print the Main menu wherever the developer pleases.

This was not the case for me, and I spent a lot of time figuring out that for some reason I had to both add '**features\[\] = main\_menu**' into the theme .info file, as well as going to '*admin/appearance/settings/themename*' and enable the feature before it will display.

I'm having trouble understanding why this is the case, and hope someone can elucidate or at least point me towards some enlightening documentation. Thanks.

# Answer
The `features` elements in the .info file are used to add or suppress Drupal core/global theme settings. If you add *any* `features` options to your .info file, you must add *all* of the options you wish to have available to your theme. All of the options are included by default if no `features` options are added to the theme's .info file.

If you want to set the default setting for any of these features to your theme's .info file, you can use the `setting` entry. For example, if you wanted to default the "main\_menu" option to be on, you would add this to .info:

```
setting[toggle_main_menu] = 1

```

More information on all of these topics can be found in the drupal.org Theming Guide
> 2 votes

---
Tags: .info
---


# Question
Title: How to interlace ouput of nodes two content types in views
I have nodes of two different content types and want to output them interlacing in a view. So nodes of type A are on odd places and nodes of type B on even ones.

Is there a straight-forward way to do this?

# Answer
You could create a view that outputs the two node types and then use `hook_views_pre_render()` to sort, shuffle, or arrange the `$view->result` array any way you wanted. Then when it is rendered in the next steps, it would be printed however you wanted. You would hook into this like:

```
function YOURMODULE_views_pre_render(&$view) {

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

    // do whatever you want with $view->result[]

  }

}

```

MORE INFO: `$view->result[]` is an array of "rows" basically, eg `$view->result[0]` contains all the raw data that makes up the first row, `$view->result[1]` is the second, etc.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Ubercart - how to alter button texts via hook_form_alter()?
I am attempting to change the language of the buttons on the product and cart forms.

All is working well on product form but when the same is implemented on the cart page it stops submitting properly. Button values change but they stop working.

```
<?php

/**
**Custom Module for hook_form_alter
*/

function MYMODULE_form_alter(&$form, &$form_state, $form_id){

    if ($form_id == uc_product_add_to_cart_form_1){
            $form['submit']['#value'] = 'Register';
    }

    if ($form_id == uc_cart_view_form){
        //dsm($form);
        $form['continue_shopping']['#value'] = 'Back';
        $form['update']['#value'] = 'Update';
        $form['checkout']['#value'] = 'Continue';
    }
}
?>

```

Any help would be much appreciated.

# Answer
> 2 votes
There is a thread about this problem on drupal.org, and there is even a patch to solve this problem:
http://drupal.org/node/1170364

**A quick explanation why the button text altering breaks up normal behavior** (which is a bit "funny"):
Let's take a look at uc\_cart\_view\_form\_submit()'s code, mainly the part below the comment *"// Specify the appropriate redirect based on the button used to submit"*. You can see that there's a switch block where the **text** of the clicked button is inspected (`$form_state['clicked_button']['#value']`), which is a very bad practice: the logic depends on what text this button is set to display. This means if you simply change the text of the buttons programatically, the appropriate redirections won't work anymore! To be honest, I don't really understand why this part of Ubercart was developed this way.

I just solved it with a custom module **without patching the Ubercart core**, and it works after some tests, you can find the code below.

About changing the "***Continue shopping***" text:

* the "*Continue shopping*" text can be easily changed on the `/admin/store/settings/cart/edit/basic` page, and as it's a multilingual variable, THIS is the appropriate way of changing it - you can do this by typing another name in the "`Custom continue shopping link text:`" textfield, and saving the changes. You can see a screenshot of it here:
* BUT I also show you how to change it programatically (you can see it below in the code - you have to set the `$set_continue_shopping_type_programatically` to `TRUE` to try it - but I would suggest using the first method)
* I also have to mention that the "*Continue shopping*" is a **link** (not a button) in *Ubercart 6.x-2.7* **by default** \- so if you would like to change its value programatically, and it is set to be displayed as a *"Text link"*, its value has to be a link markup (not a regular string, because this way it won't work as expected) - you can use Drupal's l() function to create an appropriate link. But you can also set it to be displayed as a button, this way you have to use a plain text to modify its original text (and it turned out from your comment that you've already set it to be displayed as a button).

Here is the tested and working code:

```
// ...

// you should change MYMODULE to your module's name

/**
 * Implementation of hook_form_alter()
 * @see http://api.drupal.org/api/drupal/developer%21hooks%21core.php/function/hook_form_alter/6
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id)
{

    // for testing, you can output the appropriate $form_id variable
    // to detect the form id(s) of the actual form(s) printed to the page
    // e.g. by using Devel module: http://drupal.org/project/devel
    /*
    if(function_exists('dsm'){
        dsm('Actual $form_id:');
        dsm($form_id);
    }
    */

    // You can just simply toggle overriding the default cart button values
    // with setting the variable below to "TRUE" or "FALSE" (without the quotes)
    // (this can be good for testing!)
    $modify_default_ubercart_buttons = TRUE;

    switch ($form_id) {
        // CHANGE IT TO THE APPROPRIATE $form_id!!!
        case 'uc_product_add_to_cart_form_1':
            // dsm($form);
            if($modify_default_ubercart_buttons){
                $form['submit']['#value'] = 'Register';
            }
            break;

        case 'uc_cart_view_form':
            // dsm($form);

            if ($modify_default_ubercart_buttons) {
                $form['#submit'][] = 'testModule_form_alter_uc_cart_view_form_submit';

                // 1.) changing the "Update cart" button's text

                $form['update']['#value'] = 'Update';
                // if you modify the "#name" attribute, you also have to modify it in testModule_form_alter_uc_cart_view_form_submit()
                $form['update']['#name']  = 'update-cart';

                // 2.) changing the "Checkout" button's text

                $form['checkout']['#value'] = 'Continue';
                // if you modify the "#name" attribute, you also have to modify it in testModule_form_alter_uc_cart_view_form_submit()
                $form['checkout']['#name']  = 'cart-checkout';

                // IMPORTANT!!!
                // You should rather set the "Continue shopping element display" on the "/admin/store/settings/cart/edit/basic" page!
                // This is a multilingual variable, so setting it on the appropriate admin page is the best solution.
                // The code below is just a sample for setting it programatically!
                $set_continue_shopping_type_programatically = FALSE;

                if ($set_continue_shopping_type_programatically) {
                    $uc_continue_shopping_type = variable_get(uc_continue_shopping_type, 'link');

                    $continue_shopping_link_text = 'Back';
                    // $continue_shopping_link_path   = uc_cart_continue_shopping_url();
                    if ($uc_continue_shopping_type == 'link') {
                        $continue_shopping_link_markup       = l($continue_shopping_link_text, $continue_shopping_link_path);
                        $form['continue_shopping']['#value'] = $continue_shopping_link_markup;
                    } else {
                        $form['continue_shopping']['#value'] = $continue_shopping_link_text;
                        // the default "#name" attribute equals to "op" by default
                        // we change it to the desired button text to make it clear
                        $form['continue_shopping']['#name']  = $continue_shopping_link_text;
                    }
                }
            }

            // ...

            break;
    }
}
/**
 * Ubercart submit function needed because of button text altering
 * @see http://drupal.org/node/1170364
 */
function MYMODULE_form_alter_uc_cart_view_form_submit($form, &$form_state)
{

    // Specify the appropriate redirect based on the button used to submit.
    switch ($form_state['clicked_button']['#name']) {
        // Update cart button.
        case 'update-cart':
            // No redirect.  Just display a message and preserve the last URL.
            drupal_set_message(t('Your cart has been updated.'));
            break;

        // Checkout button.
        case 'cart-checkout':
            $form_state['redirect'] = variable_get('uc_checkout_enabled', TRUE) ? 'cart/checkout' : 'cart';
            break;
    }
}

// ...

```

---

I also posted some screenshots about the button text altering:

**Modifying "Add to cart" button's text:**

BEFORE:

AFTER:

---

**Modifying "Shopping cart" page's buttons:**

BEFORE:

AFTER (*"Continue shopping"* as a *"Text link"*):

AFTER (*"Continue shopping"* as a *"Button"*):

# Answer
> 0 votes
Try this

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id){

    if ($form_id == 'uc_product_add_to_cart_form_1'){
            $form['submit']['#value'] = 'Register';
    }

    if ($form_id == 'uc_cart_view_form'){
        //dsm($form);
        $form['continue_shopping']['#value'] = 'Back';
        $form['update']['#value'] = 'Update';
        $form['checkout']['#value'] = 'Continue';
    }
}

```

Thanks Sk8erPeter

---
Tags: 6, forms, hooks, ubercart
---


# Question
Title: How much RAM does a basic installation need?
I am looking to downgrade from a dedicated to a VPS server (several, to spread it out) and was wondering if 512MB will do? I have Boost with all core caching enabled, and mostly anonymous traffic.

# Answer
> 10 votes
It depends on a number of factors:

* **What contrib modules are you using?** The bare minimum Drupal needs to run is 32 MB, but that truly is the *bare minimum*. Contrib modules and doing anything moderately complex with code will increase your memory requirements. While you're using Boost which is great, you still need to generate the cache, which requires RAM. But unless you're doing something really intensive, I've found you can generally be fine with 128 MB for PHP.
* **What web server are you running, and what type of load are you expecting?** If you're running Apache with its default settings, it'll eat up a lot of memory: generally 128 MB or more. Optimizing your Apache environment or switching to a less memory-intensive server will free up more memory, but it's up to you if that's something that's possible.
* **Are you running your database on the same server?** MySQL has its own memory requirements, and you'll find it takes up the bulk of a shared server's memory. You'll bump up to the memory limit on a small VPS pretty fast, especially if you're running InnoDB or have a large site. The general recommendation is somewhere between 70-80% of RAM should be allocated to MySQL running InnoDB, which is ~360 MB on a 512 MB instance: not a lot of room for PHP and Apache (or anything else).
* **Are you running any other service on the same server?** If you're running Memecached, Varnish, APC, Jenkins, or any other service common to a Drupal environment, they all take up memory, and in many cases, a *lot* of memory.

If you're running a small Drupal site with an optimized Apache configuration, database on its own server, and no other service, I've found 256 MB to be the bare minimum. 512 MB is okay, not great, if you need to run the database on the same server and want to enable APC, but you still be looking for ways to save RAM.

I personally run the database, caching, and continuous integration services on other servers and use a Micro EC2 instance (613 MB RAM) for most Drupal installations I do. But I'll bump that up to a Small instance (1.7 GB, overkill, but there's nothing in between) if the site's going to get a lot of traffic.

---
Tags: 7, performance
---


# Question
Title: Permanently disable Auto Preview in views?
Is it possible to make views stop defaulting to Auto Preview on? It's really slowing down my workflow.

# Answer
As seems to always be the case, I stumbled upon the views settings page after posting the question: On admin/structure/views/settings unselect "Automatically update preview on changes."
> 14 votes

---
Tags: 7, views
---


title: Load a node content programmatically

text:
# Question
Title: Load a node content programmatically
How can i load the user page (profile) in a block or in the body of a another page?
I tried to put a block in the user page but does not work. Any ideas?
Thanks.

# Answer
You can print the user profile using:

`<?php print render($user_profile); ?>`.

You can get specific user information by

`<?php print render($user_profile['user_picture']); ?>`

```
<?php print render($user_profile['summary']); ?>

```

Hope this helps.
> 1 votes

---
Tags: 7, nodes
---


title: How to expose Taxonomy term in drupal 7

text:
# Question
Title: How to expose Taxonomy term in drupal 7
can any one help me how to expose the taxonomy term filter in view in drupal 7. I have created a view with

```
   Fields:

     1. Title

     2. Body

    FILTER CRITERIA:

     Has taxonomy terms (with depth)

```

when i expose this filter it is not getting exposed.

can anyone help me how to expose the taxonomy term field.I need to see the content get filtered based on the taxonomy term.

# Answer
> 1 votes
When you select the filter 'Has taxonomy terms (with depth)' under your 'Filter Criteria' section, make sure you select the correct vocabulary on the first screen of your setup. There is a section for you to determine which vocabulary's terms you are trying to select from.

On the second screen, make sure you check the 'Expose this filter to visitors, to allow them to change it' checkbox. It is actually **unchecked** by default.

It should then show up at the top of your view in the preview window.

# Answer
> 0 votes
Try exposing the Tag field you have in your node, so if the tags you want to sort on are in a field called 'Taggies' you would expose that field

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


# Question
Title: Show fields on webform based on a value in the session
I want to use a webform to do a feedback form but want it to act on data provided by the user. That is, if the user has answered a question about location which is stored in a session, then I want to show a webform field, otherwise don't show the field at all. Any ideas on if this is possible and how to do it in webform?

Thanks.

# Answer
> 1 votes
try somewhere in your webform-form-\[NID\].tpl.php

```
hide($form['submitted']['your-field-name']);
if($_SESSION['your_value'] == 'what it should be') {
   show($form['submitted']['your-field-name']);
}

```

---
Tags: 7, webforms
---


# Question
Title: Manager of groups stopped appearing as member and groups stopped appearing in her "my groups" list
I'm utterly befuddled.

I'm in the process of building a site (D7) that is group-based. I have a few users on the site right now as I develop it and try to work out bugs. One of my users had created several groups, joined a couple others, and everything worked fine until sometime between yesterday and today. Suddenly, the groups she started (and is therefore manager of) stopped showing in her list of groups she is a member of. At the same time, she lost non-manager memberships of all groups but one, and then whenever she added a group it removed the prior one.

I had (and continue to have) the number of groups someone can join set to unlimited. I've also gotten it so she can be a member of more than one group again. However, groups she's a manager of still don't appear on her list, and her name doesn't appear on the members list on those group pages. When she views the groups she's manager of, it does say "You are the group manager." That relationship doesn't seem to appear anywhere else, though.

To further add to the confusion, on my non-admin account on the site I am manager on one group and member of another. I never lost visibility of my group I manage, and it never lost visibility of me. This seems to have affected only her account.

I'm at a loss to figure out what happened and how to solve it. I did back up the db yesterday morning (before whatever broke this happened), although I've had 2 new users and have made other adjustments since then. Can I compare her uid in the two databases and manually correct differences? Where would I look to set elements of group membership/management? Is there an easier way to do this just through Drupal admin interface?

# Answer
Apparently the user was still manager of her groups, but was no longer registered as a member. I was able to use the Masquerade module to assume her identity, go to the appropriate node/%/group menus for each one she was manager of and give her membership again. Everything seems to be back in line after that. My guess is it was caused by overzealous use of an alternate link/rule-set I was experimenting with to manage group enrollments/drops. I've now disabled that until I figure out how to get to function properly.
> 0 votes

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


# Question
Title: SimpleTest: How to make multiple Ajax posts and then save the data?
I have a form with AJAX buttons that add items to a list. To SimpleTest the form, I need to make the AJAX post:

```
$this->drupalPostAJAX(NULL, $edit, array('op' => 'Add Item Button'));

```

...then POST the resulting $edit object with the Save button.

```
$this->drupalPost('admin/structure/fms_report/create', $edit, t('Save'));

```

My question is, how do I get the resulting $edit object after the first AJAX POST happens?

# Answer
On subsequent tests of a form that has already been loaded and posted, this call will submit the form to the same URL with the field values resulting from any previous activity:

```
$this->drupalPost(NULL, NULL, t('Save'));

```

The $edit argument is only to submit new field values. And, passing NULL for $path uses the currently loaded page. So, to test my AJAX button that adds items to the form:

```
$this->drupalGet('path/to/my/form');
$this->drupalPostAJAX(NULL, NULL, array('op' => 'Add Item Button'));
$this->drupalPostAJAX(NULL, NULL, array('op' => 'Add Item Button'));
$this->drupalPost(NULL, NULL, t('Save'));

```

I was able to verify after this that two items had been added to the form as expected.
> 3 votes

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


# Question
Title: Hide publishing options in hook_form_alter without unpublishing node?
I'm trying to create a very slimmed down node edit page for a content type. One of the things I'm doing is hiding the additional\_settings section with `#access = false`.

This is what I'm using:

```
$form['additional_settings']['#access'] = FALSE;
$form['options']['status']['#default_value'] = TRUE;

```

With `#access = false`, when I save the node after editing, it set to unpublished.

I've tried using `$form_state['values']['status'] = TRUE;` in a form submission handler, but that doesn't help.

# Answer
You could just convert the element to a `value` type, that way it will be hidden from the form display but will be passed through to the submit handler as normal:

```
$form['options']['status'] = array(
  '#type' => 'value',
  '#value' => 1
);

```

You can do the same thing for the rest of the elements in that fieldset, then set the fieldset itself to a `container` type and remove the title:

```
$form['options']['#type'] = 'container';
$form['options']['#title'] = '';

```
> 10 votes

---
Tags: 7, forms
---


# Question
Title: Getting .info file not found in my custom module, even though it does contain an .info file
I am trying to install my custom module, but the error I get is:

> modulename.tar.gz does not contain any .info files.

My module tar.gz file does indeed contain a .info file. I have installed other modules on the server, so I shouldn't have any permission issues.

The following is the content of the .info file.

```
    name = Module Name
    description = Initialization module for hl
    package = My modules
    core = 7.x
    files[] = modulename.module
    files[] = modulename.install
    files[] = modulename.inc
    files[] = includes/mydrupalusers.php

```

# Answer
Mystery solved.

I traced back to the update\_manager\_install\_form\_submit() function in update.manager.inc.

When the file is uploaded, it is placed in the temp directory. Drupal then creates a temp directory to extract the file into, using a unique directory name. After the extraction, Drupal can't determine the module name any more, so it depends on the directory name in the archive. They commented on this in the code:

```
// Unfortunately, we can only use the directory name to determine the project
// name. Some archivers list the first file as the directory (i.e., MODULE/)
// and others list an actual file (i.e., MODULE/README.TXT).

```

I did not have my files tar'd in a directory. So, I created a directory named after my module, moved the files into the directory, tar'd it up, and all is well.

### Before

* modulename.install
* modulename.module

### After

* modulename/modulename.install
* modulename/modulename.module
> 2 votes

# Answer
Have you manually checked the .info file to see if its well-formed?

An info file must have at the very least a core version and project name:

```
core = 7.x
name = My Module

```
> 1 votes

# Answer
The fact that your module is named in the error message with a ".tar.gz" extension suggests that something unusual is happening. Either you have not extracted the tarball after moving to your server, or the module has been extracted and the module directory is literally named 'modulename.tar.gz'.

I would first suggest checking to see if the archive has been extracted. If not, check the names of the module directory and .info file. These names should match exactly, otherwise Drupal will not recognize the .info file as belonging to the module.
> 0 votes

---
Tags: .info
---


# Question
Title: What is the best way to add the latest version of jQuery to a theme?
This is just a simple question I have. I'm most interested in seeing what others are doing to use the latest version of jQuery in themes.

The reason for this is that some of the best jQuery plugins I use require much later versions of jQuery than what Drupal comes with.

I have tried the update jquery module but it is not as good for Drupal 6 sites.

Is there another way outside of adding your own version of jQuery. Then once you have it finding and replacing `jQuery` with something like `myQuery` and sticking `myQuery.noConflict()` at the end? And then once this is done rewriting plugins to work with `myQuery`?

# Answer
> 3 votes
In my opinion the best solution is to replace drupal jQuery with the latest jQuery only on the pages where you really need it. If you go on with newest jQuery many of drupal out of the box functionality will be broken.

You can remove native jquery like in the code snippet below only on certain pages that meet your conditions:

```
function MYTHEME_preprocess_page(&$variables, $arg, $delta) {
  if(YOUR CONDITION HERE) {
    $scripts = drupal_add_js();
    unset($scripts['core']['PATH TO DRUPAL JQUERY']);
    $variables['scripts'] = drupal_get_js('header', $scripts);
  }
}

```

to add your newest jquery file you can use drupal\_add\_js('path to yor newest jquery') function.

# Answer
> 0 votes
This page http://drupal.org/node/1058168 should answer all your questions. Although Alex has provided probably the best option for Drupal 6 sites.

In Drupal 7, using hook\_js\_alter() with a separate admin theme is what I would do.

---
Tags: 6, javascript
---