title: Views 3 vertical reading list

text:
# Question
Title: Views 3 vertical reading list
When displaying a view of all the terms on my site in asc order, they read from A-z down. Apply a grid-2 to each row, and they read as so:

```
A B C D E F G
H I J K L M N
O P Q R S T U

```

This is difficult reading in my opinion. I would like them to read as so:

```
A D G J M
B E H K N
C F I L O

```

Is it possible to achieve a vertical list like this?

# Answer
> 2 votes
Could you try changing the ordering for the grid to be vertical and not horizontal. I am assuming that the you are using a grid as the format for displaying your data in the view.

---
Tags: 7, views
---


title: how to remove fieldset from date input

text:
# Question
Title: how to remove fieldset from date input
I set up a site in drupal, and I need to show the fields of date type in the same way as other fields. the problem is that those fields are inside a fieldset.

I'm try the solution code karate, buts it only changes the fieldset to a label.

What I want is showing those fields outside a fieldset, stay equal to the remaining fields.

I am using the following code.

```
/**
 * Remove fieldset from date inputs
 */
function mytheme_date_combo($variables) {
    dd($variables);
    return theme('form_element', $variables);
}

```

# Answer
Well you try this way

`hook_form_alter`

> Perform alterations before a form is rendered.
>
> One popular use of this hook is to add form elements to the node form. When altering a node form, the node object can be accessed at $form\['#node'\].

This is the idea

```
<?php
function example_form_alter(&$form, &$form_state, $form_id) {
  // If Devel Installed
  dsm($form_id);  // print form ID to messages
  dsm($form);  // pretty print array using Krumo to messages
  // If no Devel
  print $form_id;
  // 1. Find the From ID of the Form
  // 2. Check the Form Structure and Remove the Field Set.
}
?>

```

Here is Form API Reference
> 2 votes

# Answer
I used a patch from an issue queue in drupal to sort me out on that one. I should say it works well for me. You can find it here
> 3 votes

---
Tags: entities, datetime
---


# Question
Title: Filter view based on several user profile fields (D7)
I’m trying to apply automatically several filters to a view based on the corresponding profile fields selected by the current user.

For example, the users can select a favourite color (yellow, blue...) and a favourite food (fruit, meat...). If a user have selected that he likes "yellow" and "fruit", he should see in the view only the nodes that match both criteria (yellow fruits): bananas, lemons...

This is pretty easy to do when there's only 1 field to match (following the process indicated here), but this same process doesn't seem to work for matching several fields (the content field of the view only allows 1 relationship).

I've tried creating relations between relationships (like "chain relationships") and doesn't seem to work, but maybe I'm doing something wrong (I don't have a really deep understanding of how relationships work).

Any ideas? Maybe using the Relation or Entity Reference modules? Or some PHP code?

# Answer
After many days of searching, testing and asking, I've finally found a solution here: http://blog.ampli.fi/filtering-a-drupal-7-view-based-on-multiple-user-profile-fields/#solution
> 0 votes

# Answer
You should try chain relationship, this discussed here, similar problem to yours. Here the answer on similar question on drupal.stackexchange.
> 0 votes

---
Tags: views, entities
---


# Question
Title: How do I block access to forum landing page, forum containers and forum posts?
I need only members to be able to access the forums. I have researched this to death and from what I can tell, I need to have at least three modules to achieve this.

1. Path access to block access to the core forum landing page at /forum (as it is not a node, entity nor view)
2. Forum Access module to block the top level forum containers
3. And Taxonomy Access or something like Node View Permissions to block access to the forum topics posts themselves.

Are you kidding me??? I need three permission modules just to stop anonymous users from looking and using the forums. Am I missing something here?

# Answer
> 4 votes
To control access top level forum containers, forum topics and forum content, you should use the forum\_access module (you mention it for blocking containers, but it can also be used to block access to forum topics and content).

However, after installing this and denying the anonymous user role access to forums, this user still has access to the forum landing page (he or she will see a message that it is necessary to log in to access forums).

If you also need to block access to the core forum landing page, you need to add a small custom module that uses hook\_menu\_alter to set up a custom callback function to check the user id. Since the anonymous user is assigned uid 0, you can use this to only grant users with a uid that is not 0 access to this menu item.

Here is all that is needed, stick this in `noforumforanon.module`:

```
/**
 * Implements hook_menu_alter.
 * Check access for forum menu item.
 */
function noforumforanon_menu_alter(&$items) {
  $items['forum']['access callback'] = '_accesscheck';
}

/**
 * Callback to disallow access for anonymous users.
 */
function _accesscheck(){
  global $user;
  return $user->uid;
}

```

And this in `noforumforanon.info`:

```
name = No Forum for Anonymous
description = Blocks anonymous from accessing the forum landing page.
package = Access control
core = 7.x

```

Put both files in a directory named `noforumforanon` below `site/all/modules`, enable and refresh cache, and the landing page shall be gone for anonymous.

---
Tags: users, nodes
---


title: Missing "Clean URLs" option

text:
# Question
Title: Missing "Clean URLs" option
I have a new installation of Drupal 7. I was having a problem with administrative overlay URLs having URL encodings in them, which I asked about here. Another user suggested I confirm that I have clean URLs enabled.

When I went to Home » Administration » Configuration » Search and metadata » Cleanr URLs, all I see is this:

> Use URLs like example.com/user instead of example.com/?q=user. If you are directed to a Page not found (404) error after testing for clean URLs, see the online handbook.

The message was followed by the button, "Run the Clean URL test." that seems to do nothing: The browser tells me it's loading something from the site, but the page doesn't change.

I have no options to enable or disable clean URLs.
I'm pretty sure it's disabled, because when I go to website.com/user, I get a 404.

How can I troubleshoot this?

# Answer
This is a known problem in Drupal 7. The "Run the Clean URL test" button does not behave like that page says it does, and this can be very confusing. Please see "Run the clean URL test" UX is broken; basically, what it comes down to is that the logic and UX of that page is broken, but the clean URL system itself (ie. the part in Drupal core that makes clean URLs work) does not contain any (known) bugs.

If you cannot enable clean URLs (you don't see the checkbox to enable it), this means that a test has already been run, it returned a negative result, and you should check your server configuration. See drupal.org - Clean URLs for documentation.

PS. If you can, test the patch from comment #87. This patch will improve the UX on the clean url's page, but it will not solve problems with an incompatible server configuration.
> 11 votes

# Answer
Is Drupal installed in a subfolder?

I had a similar problem using Drupal on a subfolder. Try this:

1. Open your .htaccess file
2. Look for the following line (line 100 on Drupal 7.4 .htaccess file):
\# RewriteBase /drupal
3. Uncomment this line and change the "/drupal" to match your subfolder. In my case, since Drupal was installed on a folder named "/public\_html/test", I changed so:
RewriteBase /test
4. Try enabling Clean URLs again. You should now see the checkbox "Enable Clean URLs" available.

For me, this solved the problem.
> 5 votes

# Answer
Are you using WAMP? You need to enable the Apache rewrite\_module through the WAMP interface. When you do you will find the Clean URL's option under Search and Metadata heading of localhost/MYSITE/admin/config
> 4 votes

# Answer
When I ran the clean URLs test, nothing happened.

In order to correct the problem, I went to the directory where Drupal was installed (a subdirectory of my main site), and found the ".htaccess" file; this is a different ".htaccess" file than the one in the root directory of the web server, and it is part of the original install.

The file was named ".htaccess.txt"; I removed the ".txt" extension, then ran the clean URLs test again. It ran successfully and the *Enable clean URLs* check box showed up.
> 2 votes

# Answer
I had this problem in local, and i am using wamp, if you go in the apache directory in your wampserver, you look in "apache modules" and scroll down until you find rewrite\_module, check it and it should work! I hope it will help
> 2 votes

---
Tags: 7, debugging
---


title: Equivalent of _phptemplate_variables()

text:
# Question
Title: Equivalent of _phptemplate_variables()
There is a function in Drupal 5 (`_phptemplate_variables()`) that has been deprecated in Drupal 6. Is there a similar function in Drupal 6?

# Answer
> 4 votes
well, i'm not totally sure what you mean, but according to the title of the post, you want a redirect function ?

something like the drupal\_goto(); function?

http://api.drupal.org/api/drupal/includes--common.inc/function/drupal\_goto/6

# Answer
> 4 votes
`_phptemplate_variables` in D5 have been changed into multiple functions.

The Drupal preprocess functions have changed from Drupal 5 -\> Drupal 6, to make them hook based. So instead of having a single function that could be invoked for different hooks, Drupal 6 uses the naming system similar to how hooks is used in modules.

This is described in detail on Drupal.org: Converting 5.x themes to 6.x

# Answer
> 2 votes
`_phptemplate_variables()` is not a function that has been deprecated. It is simply a private function that is not used anymore.

Drupal 5 PHPTemplate engine looked for a function with that name to alter the variables used in a template.

```
function _phptemplate_callback($hook, $variables = array(), $suggestions = array()) {
  global $theme_engine;

  $variables = array_merge($variables, _phptemplate_default_variables($hook, $variables));

  // Allow specified variables to be overridden
  $variables_function = '_'. $theme_engine .'_variables';
  if (function_exists($variables_function)) {
    $variables = array_merge($variables, call_user_func($variables_function, $hook, $variables));
    // …
  }
  // …
}

```

What the code for Drupal 6 needs to do is to implement `MODULE_preprocess(&$variables)`, or `MODULE_preprocess_HOOK(&$variables)` (where `HOOK` is `page`, `node`, `comment`, or any of the values defined from a theme or module).

# Answer
> 0 votes
```
function phptemplate_preprocess_page(&$variables) {
  if (isset($variables['node'])) {
    $variables['template_files'][] = 'page-' . str_replace('_', '-', $variables['node']->type);
  }
  return $variables;
}

```

---
Tags: 6
---


# Question
Title: How to create html page via module drupal 7
I am new in Drupal. I have created a form which saves the values to custom table how ever I want to display those items in a tabular format. Does any one know how to create a custom page where I can display those items.

This is what I tried: in module file

```
<?php $menu_items['user/campaigns/new_campaign'] = array(
        'title' => 'Campaigns',
        'type'=> MENU_CALLBACK,
        'page callback' => 'create_campaign_form2',
        'access arguments' => array('access content'),
        'file' => 'campaigns.create_campaign2.inc',
        'weight' => 1,
    ); ?>

```

in campaigns.create\_campaign2.inc file:

```
<?php function create_campaign_form2()
{
    echo 'Some HTML here';

}
?>

```

But it displays only displays the text, the entire css is removed please let me know what should I do. Sorry if the question is too basic.

# Answer
Use Drupal's Form API. Basically your code will look like this:

```
<?php
    $menu_items['user/campaigns/new_campaign'] = array(
      'title' => 'Campaigns',
      'type'=> MENU_CALLBACK,
      'page callback' => 'drupal_get_form',
      'page arguments' => array('create_campaign_form2');
      'access arguments' => array('access content'),
      'file' => 'campaigns.create_campaign2.inc',
      'weight' => 1,
    );
?>

<?php
   $form = array();
   $form['selected'] = array(
     '#type' => 'select',
     '#title' => t('Selected'),
     '#options' => array(
        0 => t('No'),
        1 => t('Yes'),
     ),
     '#default_value' => 'Maybe',
     '#description' => t('Set this to <em>Yes</em> if you would like this category to be selected by default.'),
   );
   return $form;
?>

```

Notice the use of drupal\_get\_form() in the menu hook. This function takes the return value of create\_campaign\_form2, which it expects to be a PHP array, as an argument and uses that data to build the markup of the form.

This particular example will generate a form with only a select drop down. But check out the complete Form API reference for all (and there are A LOT) of the options and settings you have available to build your form. It might be intimidating at first, but the idea is quite simple: you create a PHP array that represents your form and then drupal\_get\_form() turns that array into a secure and well structured form. ALWAYS use the Form API to build forms in Drupal.
> 2 votes

---
Tags: theming, routes
---


# Question
Title: Show a webform input if user selects certain option from select list?
Im making a webform with a select list. If you chose a certain option in the select list I need a text input field be be revealed.

Can this be done by Drupal or should I write some jQuery to show / hide the input?

# Answer
> 2 votes
Update to a newer version of Webform where webform\_conditional has been merged.

> Description: This modules enhances the existing Conditional Rules of the Webform Module. It adds the ability to make components dependent on select components(i.e. listboxes, radio buttons, and checkboxes) that appear on the same page.
>
> **Important** As of Webform version 7.x-4.0-alpha2 this module has been merged into Webform and is no longer necessary. The 7.x-2.x version of this module handles this upgrade. See: #1616376: Create Migration to Webform 4.x

Then when you make a webform node you will have additional local task labeled `conditionals`. Once you've added form fields to the webform -- you can set conditions using the administrative form found there.

# Answer
> 0 votes
I would do it using Javscript and hide the text field with CSS

Using a form\_preprocess, add an attribute to fire your JS event.

This might be a helpful link: How to make form buttons call only javascript?

---
Tags: webforms
---


# Question
Title: Technical advantages of either Configuration or Features over the other?
In short, Configuration vs Features, in Drupal 7, fight!

As always, *technical* advantages, or other hard facts, as we don't do *discussions* here. Drupal 7 specific to limit to scope, as CMI vs Features is a completely different discussion.

# Answer
Watch Configuration for the future, because it more closely follows the model of Drupal 8. But I wouldn't suggest using it for now, because it is in alpha state, which means you need to be prepared to hack on it to keep it working, and you need to constantly update it, because it will not get formal Security Advisories if security issues are discovered.

Features is at 1.0, so it's a more stable choice for projects going to production soon, as you can trust that minor version updates will not break your existing features.
> 2 votes

---
Tags: 7, features, configuration
---


title: CKEditor disappeared

text:
# Question
Title: CKEditor disappeared
Was in my Drupal 6 site editing some pages and CKEditer suddenly disappeared in the Edit screens.

I did nothing to anything else & have no idea why the CKeditor fields are no longer showing up when I edit content?

# Answer
I recommend you to do the following and I hope it will fix your issue

* Clear drupal cache then check CKeditor field
* If nothing changed then try to open your site on different browser
* If nothing changed then try to look if you have any javascript errors when you edit any content/node/settings; use firefox with firebug add-on
* If nothing changed then try to uninstall the module then install it again
* Also try to disable javascript optimization under performance menu
> 1 votes

---
Tags: wysiwyg
---


title: Using '/profiles' in a URL alias

text:
# Question
Title: Using '/profiles' in a URL alias
The path '/profiles' exists as a physical folder in the root of a Drupal install, which means adding a URL alias for a piece of content to '/profiles' will not work - a 403 error is the result.

Lucky 'ol me, for a particular project I have an SEO partner telling me that using that particular path is an absolute, categorical must; not having this would be proof that the Myan's doomsday prediction is in fact accurate, we'll all die slowly, etc., etc.

So I'm going to go ahead and throw this slightly ridiculous question out to the masses to see if anyone's found a creative way to solve this problem before...

How can I use '/profiles' (and '/profiles/\*', etc.) as URL aliases, while maintaining a fully functional, update-able Drupal instance?

Importantly, we're using the Global Redirect module, with the 'De-slash' and 'Non-clean to clean' options enabled (and they need to stay that way).

# Answer
> 11 votes
1) .htaccess (before line 100):

```
RewriteRule ^profiles($|/(.*)) /index.php [L]

```

2) VirtualHost (for de-slash setting):

```
<Location /profiles>
     DirectorySlash Off
</Location>

```

Second part is needed only if you use Global Redirect "de-slash".

---
Tags: 7
---


title: jQuery not working in zen theme

text:
# Question
Title: jQuery not working in zen theme
Ive put this code before the closing head tag in my html.tpl.php but nothing is happening. Im using the zen theme. Ive tried clearing my cache.

Im I somehow missing a syntax error or is this a Zen/ Drupal qwerk?

```
<script>
    $(document).ready(function() {
        alert('hi');
    });
</script>

</head>

```

# Answer
> 4 votes
It would be helpful to know what version of drupal you are using.

Modifying `html.tpl.php` to add Javascript like this is really a bad choice as it is a very brittle way of coding something.

Jquery in Drupal 7 is loaded using the `noConflict` mechanism. This avoids javascript namespace collisions:

> Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $. If we need to use another JavaScript library alongside jQuery, we can return control of $ back to the other library with a call to $.noConflict():

If you wanted to use code like you've written you would write:

```
<script>
    jQuery(document).ready(function() {
        alert('hi');
    });
</script>

```

You're better off adding a `scripts[]` entry into your `theme_name.info` file and placing such code in its own javascript file in your theme directory. Drupal will load it into the HTML `<head>` for you and aggregate your javascript files for you if you have aggregation turned on.

```
# In YOURTHEME.info
scripts[]= js/example.js

/* Example /sites/all/themes/YOURTHEME/js/example.js */
jQuery(document).ready(function($) {
  $('nav ul.primary-menu').append('<div class="nav-blackhole"></div>');
});

```

---
Tags: javascript, theming
---


title: Dynamic hook registration

text:
# Question
Title: Dynamic hook registration
Is it possible to register hooks dynamically? I.e. not by hardcoding the hook handler into your code.

For instance, I'm writing a module and would like to add an option to some content type creation pages. I know this can be done using the `hook_form_FORM_ID_alter` hook, but since I don't know what node types will exist in the drupal installation I obviously can't hardcode the hooks.

Or will I have to use `hook_form_alter` or `hook_form_BASE_FORM_ID_alter` and check whether the option should be shown for that form? I'd really, REALLY would want to avoid that, since it's a really icky solution.

Or am I approaching this the wrong way?

# Answer
> 1 votes
What you describe is what Drupal does in translation\_form\_node\_form\_alter(), and book\_form\_node\_form\_alter(). Both the hooks are implementations of `hook_form_BASE_FORM_ID_alter()` which first verify if the form should be modified.

Hooks are normal functions; to dynamically add them you should execute code similar to the following one, outside any function.

```
$body = "The body of the function";

foreach (mymodule_get_content_types() as $type) {
  eval("function mymodule_form_{$type}_alter { {$body} }");
}

```

That code would be executed every time the module file is loaded, and there would not be any practical benefit from using such code.

Considering that Drupal 8 will use Symfony, and its Dependency Injection Container, it is preferable to use `hook_form_BASE_FORM_ID_alter()` until Drupal 8, and then changing implementation with Drupal 8. (Module's code already needs to be changed for Drupal 8, anyway.)

# Answer
> 1 votes
The usual approach is to create a settings form for your module and save the content types on which you want your hook\_form\_alter to intervene. Then with a simple check you can implement you alterations. The list of content types existing at a certain point in Drupal is easy to check.

I see no other way of actually placing your alters for specific content types. Even if you create your hook dynamically by using an unorthodox

```
foreach ($SELECTED_NODETYPES as $NODETYPE) {
  if (!function_exists("my_module_form_$NODETYPE_node_form_alter")) {
    function my_module_form_$NODETYPE_node_form_alter (&$form, &$form_state) {
        //your alterations
    }
  }
}

```

You will still have to have a list of nodetypes to check from, and on each new nodetype creation you have to be sure you flush the cache so your module will declare the new hooks and Drupal actually will take them into account.

---
Tags: 7, hooks, forms
---


# Question
Title: Views & custom exposed filters : where do I start?
I've got this module which makes an additional field available when you base the view on **Users**. The field is made available through `hook_views_data()`.

I've created a filter for this field, and it should be exposed to users. However, what I would really like to do is to create a custom filter. That is, a very custom form with some specialised options which the user can choose between.

How do I go about doing this? How do I tell Views that I've got this custom exposed filter. I know `hook_views_plugins` has something to do with this, but I can't find any place which describes the general picture of how things interact. Does anyone have any experience with this; and how things work together and which pieces I need to solve the "puzzle"?

Any input appreciated!

# Answer
I guess the best place to start is to look at the way some other module is doing it. Or how views itself does it for some core module :) (i.e. taxonomy or user. There is at least 3 things you have to do :

1. tell views you have something for it
2. provide it :)
3. tell drupal to load it

the telling can be done by implementing :

* hook\_views\_data in case you define an entire field, or
* hook\_field\_views\_data\_views\_data\_alter (no doc if i get it right) if you want to change someone elses field filtering

create a directory views, place a file called your\_module.views.inc in it and put the hooks there.

then create a file with a class that will extend the filter

and include that file in the modules info file

dont forget to refresh cache and that should be it :)
> 0 votes

---
Tags: views
---


title: Why does the search module break cron

text:
# Question
Title: Why does the search module break cron
I was trying to work out why cron wouldn't run on my site and came across this post: http://codekarate.com/blog/drupal-6-fixing-stuck-cron-run which said that enabling and disabling search would fix it. It did, but does anyone know why search breaks cron?

# Answer
> 2 votes
The Search module implements `hook_cron()`, and its implementation it invokes hook\_update\_index() to update the search index. One of that hook implementations is node\_update\_index(), which

* Loads some nodes whose IDs are returned from a query
* Renders those nodes, and passes their body content to search\_index()

If the node body contains PHP code that redirects the users to a different page, or an implementation of `hook_nodeapi()` redirects the users when a node is viewed, that can cause problems to cron tasks.

---
Tags: search, cron
---


# Question
Title: Extracting field values (of certain entity type and bundle) from form/form_state
I have fields of entity type `foo` and bundle name `bar`. These fields get rendered as an HTML `input` inside a form. There are other fields present on the form, but I'm only interested in foo/bar ones.

The number of foo/bar fields is dynamic (as are the names). I need a way to extract their name/value pairs.

Here's my situation in code:

```
function submit($form, &$form_state) {
  // Get all the submitted data that is backed by a field of
  // an entity type 'foo' and bundle 'bar'
}

```

Thanks.

# Answer
Okay, I solved my problem with `field_info_instances` function.

`array_keys(field_info_instances('foo', 'bar'))` gives me the names of the fields I'm interested in.

At this point, all I have to do is to loop thru the field names and access their values like this:

`$form_state['values'][$field_name][LANGUAGE_NONE][0]['value']`

Works like a charm. But do let me know if there's a better solution.
> 0 votes

# Answer
All the field values are in `$form_state['values']`. See: `drupal_form_submit`.

You might also be interested in using `hook_form_BASE_FORM_ID_alter` instead of `hook_form_alter` to target a particular content type. Your function would look like: `'mymodule_form_' . $form_id . '_alter'`.

Or at least an:

```
if ($form_id == 'your_content_type') { // add new submit handler }

```

in `hook_form_alter`.

Also use `LANGUAGE_NONE`, without quotes, instead of 'und' ie `$some->var[LANGUAGE_NONE]['value'];`

---

Also for future reference: Install the Devel module, use `dpm($form_state,'$form_state');`

When you use `dpm` you get nice dumps of variables that look like: http://goo.gl/qIf6p
> 1 votes

---
Tags: 7, entities
---


# Question
Title: taxonomy_node_get_terms(arg(1)) kills layout in page.tpl.php
I use this function to get the node's taxonomy term.

```
$tax = taxonomy_node_get_terms(arg(1));

```

Calling this function destroys the layout of the page. Why?

# Answer
`taxonomy_node_get_terms()` needs a node object as the first argument; `arg()` returns a part of the URL (which is just a string).

You can use the `menu_get_object()` function to get the current node (if available) so it would be easier to use that:

```
$node = menu_get_object();
if ($node) {
  $tax = taxonomy_node_get_terms($node);
}

```
> 1 votes

---
Tags: nodes, 7
---


# Question
Title: Calculate values from multiple content items
I have a Drupal 7 website that will be used to track automobiles in a fleet, as well as their engines and a few other items. Regarding the engines, I will be tracking the number of hours the engine is used, and the number of miles put on the engine in each use. To do so, I have an "Engine Usage" content type set up with fields for "hours used this trip" and "Mileage this trip". Each time the Engine is used, a new Engine Usage content item will be created manually, and the hours/miles will be entered into those fields. The Engine Usage content type is linked to the Engine content type/item by way of the Node Reference module.

I now need to create a View that will pull in the information for the Engine content item (its specifications, etc), as well as the total usage for that Engine by way of its related/linked Engine Usage content items. Instead of displaying each of the usage items separately, I need to apply a calculation to them, in the form of "Engine Usage for content item Engine123 'Hours driven'" multiplied by "Engine Usage for content item Engine123 'Mileage this trip'". I have looked into Views Calc, bu I cannot figure out how to first combine all of the Hours for the Engine Usage content item for any given engine, and then combine all of the Mileage for the Engine Usage content item for any given engine. If I can get to that point, I think I can then figure out the rest of the calculation on my own.

The end result will be a View block with a contextual filter that will pull the info in based on the ID of the content item being viewed. So when viewing the content item Engine123, the block with the calculated hours * mileage for Engine123's usage content items would be displayed.

Any ideas? Please let me know if any of this is too vague.

# Answer
did you try to use the **Aggregate option** (use SUM field aggregation option) *and* **Views Calc** at the same time ? That might do the trick.

---

If not, you can use a PhP block (you have to send it the engine node id, I hope you use Panels or node.tpl.php).

Then, the code would be (I guess) ;

```
$engine_usages_nids = db_select('yourentityreferencefield', 'n')
  ->condition('entity_id', $the_engine_nid, '=')
  ->field('n', 'field_yourentityreferencefield_nid')
  ->execute()
  ->fetchCol;

$myfields_values = $db_select('field_data_hoursuagefield', 'h')
    ->condition('entity_id', $engine_usages_nids, 'IN')
    ->join('field_data_mileagefield', 'm', 'h.entity_id = m.entity_id)
    ->fields('h', array('hoursuagefield'))
    ->fields('m', array('mileagefield'))
    ->groupBy('h.entity_id')
    ->execute()
    ->fetchAssoc;

$total = 0;
while($record = $myfields_values) {
  $total = $total + intval($record['hoursuagefield'])*intval($record['mileagefield']);
}

echo($total);

```

This is all made by heart, I advise you to double-check :)

Have fun !
> 0 votes

---
Tags: views, entities
---


title: Include javascript in node

text:
# Question
Title: Include javascript in node
myjavascript.js:

```
    function initialize() {

        var waStyle = [
            {
                featureType: "all",
                stylers: [
                    { saturation: -100 }
                ]
            }
        ];

        var mysiteMap = new google.maps.StyledMapType(waStyle,{name: "Nuance"});

        var img = new google.maps.MarkerImage("/themes/nuance/img/pin.png");

        var myLatlng = new google.maps.LatLng(41.061833,28.997948);

        var mapOptions = {
            zoom: 16,
            center: myLatlng,
            disableDefaultUI: true,
            mapTypeControlOptions: {
                mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'mysite_map'],
            }
        };

        var map = new google.maps.Map(document.getElementById('mainmap'), mapOptions);

        var point = new google.maps.LatLng(41.061833,28.997948);
        var marker = new google.maps.Marker({
            position: point,
            map: map,
            animation: google.maps.Animation.DROP,
            icon: img
        })

        map.mapTypes.set('mysite_map', mysiteMap);
        map.setMapTypeId('mysite_map');
    }

    function loadScript() {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
        document.body.appendChild(script);
    }

    window.onload = loadScript;

```

And include in my node via field. (text format: php code)

```
<?php include('themes/mytheme/scripts/maps/myjavascript.js'); ?>

```

But get error.

On site:

```
 function initialize() { var waStyle = [ { featureType: "all", stylers: [ { saturation: -100 } ]
    ...

```

What's my problem and how can i fix it?

# Answer
The Drupal way is to add js on the go is `drupal_add_js`

```
drupal_add_js($data = NULL, $options = NULL)

```

**Examples:**

```
  drupal_add_js('misc/collapse.js');
  drupal_add_js('misc/collapse.js', 'file');
  drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
  drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });',
    array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
  );
  drupal_add_js('http://example.com/example.js', 'external');
  drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');

```

There is a better way to add a library file drupal\_add\_library

### Parameters

**$module**: The name of the module that registered the library.

**$name**: The name of the library to add.

**$every\_page**: Set to TRUE if this library is added to every page on the site. Only items with the every\_page flag set to TRUE can participate in aggregation.
> 1 votes

---
Tags: 7, nodes, javascript
---


# Question
Title: How to implement a custom field available for Views?
I'm making my first steps authoring simple modules. I would like to make my life easier by implementing a custom field for taxonomy views, a field named: "Taxonomy term: Arbitrary ascendant" so that it gets a term's ascendant at the given hierarchy level, as returned by `taxonomy_get_parents_all`.

Similarly, for content Views, I would like to provide a field configuration that would allow for ascendant tests for any term on an entity.

Could anyone point me to the Views API functions that must be taken into account to make this module properly authored?

# Answer
Try views.api.php

> Describe hooks provided by the Views module.

& Views hooks

> Hooks that can be implemented by other modules in order to implement the Views API.
> 1 votes

# Answer
A way I have gone about this recently is to add a place holder field to a content type. I then create a module that provides a tpl.php for this field and use a preprocess function to actually calculate it.
> 0 votes

---
Tags: views
---


title: Minimum Items in Cart for Checkout

text:
# Question
Title: Minimum Items in Cart for Checkout
I am working in Drupal 7 in Ubercart 3, and I am looking for a way to set a minimum on the number of items that a user can have before being able to start the checkout process.

Is there a module out there that handles this need?

# Answer
There is Ubercart Product Minimum & Maximum

> Adds minimum, maximum and order in multiples limits on products. Checks that the quantity selected matches the limits during both Add To Cart and Checkout actions. Quantity checks are disabled when product is added to the cart as part of a product kit.

If you want to do it with code this is one way to do that.

You can make use of hook\_add\_to\_cart to get the product add event.

To get the number of items use uc\_cart\_get\_contents

The ides is

```
function <modulename>_add_to_cart($nid, $qty, $data) {
  $items = uc_cart_get_contents();
// Display a message if the cart has more than 5 products.
  $item_count = count($items);
  if ($item_count < 5) {
    drupal_set_message('Your cart Should contains more than 5 products to checkout !');
    // drupal_goto to product listing page
  }
  return $result;
}

```
> 1 votes

---
Tags: ubercart
---


# Question
Title: What do you do in a Views field theming function to change the output?
\[warning: Views newbieism ahead...\]

I've got a View working with the FullCalendar module, which shows items from one of my content types in the calendar. The title of the item appears in the calendar on the day specified by the "target date" field; all of this is working fine. I now want to change the string that shows up in the calendar from the title of the item to something different, which I'll work out based on the item being shown in the view.

This is a matter of theming, I presume. I've defined a template file called `views-view-field--fullcalendar--field-target-date.tpl.php` in my theme's template folder. Some dsm() statements in this file confirm that it is getting picked up by the Views system, and its `$row` and `$view` variables have appropriate values. But nothing that I do in this file changes what's presented in the view -- I thought `print "something"` would do it, but it doesn't; I've tried setting the passed-in `$output` and other values to something on the hope that they would magically find their way back to some code that would print them, but again without luck.

So I seem to be in the right place -- what do I have to do to change what gets displayed on the page?

# Answer
> 0 votes
I seem to have stumbled into something that works:

In the Views control panel for my Calendar view, I went down into Format \> Settings \> Customize Fields, and clicked the "Use a custom title" checkbox. After I did this, the system started paying attention to `views-view-field--fullcalendar--field-target-date.tpl.php`, and used whatever I `print`ed as the title of the events in the calendar.

So far, all is well, although I'm not sure whether this is an inherent part of the Views system per se, or if it has something to do with the module's use of the fullcalendar jQuery plugin. Other solutions/answers/explanations are of course welcome.

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


# Question
Title: How do I force a 403/410 error code for specific users and content?
I have a content type in a Drupal 6 site that allows the creator of a node to mark the node as "withdrawn"; he can still see it, but attempts by others to see it are caught and redirected somewhere else, like their user page.

So far so good, but I'm concerned about what happens when search bots show up looking for the node; they get a 302 response from the server and are then redirected to the "somewhere else" page with an http code 200. What ought to happen (I think) is that the request by Googlebot for the node should result in a 403 or 410 error code, causing (eventually) the page to get dropped from the Google index. So I'd like to have the page generation work just like it is, except with a 401/410/whatever getting sent back as the response to the initial request.

I've tried putting some `header()` calls into the part of the code that detects the disallowed access, but they're not working, presumably because I'm too far along in the page construction by the time that call happens for the new header information to matter.

Is there any way to get this error code generated while still getting the user to the page I want them to be at?

# Answer
drupal\_goto Can help you

```
drupal_goto($path = '', $query = NULL, $fragment = NULL, $http_response_code = 302)

```

### Parameters

**$path**: A Drupal path or a full URL.

**$query**: A URL-encoded query string to append to the link, or an array of query key/value-pairs without any URL-encoding. Passed to url().

**$fragment**: A destination fragment identifier (named anchor).

**$http\_response\_code**: Valid values for an actual "goto" as per RFC 2616 section 10.3 are:

* 301 Moved Permanently (the recommended value for most redirects)
* 302 Found (default in Drupal and PHP, sometimes used for spamming search engines)
* 303 See Other
* 304 Not Modified
* 305 Use Proxy
* 307 Temporary Redirect (alternative to "503 Site Down for Maintenance")

Note: Other values are defined by RFC 2616, but are rarely used and poorly supported.
> 1 votes

# Answer
I think I've got an answer for this -- at least, it seems to be working for me, and (after the fact) seems fairly obvious :) After detecting the issue:

* Do `drupal_set_header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');` to generate the 404 response. This works where `header()` doesn't; it knows how to fit the header into the page being generated.
* You can't do a `drupal_goto()` to generate the desired content -- this will generate a new page with a new URL. Instead, call whatever code gets called at your desired destination page and PRINT (not `return`) the result.

This gives me what I want: an apparent 404 error at the desired location, but with content corresponding to what I want. This is in some sense a custom 404 page; I played around with the `customerror` module, but doing it this way seemed simpler. Anyway, it works...
> 0 votes

# Answer
If I understand you well I won't bother about redirects:

```
function mymodule_view($node, $teaser = FALSE, $page = FALSE) {
   global $user;

   if (_is_node_withdrawn($node)) {
       if (! _user_allowed_to_view($user)) {
          drupal_not_found();
       }
   }
}

```
> 0 votes

---
Tags: nodes, users
---


# Question
Title: In a tableselect form element with '#js_select' => FALSE, how can I re-use the column header for a label?
I have a pretty ordinary tableselect element that looks like so

```
$form['registration_table'] = array(
    '#title'=>"Register",
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $enrollment_options,
    '#js_select' => FALSE,
    '#multiple' => TRUE,
);

```

What I would like is to be able to use the empty space which is reserved for the "select all" checkbox for a text label. I would like to indicate by the label what action the checkboxes represent. In this case they represent selecting a course to register for so I would like to add the label "Register" there. Any advice on how to do this?

# Answer
For doing this you have to change the "theme\_tableselect" core code. See this documentation code part. If you do not set "select all" then the header is assigned to null
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Change size of views exposed form search box
Im using hook\_preprocess\_views\_exposed\_form to change the output of my views exposed search box. I am able to successfully change the text on the search button, but I am not able to change the size. I cant figure out where I am going wrong. Here is what I have:

```
function MYTHEME_preprocess_views_exposed_form(&$vars, $hook) {
  // dsm($vars['form']);
  if ($vars['form']['#id'] == 'views-exposed-form-all-page') {
    $vars['form']['submit']['#value'] = t('Go');
    $form['text']['#size'] = '90';
    unset($vars['form']['submit']['#printed']);
    $vars['button'] = drupal_render($vars['form']['submit']);
  }
}

```

This is what I am stuck on:

```
$form['text']['#size'] = '90';

```

# Answer
I think it would be better to change the form sooner than during themeing ... the best is to implement a form\_alter hook, in this case

> function MODULENAME\_form\_views\_exposed\_form\_alter(&$form, $form\_state)

you can try to dpm($form) first, to see what exactly you should change, and probably also add a condition about module id.

if you install advanced\_help, this info can be found on your site at help/views/alter-exposed-filter :)
> 0 votes

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


# Question
Title: Unable to update head_title string in template_preprocess_html
I wanted to add some data to the page head title and created a template\_preprocess\_html function in my module.

I added a couple entries to the head\_title\_array and imploded the array back into head\_title.

At first it looked like it wasnt working at all, but then I checked and in html.tpl.php the $head\_title\_array was updated.

My temp solution is to implode the array there before printing it but that's a little hackish for me.

Thoughts on where the title is being set or re-set to prevent it from being changed in template\_preprocess\_html?

Module code is aproximately:

```
function MODULE_preprocess_html(&$variables) {
  $head_title = $variables['head_title_array'];
  array_unshift($head_title, 'TEST');

  $variables['head_title_array'] = $head_title;
  $variables['head_title'] = implode(' | ', $head_title);
}

```

and in html.tpl.php:

```
<title><?php print implode(' | ', $head_title_array); ?></title>

```

I just noticed that the metadata module is storing variables in an array called metatag\_set\_preprocess\_variable. That might be the cause, I'll investigate further.

# Answer
> 4 votes
If you find that `$head_title` is different from `implode(' | ', $head_title_array)`, it means there is a module running after yours that implements `hook_preprocess_html()` which runs after your implementation, or `hook_process_html()`.

The code executed from Drupal is the following:

* template\_preprocess\_html() (It runs before `hook_preprocess_html()`.)

```
// Construct page title.
if (drupal_get_title()) {
  $head_title = array(
    'title' => strip_tags(drupal_get_title()),
    'name' => check_plain(variable_get('site_name', 'Drupal')),
  );
}
else {
  $head_title = array('name' => check_plain(variable_get('site_name', 'Drupal')));
  if (variable_get('site_slogan', '')) {
    $head_title['slogan'] = filter_xss_admin(variable_get('site_slogan', ''));
  }
}
$variables['head_title_array'] = $head_title;
$variables['head_title'] = implode(' | ', $head_title);

// Populate the page template suggestions.
if ($suggestions = theme_get_suggestions(arg(), 'html')) {
  $variables['theme_hook_suggestions'] = $suggestions;
}

```
* template\_process\_html() (It runs after `hook_preprocess_html()`, but before `hook_process_html()`.)

There is no code that alters `$variables['head_title_array']`, or `$variables['head_title']`.

The fact `$head_title_array` contains the value you expect makes me think there is really a module that implements `hook_preprocess_html` to alter `$variables['head_title']`.

To be sure your module is the last one running `hook_preprocess_html()`, you need to make your module weight higher.

# Answer
> 2 votes
try to paste this into devel/php :

```
dpm(module_implements('preprocess_html'));
dpm(module_implements('process_html'));

```

---
Tags: theming, 7
---


title: Can’t login after FF browser update

text:
# Question
Title: Can’t login after FF browser update
My Firefox has just updated to version 17.1. When I try and login I get this message:

> Access denied
> You are not authorized to access this page.

The URL does however recognize my account as it contains /users/myusername

I can log in fine in older versions of Firefox, and Internet Explorer. I however get the same problem in Safari version 4 Public Beta (528.16).

Does anyone know a fix for this? I have tried rebuilding permissions but it didn't help.

I am running Drupal 6.

# Answer
A similar situation was encountered by a user who reported that clearing his browser cookies solved the problem.
> 1 votes

---
Tags: users
---


title: Commerce: Show taxes on checkout

text:
# Question
Title: Commerce: Show taxes on checkout
I am having problems with a porjectr of mine. Seems the taxes are not showing up until AFTER the order is put through. Here is a screenshot of what I mean.

I would like to have taxes show up at the button right before total. Can anyone point me in the right direction? Thank you.

i.stack.imgur.com/3hMWC.png

# Answer
> 1 votes
Taxes are dependent on shipping address so adding a tax line item to the cart does not make sense. Try looking at one of the tax rules on /admin/config/workflow/rules/components to see how the tax line item is added to an order. By default, tax line item is added in the pane that comes after a customer has entered her shipping address and before payment is submitted. Adding a tax line item to a cart requires a custom line-item type and a shipping address to be provided for tax calculation.

---
Tags: commerce
---


title: Defining a new input format

text:
# Question
Title: Defining a new input format
I need to define a new input format programmatically, probably as part of my module's `hook_install()`. I need to write code that duplicates the manual operations described on http://drupal.org/node/778976.

I have not been able to learn how to do this. Any pointers in the right direction will be appreciated.

# Answer
Code from standard Drupal profile is your friend: http://drupalcode.org/project/drupal.git/blob/c5d6e6334fb7a71ecf1dbc7e06a7de8ad9547b27:/profiles/standard/standard.install#l14

```
  // Add text formats.
  $filtered_html_format = array(
    'format' => 'filtered_html',
    'name' => 'Filtered HTML',
    'weight' => 0,
    'filters' => array(
      // URL filter.
      'filter_url' => array(
        'weight' => 0,
        'status' => 1,
      ),
      // HTML filter.
      'filter_html' => array(
        'weight' => 1,
        'status' => 1,
      ),
      // Line break filter.
      'filter_autop' => array(
        'weight' => 2,
        'status' => 1,
      ),
      // HTML corrector filter.
      'filter_htmlcorrector' => array(
        'weight' => 10,
        'status' => 1,
      ),
    ),
  );
  $filtered_html_format = (object) $filtered_html_format;
  filter_format_save($filtered_html_format);

```

Enable permission for system roles (code):

```
// Enable default permissions for system roles.
$filtered_html_permission = filter_permission_name($filtered_html_format);
user_role_grant_permissions(DRUPAL_ANONYMOUS_RID, array($filtered_html_permission));
user_role_grant_permissions(DRUPAL_AUTHENTICATED_RID, array($filtered_html_permission));
user_role_grant_permissions(variable_get('user_admin_role', 0), array($filtered_html_permission));

```
> 3 votes

---
Tags: 7
---


# Question
Title: How can I send an e-mail whenever user registration fails?
I am a bit concerned that my user registration is too complicated. I have done some basic usability testing, but I'm still not confident, so what I'd like to do is send an e-mail to myself every time a user makes a mistake on the registration form that requires a correction before registration can be processed (Mollom validation fails, no input in a required field, etc.)

Is there an easy "catch-all" way to do this for all possible mistakes users can make?

# Answer
> 2 votes
Not sure how *deep* you want to go, but here's what I would do.

* Create a custom module, "mysite\_utils" (I always make at least one custom module to do some custom tweaks.)
* Create a mysite\_utils\_form\_alter(&$form, &$form\_state, $form\_id) function.
* In that form\_alter function, look for the user registration form\_id.
* Add a custom validation handler `mysite_utils_user_register_validate().`
* Put your validation checks in that function. If the validation fails, send yourself an email.

This process will require a lot of custom coding, not sure what your Drupal level is.

---
Tags: users, forms
---


# Question
Title: How can I save arrays of values in the database?
I am trying to save multiple values from a textarea to a database table.

I use the following code, but I feel it is the wrong way.

```
foreach ($user_emails as $key => $value) {
  $insert_banned_emails = db_insert('banned_users');
  $insert_banned_emails
    ->fields(array(
      'email' => $value,
    ))
    ->execute();
}

```

Is there a different way for achieving the same result?

# Answer
I would use the following code.

```
foreach ($user_emails as $value) {
  $query = db_insert('banned_users');
  $query->fields(array('email' => $value))->execute();
}

```

Alternatively, you could use the following code.

```
$query = db_insert('banned_users')->fields(array('email'));

foreach ($user_emails as $value) {
  $query->values(array('email' => $value));
}

$query->execute();

```

With MySQL, the query uses the multi-value syntax.

With other databases, the executed queries will be one for each call to `$query->values()`, wrapped in a transaction. This means the queries will be rolled back when one of them fails. In fact, the code executed from InsertQuery::execute() is the following one.

```
  // Each insert happens in its own query in the degenerate case. However,
  // we wrap it in a transaction so that it is atomic where possible. On many
  // databases, such as SQLite, this is also a notable performance boost.
  $transaction = $this->connection->startTransaction();

  try {
    $sql = (string) $this;
    foreach ($this->insertValues as $insert_values) {
      $last_insert_id = $this->connection->query($sql, $insert_values, $this->queryOptions);
    }
  }
  catch (Exception $e) {
    // One of the INSERTs failed, rollback the whole batch.
    $transaction->rollback();
    // Rethrow the exception for the calling code.
    throw $e;
  }

```

In short, I would use the code you are using if the inserted values are independent from each other; I would use the code I shown when the values depend from each other.

In your case, the emails are independent from each other. If you would use the second snippet I shown, the database table will contains all the values, when the sub-query don't fail, or none when a single sub-query fails.

You could also use `drupal_write_record()`, even though I much prefer the other snippets.

```
foreach ($user_emails as $value) {
  drupal_write_record('banned_users', array('email' => $value));
}

```

I don't see any pro in using this snippet, though.

### Reference
> 14 votes

# Answer
This is a similar version to your code, but better performance. You really don't want to call execute() a thousand times, you only need to call it once.

Reference

```
$insert_banned_emails = db_insert('banned_users')->fields(array('email'));
foreach ($user_emails as $key => $value) {
  $insert_banned_emails->values(array(
    'email' => $value,
  ));
}
$insert_banned_emails->execute();

```
> 3 votes

---
Tags: 7, database
---


title: Duplicate Content

text:
# Question
Title: Duplicate Content
is there any way, to remove the duplicate content, produced by D7?

An Example:

You can reach a node with two URL's:

```
http://mysite.com/node/3

```

Or:

```
http://mysite.com/nodename

```

The same problem with taxonomy terms

From SEO view, this is very negative...

Is there any way, to fix that?

# Answer
It's already handled for you, if you look at the source you'll see the `<link rel="canonical"` tag which lets search engines know which page to consider the 'original' content.

This is Google (and others) preferred method to handle this type of situation; there's more information on this post.
> 1 votes

# Answer
Redirect from one URL to the other: use the Global Redirect module. Here is a quote about it (from the module's project page):

> ... a simple module which:
>
> * Checks the current URL for an alias and does a 301 redirect to it if it is not being used.
> * Checks the current URL for a trailing slash, removes it if present and repeats check 1 with the new request.
> * Checks if the current URL is the same as the site\_frontpage and redirects to the frontpage if there is a match.
> * Checks if the Clean URLs feature is enabled and then checks the current URL is being accessed using the clean method rather than the 'unclean' method.
> * Checks access to the URL. If the user does not have access to the path, then no redirects are done. This helps avoid exposing private aliased node's.
> * Make sure the case of the URL being accessed is the same as the one set by the author/administrator. For example, if you set the alias "articles/cake-making" to node/123, then the user can access the alias with any combination of case.
> * Most of the above options are configurable in the settings page. In Drupal 5 you can access this after enabling the globalredirect\_admin module. In Drupal 6, the settings page is bundled into the module.
> 0 votes

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


# Question
Title: Search Api Solr - Pointing term links inside a view to its facet
Using Search Api. Solr as a backened. Search pages built with Views. When adding a term field to a view, that term links to the core taxonomy term pages. That term should instead link to it's facet(not adding to the other facets if the user had previously click on other facets).

I have searched high and wide for any documentation or discussion involving this, and only found a few issues that didn't go anywhere. There is hardly any discussion, which I find odd because I would imagine this would be a pretty common request.

Does anyone have any knowledge on this issue?

# Answer
> 1 votes
Why would you want the fields in the search results to have taxonomy terms that are linked to the facet URL instead of the taxonomy page of the item? It just seems a little redundant, because that's what the facets there are for.

A solution would be to use FacetAPI Pretty Paths and rewrite the output link of the taxonomy term to match the URL of the facet. You'll need the fields term name and id, then format as : www.example.com/search-page/\[pretty paths term\]/\[term name\]-\[term id\]

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


# Question
Title: Is there a distribution optimized for heavy data traffic?
I am testing an Android app which sends minute-by-minute updates to my Drupal site which acts as a server.

I create a single node each day and all my app data is saved in CCK fields within that node.

I got the updates working yesterday and tested for half a day. When I try to edit the node, to see the CCK data uploaded, my site crashed and complained of lack of PHP memory.

In my .htaccess file, I had set PHP memory to 100M. I then increased it to 300M and then 500M with no improvements. Then I tried 1000M. It worked but it seems slow.

That's just for one user's half a day's worth of data. Eventually, I will have hundreds of users with 24hours data each.

Can anyone tell me if there is a Drupal distribution which handles heavy data traffic by design?

# Answer
You should have a look at Pressflow.

> Pressflow is a distribution of Drupal with integrated performance, scalability, availability, and testing enhancements.
> 6 votes

# Answer
Bojan put it right in a comment above. I just think its important to explain it again, in case someone finds this in the future :)

I think the problem here is rather in the design. If I get it right, you are saving all the data from 1 day into 1 node ?

When you attempt to load such one node, drupal loads all the data in memory, so I am afraid that no settings and distributions can save you, you just have to change the design - probably having 2 types - 1 for the day and 2nd for the data entries.

You might as well try something "lighter" for the data - such as the data module.
> 1 votes

---
Tags: performance
---


title: Safe to remove core optional modules

text:
# Question
Title: Safe to remove core optional modules
I'm running on a restricted machine space/memory where I have to remove all un-needed modules.

Is it considered safe to uninstall core optional unused modules?.

modules like: Book, Forum, etc.

# Answer
Yes it's safe to remove them. But I would recommend you *not* doing so. These modules are just tiny modules and it won't give more than 1 MB of space to your system.

However, if you are no longer using a module, make sure you have uninstalled that module. If you had search module enabled and if you are no longer using it, disabling it *and* uninstalling it will clear existing search index and now you could get a lot of database space saved.

If saving every bit of the space is worth, look at your third party libraries. They often come with folders such as docs and examples in it that actually do not help in terms of the site functionality.

Other places that you might want to check include, log folders (Apache logs), SSH command logs, old backups from Backup and Migrate module (or other backups), obsolete caches (Admin \> Configuration \> Development \> Performance \> Clear All Caches -- this will clear all caches, including in-use ones), watchdog (Administer \> Reports \> DB Log \> Clear), spam comments (Admin \> Content \> Comments \> Unapproved).

Make sure you keep a backup of the system for your own safety!
> 9 votes

---
Tags: 7, installation
---


title: Ajax form only works the first time

text:
# Question
Title: Ajax form only works the first time
I have this simple ajax form with some ajax taxonomy checkboxes and a function that renders the content when the users changes the selected checkboxes. Everything work fine, the first time. The second time the user changes a checkbox I get this error:

`Undefined index: form_build_id in ajax_get_form() (line 320 of /var/www/mf/includes/ajax.inc)` and `Invalid form POST data.`

The only strange thing I've seen is when I inspect the request, there are a settings command, and ok insert command and another empty insert:

```
{command:insert, method:prepend, selector:null, data:, settings:null}

```

And in my html there is an empty .

My form:

```
function courses_lists_form($form, &$form_state) {dd(date('l jS \of F Y h:i:s A'));
  $terms = taxonomy_get_tree(1); // 1 = courses taxonomies vid
  $terms_array = array();
  foreach ($terms as $term) {
    $terms_array[$term->tid] = $term->name;
  }
  $form['taxonomias'] = array(
    '#type' => 'checkboxes',
    '#options' => $terms_array,
    '#title' => t('TEMÁTICAS'),
    '#ajax' => array(
      'callback' => 'courses_lists_form_ajax',
      'wrapper' => 'courses-lists-ajax',
    ),
  );
  $form['block'] = array(
    '#prefix' => '<div id="courses-lists-ajax">',
    '#markup' => mf_form_commons_courses_lists_gen(0, 0, TRUE, 'matrix', array(0 => 9), ''),
    '#suffix' => '</div>',
  );
  $form_state['redirect'] = FALSE;
  return $form;
}

function courses_lists_form_ajax($form, &$form_state){
  $taxs = array();
  foreach ($form_state['values']['taxonomias'] as $tid) {
    if($tid) $taxs[] = $tid;
  };
  $outp = '<div id="courses-lists-ajax">';
  $outp .= mf_form_commons_courses_lists_gen(0, 0, TRUE, 'matrix', $taxs, '');
  $outp .= '</div>';
  return $outp;
}

```

# Answer
There was an error in the generated markup. A missing closing div was messing everything. Now everything work as expected. Thanks.
> 2 votes

---
Tags: forms, ajax
---


# Question
Title: Uncheck Generate automatic URL alias problem
When I add new content I uncheck generate automatic url, but below, the Url Alias text field where I want to add custom url is still disabled. I'm not able to write my custom url there.

# Answer
Check if "Path" module is enabled. If not, enable it. I think it is enabled by default.

And go to admin/people/permissions and check "Administer URL aliases" under "Path" section.
> 0 votes

---
Tags: 7
---


# Question
Title: Rendering field_view_field with extra fields
I have a field which is being called with `field_view_field()`, and I want to add some extra parts.

```
$badges = field_view_field('profile2', $profile, 'field_badge', 'user_header');
if ($badges) {
  foreach ($badges as $b) {
    $b['title'] = $b['#term']->name;
    $b['link'] = l(t('external link'), '1234');
  }
}

```

I'm trying to use the term name as the title since it describes the image being rendered, and the link goes to a node. The logs are suggesting that I am trying to iterate across a Profile so that call fails, but I am wondering if I have missed the Drupal way of adding the title and the links to the rendering array.

# Answer
> 0 votes
I managed to solve this by overriding template\_taxonomy\_theme\_preprocess and then using the theme('image', $variables) function to output the styled images correctly with the link.

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


title: Get the Dimensions of the Theme Logo

text:
# Question
Title: Get the Dimensions of the Theme Logo
In Drupal 7 theme settings, you can upload a logo. How do you print the width and height of this logo in your theme?

---

**Background Research:**

`theme_get_setting('logo')` lets you get the path of a logo uploaded in the theme settings.

`image_get_info` lets you get the height and width of an image.

However, `image_get_info(theme_get_setting('logo'))` does nothing.

# Answer
You can use the following code. (Add error checking where necessary.)

```
  $image_url = parse_url(theme_get_setting('logo'));
  $image_path = str_replace(base_path(), realpath(DRUPAL_ROOT) . '/', $image_url['path']);
  $info = image_get_info($image_path);
  $height = $info['height'];
  $width = $info['width'];

```

As side note, `theme_get_settings('logo_path')` returns the path of the uploaded file used as logo. While `theme_get_settings('logo')` always return a value, whatever the logo is the default one, or one that has been uploaded, `theme_get_settings('logo_path')` returns a value when the logo has been uploaded.
The value returned for "logo\_path" is similar to public://logo.png. To obtain the real path, you would use code similar to the following one.

```
  if ($image_uri = theme_get_settings('logo_path')) {
    if ($wrapper = file_stream_wrapper_get_instance_by_uri($image_uri)) {
      $image_path = $wrapper->realpath();
    }
    elseif (!empty($image_uri)) {
      $image_path = realpath($image_uri);
    }
  }

```
> 4 votes

# Answer
The call to `theme_get_setting('logo')` gives you the *URL* of the logo, not the *path* (which is what you need in order to use `image_get_info`). The reason your call to `image_get_info` returns nothing (actually `FALSE`) is that you're feeding it garbage. As the old saying goes: GIGO.

You need to do something like the following:

```
$filepath =  $_SERVER['DOCUMENT_ROOT'] . base_path() . path_to_theme() . '/logo.png';
$image_info = image_get_info($filepath);
$width  = $image_info['width'];
$height = $image_info['height'];

```

(My method for sniffing the $filepath is probably not optimal, as it assumes the logo file is named "logo.png", which is not always the case, but I hope you get the idea.)
> 2 votes

---
Tags: files
---


# Question
Title: Can a form submit handler return results without using the $_GET array?
It looks like the default method for passing the result of handling a form submit is GET.

The following statement will redirect to `form/result`, where a page callback function will extract `$content` (the result form processing the form) from the query string (attached to the URL) using the `$_GET` array:

```
$form_state['redirect'] = array('form/result', array('query' => array('text' => $content)));

```

This works, but I do *not* want `$content` to be a query string (where it can be edited by the user).

Is there an alternative method (e.g. `POST`) for passing the value of `$content` to the page callback?

# Answer
> 3 votes
Actually, the default method of the form submission is POST and you're likely doing a POST back to the same page, then doing a redirect to this other page where you're setting params in the URL. The real issue you're having is getting data from the form submission onto the other page. Here's what you can do:

1. If the data is not sensitive you can stuff $content into a cookie and get it back out on your other page. This is still susceptible to user manipulation, so it shouldn't be used for anything sensitive.
2. Your other option is to save the value into the database somehow and fetch it back out on the next page. To do this you'll have to have some sort of scheme to the way you save the data that allows you to look it back up on the next page.

You're kind of using the Form API in a way it wasn't intended to be used. One other option would be to adjust the page that the form appears on to allow it to present the data, then no need for a redirect. That's a more normal use of the FAPI.

# Answer
> 4 votes
You can save `$content` in a session variable, and then redirect the users to a new page. The page callback of that page will then extract the data from the session data.

```
$_SESSION['mymodule_content'] = $content;
$form_state['redirect'] = 'form/result';

```

```
// The page callback then will execute the following code.
$content = $_SESSION['mymodule_content'];

```

The pros of using session data are:

* There isn't the length limit GET data has
* The data will not be visible in the browser address bar
* The data can be complex like an array, or an object

---
Tags: 7, forms
---


title: Entity Form Anonymous Users

text:
# Question
Title: Entity Form Anonymous Users
I am working on entity forms in drupal 7, I want anonymous users to be able to post content and then create an account, the problem is that by the time they create an account, any previous submission is already attached to "anonymous user".

I want to change the code so that when anonymous user posts, their content can be attached to the latest created users

Below is my code so far but it is not working.

```
if (empty($user->uid))  {
  $result = db_query('SELECT u.uid FROM {user} u ORDER BY u.uid DESC LIMIT :d',array(":d"=>1));
  while ($record = db_fetch_object($result)) {
    $uid = $record->uid; // last created user id .
  }
  $entityform->uid = $uid;
}

```

# Answer
> 1 votes
You should rather use the following code, but there is a problem I will describe.

```
if (empty($user->uid))  {
  $entityform->uid = db_next_id(db_query('SELECT MAX(uid) FROM {users}')->fetchField());
}

```

The problem with that code is that it will use the user ID of the next user account that is being created, which could not be the user who created the entity. This is true when:

* The anonymous user creates an entity instance
* After the code I shown is executed, a new user creates an account
* The anonymous user who created the entity instance creates an account

I would rather do the following:

* When an anonymous user creates an entity instance, asks for an email address
* Save the email address as part of the entity

When a user account is created, and the user logs in the very first time:

* Search for any entity instance where the email address is equal to the email address used for the user account
* Change the user ID with the user ID associated to that email address

Instead of the email address, you could ask anything else, as long as it is clear to the user that the entered value is requested when s/he creates an account to assign to her/his account any entity s/he creates. As the email address is required to create a user account, I would ask the email address to the anonymous users who creates entities.

# Answer
> 0 votes
In your entity property you can add option of author. Now if user is creating the entity then users id will be stored in author. So you dont need to do it with code.

---
Tags: entities
---


# Question
Title: How do I create taxonomy terms from an exploded list?
I have followed the procedure outlined on How to add multiple terms to a taxonomy reference field via feeds?

However, I'm unsure of what else to do in order to create taxonomy terms from a set of words imported via Feeds.

How should my content type be set up? I currently have the field set up as 'term reference' and have tried 'select list' and 'autocomplete' as widget type; neither displays any of the field data as a taxonomy term.

# Answer
> 2 votes
An important caveat thats missing from How to add multiple terms to a taxonomy reference field via feeds? is that the taxonomy terms already need to be defined in the vocabulary that you are referencing in order for feeds tamper to assign the term reference value to the node.

In the past I have created two feeds importers, one that is a taxonomy term processor that just contains the terms to load into the vocabulary, and one that is the node importer to import the nodes and have the taxonomy terms assigned to those nodes.

I may be wrong, but I dont believe that you can import nodes and simultaneously populate the taxonomy vocabulary in one step with feeds.

---
Tags: 7, taxonomy-terms, feeds
---


# Question
Title: How we can generate Latitude/Longitude at the time of import while using Feed module
I am using Feed Module For Importing Nodes Form CSV File. What i want that at the time of import how we can generate lat/long pair for every node imported. I have address in csv file for every node an i want to generate lat/long pairs.

# Answer
I use the location module in tandem with the location feeds module (http://drupal.org/project/location\_feeds). It can be configured to geocode the the addresses at the time of import.

I had to adjust some timeout settings as its possible to try to geocode addresses faster than the geocoding api allows.
> 1 votes

---
Tags: 7, feeds, importing-exporting
---


# Question
Title: How to merge more than one profile type within registration page?
So I am using profile2 module to create different types of user profiles

for example

* personal information profile
* contact information profile
* team profile - team role
* member profile - member role

contact information profile is a common profile (fields) between team user and member user

I created a registration page for each role using profile2 registration path module, in this module I can only create one registration path for each profile which will combine Drupal account fields with profile2 profile fields.

Current registration pages as follow:

* team profile registration page
* member profile registration page

Now I want to include/merge contact information profile fields with team and member profiles in the registration page without creating redundant fields for each profile.

Any helpful ideas

# Answer
> 0 votes
If you create fields for one profile, you can also use the same fields for another profile type.

When making the fields for the second type, rather than make new ones use the "Already Existing" Field to select the already made fields from a drop-down list.

This way both roles will fill in the same Contact Information since they both used the same fields for the task.

---
Tags: 7, users
---


title: making a custom page template

text:
# Question
Title: making a custom page template
I currently have a general template and a front page template. I made a custom node for a content type I made and it works just fine but then realized that I need an entirely new page template as well. I already made a page--\[content\_name\].tpl.php file and cleared the cache but it wasn't read. Is there something I need to change elsewhere or is what I'm doing completely off? Thank you.

# Answer
> 3 votes
For Drupal 6 -- `page-[content_type_name].tpl.php` and clear the cache.

For Drupal 7 -- http://www.digett.com/blog/01/11/2012/overriding-page-templates-content-type-drupal-7

# Answer
> 0 votes
You can do the same thing. means a different layout for specific content type using panels. Check the first answer : Panels for Node Types

---
Tags: theming, 7
---


# Question
Title: How to set conditional edit permissions on webforms?
I need to extend a Drupal6 based system. I'm not too familiar with it since I overtook administration from another group. It has a product registration system wich uses webforms and a custom module. The user have to be able to edit the their own submitted webform but only until the status is set to accepted.

I switched on permissions for users to edit their content, and it works fine, but I need to revoke this permission based on a field in the webform. When the field value is set to "new" or "pending" the user must be able to edit the content, but when the business owner sets that field to "accepted", the user shouldn't be able to edit that submission any more.

How can I catch user permissions and only let users edit certain content when I want?

# Answer
> 2 votes
Just place a hook\_form\_alter() or a hook\_form\_FORM\_ID\_alter() (just for your webform) in your module.

Then inside the code check that the webform status is valid before committing the update or redirect to to an error page.

---
Tags: 6, webforms, users
---


# Question
Title: How do i change the apachesolr index environment based on node values?
I have two apachesolr environment setup in my drupal instance. I want to index some nodes to one environment and some to the other, say based on some node values.

I could see that it always indexes to default the environment. I could see the possibility of indexing in two environments, but it is irrespective of the nodes value.

How can i achieve it?

**UPDATE:**

To give more detail, I am trying to achieve shards in apache solr in Drupal

**UPDATE - 17 DEC 2012**

*Modules used:*

***Reason on why i need node values***

* I have a large nodes of a particular entity type, This makes my index so large.

+ So Decided to go with shards with multiple indexes of the same node type.
* So based on the node size and its priority of the node or proximity of the nodes location or users location , I want to split up the index to separate cloud servers and index them.
* Proximity of the node also gives me power of separate out search indexes at a later stage.

# Answer
I do not know if it is possible to shard Drupal nodes into different Solr indexes based on arbitrary field values, I do however know it is possible at a node type level.

From the API documentation:

```
/**
 * This is invoked for each entity that is being inspected to be added to the
 * index. if any module returns TRUE, the entity is skipped for indexing.
 *
 * @param integer $entity_id
 * @param string $entity_type
 * @param integer $row
 *   A complete set of data from the indexing table.
 * @param string $env_id
 * @return boolean
 */
function hook_apachesolr_exclude($entity_id, $entity_type, $row, $env_id) {
  // Never index media entities to core_1.
  if ($entity_type == 'media' && $env_id == 'core_1') {
    return TRUE;
  }
  // Never index news entities to core_2.
  if ($entity_type == 'news' && $env_id == 'core_2') {
    return TRUE;
  }
  // Default to allow.
  return FALSE;
}

```

So all you would need to do is allow some node types to be indexed by one core, and allow some other node types to be indexed by another core.
> 3 votes

---
Tags: 7, search
---


title: Change menu link title dynamically?

text:
# Question
Title: Change menu link title dynamically?
I'm trying to alter the text of a menu item dynamically based upon certain variables.

I'm using hook\_menu\_alter like this:

```
function mymodule_menu_alter(&$items) {
  $items['toggle-review-process']['title'] = 'asdf';
}

```

Problem is, it does nothing. That menu entry is in there, but it has no title normally, and adding the key isn't doing anything. How can I change the text of this menu item dynamically?

# Answer
> 3 votes
Be sure too understand how the menu system works. The menu structure is only build once every time the cache is cleared. It is at that moment that `hook_menu_alter()` will be called. The results are then stored in the database. So simply implementing this hook is not sufficient to create dynamic menu titles. You can use it though to add a title callback that will be called every time a link to the menu item will be rendered. For details have a look at http://drupal.org/node/140311 (D6, but basic logic still applies to D7).

From the top of my head:

```
function mymodule_menu_alter(&$items) {
    $items['toggle-review-process']['title callback'] = 'mymodule_title_callback';
    $items['toggle-review-process']['title arguments'] = array(1, 'some string');
}

function mymodule_title_callback($arg1, $arg2) {
    $title = 'create the title';
    return $title;
}

```

# Answer
> 2 votes
If it is a menu item that you defined in `hook_menu()` then you can simply add a `title callback` declaration and, if necessary, `title arguments` to pass to it.

If the menu item was created elsewhere, I've found that implementing `hook_preprocess()` allows you to alter the menu text through the mammoth `$variables` array.

This will only work for menu items on uncached pages; otherwise the first title displayed is cached along with the page.

# Answer
> 1 votes
To create / change dynamic menu you could use Menu Token module.

> Menu Token module provides tokens, that could be used in title or in path of menu items (links). For example, if you create a menu item with path: "user/\[current-user:uid\]", the url will be changed "on fly" to: "user/1" (assuming you are user 1).

It has dependency on the Token module.

---
Tags: 7, routes
---


# Question
Title: Webforms - '[+] Add more fields' (up to 5) button to file upload form control
I managed to add fields to submit attachments in a webform. Now all I need is to restyle them to only allow one upload per charge plus a 'add more button'. I need to restyle the 1 into 2.

How can this easily achieved?

# Answer
Have you checked this Webform Add module ?

> Webform Add More enables selected fieldsets to be initially hidden and progressively shown with an Add more button, mimicking CCK multiple fields.
> 1 votes

# Answer
I found a solution which relies on javascript, here below is the skeleton:

```
    $("#edit-submitted-file-ajax-wrapper").after('<a id="addmore" href=#>[+] Add more</a>');
          //this vars are available inside bind function due to js scope
          var c = 1;//counter
          var wrapper_to_clone;
          $('#addmore').bind('click', function(e) {
            //clone filed and change attributes
            wrapper_to_clone = $("#edit-submitted-file-ajax-wrapper");
            field_to_clone = $("#edit-submitted-file-ajax-wrapper input");
            wrapper_to_clone.clone().attr('id', 'edit-submitted-file' + c + '-ajax-wrapper').insertAfter(wrapper_to_clone);
            //here you need to rename the attributes of children
            ...
            ++c;

            if (c == 5) {
              return false;
            }
     });

```
> 0 votes

---
Tags: webforms
---


# Question
Title: _preprocess_views_view__ specify view name
I have a view named "taxonomy\_term\_custom." The preprocess code below works to do some specific stuff for this view, but I would like to override the hook like this:

```
function mywebsite_glue_preprocess_views_view__taxonomy_term_custom(&$vars) {
}

```

Is this possible?

```
function mywebsite_glue_preprocess_views_view(&$vars) {
  if($vars['view']->name == 'taxonomy_term_custom'){
    dpm($vars);
    // do stuff
  }
}

```

# Answer
> 5 votes
In Drupal 7 this preprocess function will not automatically get picked up as it did in Drupal 6. There is a workaround posted here if you want the same behaviour as Drupal 6. For the issue.

# Answer
> 5 votes
Just call preprocess for each view.

```
function mywebsite_glue_preprocess_views_view(&$vars) {
  $function_name = __FUNCTION__ . '__' . $vars['view']->name;
  if (function_exists($function_name)) {
    $function_name($vars);
  }
}

function mywebsite_glue_preprocess_views_view__taxonomy_term_custom(&$vars) {
  dpm($vars);
  // do stuff
}

```

# Answer
> 0 votes
Sure, that depends on which version of Drupal you are using though. Watch out for this issue. It says that you can't have a views preprocess function unless you have a corresponding tpl file.

---
Tags: views, theming
---


# Question
Title: Ajax on a webform affecting comment form and user-registration form
I have Ajaxified a webform using a (`hook`) custom module. The code used is:

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

    //see if webform_client_form_ is in the form_id

    if(strstr($form_id, 'webform_client_form_')) {

      //get the nid so we can use it in the wrapper value

       $nid = $form['#node']->nid;

        $form['actions']['submit']['#ajax'] = array(
            'callback' => 'alterwebform_webform_js_submit',
            'wrapper' => 'webform-client-form-' . $nid,
            'method' => 'replace',
            'effect' => 'fade',
     );

  $form['#validate'] []='alterwebform_test';
      }
    }

```

The code in the **callback function** is:

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

  // define the $sid variable (submission id from webform)
    $sid = $form_state['values']['details']['sid'];

 // sid to know the form was properly submitted

    if ($sid) {

  //load up the webform node object

     $node = node_load($form_state['values']['details']['nid']);

  //create an array with the confirmation message of webform
        $confirmation = array(
                 '#type' => 'markup',
                 '#markup' => check_markup($node->webform['confirmation'], $node->webform['confirmation_format'], '', TRUE),
                     );

  // return the confirmation message
    return $confirmation;
    }
  else {
   // return the form
       return $form;
        }
    }

```

The web-form works fine . The problem is: The AJAX code above is affecting other forms (Comments form and User Register form).

> How is it affecting ?

If other (comment and user-register) forms are submitted successfully in the first time then its fine. But if there is some error in the first time and we submit second time, then click on submit does not perform any action but show ajax effect.

The click on submit button now shows ajax kind of affect but is without any action.

As you can see in the picture, the ajax affect comes in this form. This happens if someone is clicking the button the second time (because of some error on first time).

What could be the possible reason for this and how should I fix this? Thank you in advance.

# Answer
The problem can be that ajax functionality is attached to button by its id attribute. Seems all three buttons - for webform, comment and user-register have the same id "edit-submit".

To fix this - just add unique id for webform submit button.

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

//see if webform_client_form_ is in the form_id
if(strstr($form_id, 'webform_client_form_')) {

  //get the nid so we can use it in the wrapper value
   $nid = $form['#node']->nid;

    $form['actions']['submit']['#ajax'] = array(
        'callback' => 'alterwebform_webform_js_submit',
        'wrapper' => 'webform-client-form-' . $nid,
        'method' => 'replace',
        'effect' => 'fade',

    );
    // Add unique id for submit button.
    $form['actions']['submit']['#id'] = 'webform-client-form-submit-' . $nid;

    $form['#validate'] []='alterwebform_test';
  }
}

```
> 1 votes

---
Tags: ajax, webforms, forms
---


title: Profile2 Statistics

text:
# Question
Title: Profile2 Statistics
Is there any module that would help me to see statistics and also use them as filter/sorting criteria in views of profile2 pages ? I mean as is the core module statistics and i can add filters like content:total views or anything similar ,is there a module which offers the same data ?

# Answer
You can try user visits module.

The user Visits module tracks visits and referer from other users on a user's profile page. It displays the latest visitors on a user's profile page and provides two blocks one with the latest visitors on a user's profile page and one with the latest visitors on own profile page.

You can create your own module to filter afterwards using the data provided by the above module.

Check this mdoule also User visits Advanced
> 0 votes

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


# Question
Title: YourTheme_links doesn't work on sub theme
I have tried the way described in http://api.drupal.org/api/drupal/includes%21theme.inc/function/theme\_link/7#comment-24463

But as it seems it works on the main theme but not on a subtheme.

```
function MYTHEME_link($variables) {
    print_r($variables);
    die;
}

```

Yeilds no result.

Applied on Zen theme which results the menus.

But on a subtheme it shows nothing. Anyone knows why?

# Answer
> 0 votes
I believe it is a typo, the function should be `MYTHEME_link` and not `MYTHEME_links`.Possible other ways to identify is use theme engine `phptemplate_link` instead of your theme name.

Try clearing your theme registry. Also Check whether you have spelled your theme machine name correctly.

```
function MYTHEME_link($variables) {
    print_r($variables);
    die;
}

```

---
Tags: navigation
---


title: how can i add classes to the content

text:
# Question
Title: how can i add classes to the content
I'm trying to add class to the content, however its not adding anything

```
    function themename_preprocess_page(&$vars) {
      $is_sidebar_first_or_second= (empty($vars['page']['sidebar_first'])) || (empty($vars['page']['sidebar_second']));
      $is_sidebar_first_and_second= (empty($vars['page']['sidebar_first'])) && (empty($vars['page']['sidebar_second']));
      if ($is_sidebar_first_or_second) {
        $vars['page']['content']['#theme_wrappers'][0] .= ' one-sidebar';
      }

      if ($is_sidebar_first_and_second) {
        $vars['page']['content']['#region'] .= ' two-sidebar';
      }

    }

```

can anyone help me on this?

# Answer
Have you tried this code ? I have taken it from here

```
// Add information about the number of sidebars.
  if (!empty($variables['page']['sidebar_first']) && !empty($variables['page']['sidebar_second'])) {
    $variables['classes_array'][] = 'two-sidebars';
  }
  elseif (!empty($variables['page']['sidebar_first'])) {
    $variables['classes_array'][] = 'one-sidebar sidebar-first';
  }
  elseif (!empty($variables['page']['sidebar_second'])) {
    $variables['classes_array'][] = 'one-sidebar sidebar-second';
  }
  else {
    $variables['classes_array'][] = 'no-sidebars';
  }

```
> 3 votes

---
Tags: 7, theming
---


title: Module to display blank theme template

text:
# Question
Title: Module to display blank theme template
I am creating a module with a map displaying markers. Do I need to create a page/ node or can I load the drupal theme without any page / node content and add my code.

```
<?php /**
 * Implementation of hook_menu.
 */
function projects_map_menu() {
  $items = array();

  $items['projects-on-map'] = array(
    'title' => 'Projects on Map',
    'page callback' => 'projects_map_page',
    'access callback' => 'user_access',
    'access argument' => array('access nodes'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Page callback
 */
function projects_map_page() {
//render them current theme
//custom code
}

```

# Answer
It is possible to create this functionality using the Geolocation Views module. Here is a quote about it (from the module's project page):

> ... is sub-module for Geolocation Field to display markers on Google Map using Views 3.
>
> Module support:
>
> * show content in Info Windows
> * custom marker images
> * markers as links
> * multiple maps on a single page
> * support MarkerClusterer
> 0 votes

---
Tags: 7, routes
---


title: Drupal 7 force active menu item

text:
# Question
Title: Drupal 7 force active menu item
I got a page where I link to in the menu bar. On this page there is a custom module. On this page there are items from anothor database where the user can click on. When they click on it they go to another page with more information. When they are on the second page there is no active button in the menu bar. On the second page I also have a custom module.

How can u force a button in the menu bar to have the .active class or in another way so that it haves the active lay-out button.

I use Drupal 7.

# Answer
> 1 votes
The Menu position module will solve your problem.

> Often times site builders want certain types of content to appear in a specific position in the navigational menu. The simplest solution, adding all of that content individually to the menu system, has performance and usability issues. (Imagine hundreds of menu items added to one spot in the menu.)
>
> This module allows for the creation of rules that will dynamically add the current page into the menu system at the requested spots.

# Answer
> 1 votes
You can use http://drupal.org/project/context to set an active menu.

> Context allows you to manage contextual conditions and reactions for different portions of your site.

Or use the API http://api.drupal.org/api/drupal/includes!menu.inc/function/menu\_tree\_set\_path/7

---
Tags: 7, routes
---


# Question
Title: How to convert a stdClass object to a SimpleXMLElement object
I have a JSON file from a web service and want to use this data with a Drupal module. However, this module expects XML data. So I have the idea of overwriting the module. To do this, I need to convert the JSON file in XML, and ensure the file changes from JSON to PHP array.

Does any method or library exist to do this or convert .json file to .xml directly?

Now I have an array that is like the following one:

```
Array(
  [0] => stdClass Object(
    [sponsor] => stdClass Object(
      [created_at] =>
    )
  )
)

```

I need to convert this array in:

```
SimpleXMLElement Object(
  [@attributes] => Array(
    [type] => Array(
      [sponsor] => Array(
        [0] => SimpleXMLElement Object(
          [created-at] =>
        )
      )
    )
  )
)

```

# Answer
> 1 votes
Using the XML Serializer package, you can use the following code to make the conversion, as reported in this answer on Stack Overflow.

```
function json_to_xml($json) {
  $serializer = new XML_Serializer();
  $obj = json_decode($json);

  if ($serializer->serialize($obj)) {
    return $serializer->getSerializedData();
  }
  else {
    return NULL;
  }
}

```

Alternatively, you can use the following code give in this answer for the same question.

```
require_once 'XML/Serializer.php';

$data = json_decode($json, true)

// An array of serializer options.
$serializer_options = array (
  'addDecl' => TRUE,
  'encoding' => 'ISO-8859-1',
  'indent' => '  ',
  'rootName' => 'json',
  'mode' => 'simplexml'
);

$Serializer = &new XML_Serializer($serializer_options);
$status = $Serializer->serialize($data);

if (PEAR::isError($status)) {
  die($status->getMessage());
}

echo '<pre>';
echo htmlspecialchars($Serializer->getSerializedData());
echo '</pre>';

```

# Answer
> 1 votes
I had a similar issue where I wanted to mock away a `SoapClient` and verify the web service payloads generated by our system. I tried working with `SimpleXMLElement` to parse prepared XML snippets (requests and response) but had several issues with that and ended up writing my own stuff in the end.

https://github.com/FredrikWendt/php-xml-sax-stdclass

(It doesn't handle XML node attributes at all but turned out useful although `SoapClient` can't be mocked by Phockito.)

---
Tags: 7
---


# Question
Title: How to auto resize the height of an iframe with Jquery?
Any idea on how to automatically resize the height of an iframe based on its content.

The iframe source is coming from different domain.

Any thoughts on how to achieved it via Jquery or native JS?

Thanks

**UPDATE: This script addressed my needs.**

```
Drupal.behaviors.cnngomobile = function (context) {
    $(window).bind('load', function(){
        var adsIframe = document.getElementById("303799");
        if (adsIframe) {
          var style = adsIframe.contentWindow.document.createElement("link");
          // create <link>
          var host = "http://"+location.host+"/sites/all/themes/cnngomobile/css/style-iframe.css";
          style.setAttribute("href", host);
          style.setAttribute("rel", "stylesheet");
          style.setAttribute("type", "text/css");
          // append
          adsIframe.contentWindow.document.head.appendChild(style);
        }
    });
  };

```

# Answer
I have implemented automatic iframe resizing using the cross-domain messaging ability of HTML5's window.postMessage() API. Required reading: http://davidwalsh.name/window-postmessage, http://drupal.org/node/756722.

Example:

```
// "Sending" side (iframe)
Drupal.behaviors.yourIframeUpdateBehavior = {}
Drupal.behaviors.yourIframeUpdateBehavior.attach(context, settings) = {
  var data = {
    'bodyWidth':jQuery('body').width(),
    'bodyHeight':jQuery('body').height()
  }
  var domain = '*'; // Send to any domain.

  // Send current document dimensions to any parent of iframe
  parent.postMessage(data, domain);

  return false;
}

// "Receiving" side (iframe parent)
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
  $(window).bind('message', function(event) {
    var frameWidthPx = event.originalEvent.data.bodyWidth+'px';
    var frameHeightPx = event.originalEvent.data.bodyHeight+'px';
    $("#frame_id").width(frameWidthPx);
    $("#frame_id").height(frameHeightPx);
  });
});
// ]]></script>

```
> 3 votes

# Answer
But in the past i use this plugin http://www.lost-in-code.com/programming/jquery-auto-iframe-height/
> 1 votes

# Answer
hmmn... aren't you able to set the width or height of the iframe using simple jquery like

```
$('iframe-id').width('xxxpx');
$('iframe-id').height('xxxpx');

```

or does the complication lie in the type of data you have in iframe and the logic to determine the width and height of the iframe...kindly elaborate...
> 1 votes

# Answer
Hello i like how it is down here- iframe toolbar

Actually i dont wat to add a toolbar thinking of it i just want to give my iframes which are in pages auto height. I dont understand how to implement the porthole. Actually just like ninja. Could anyone point us in the right direction?

Thanks
> 0 votes

---
Tags: ajax, javascript
---


# Question
Title: How can I show a block only on the edit page for a specific content type?
I have a block that I would like to display on the edit page for a specific content type. Since the content of this block describes the site policy for editing that specific content type, I only want users to see it when editing nodes of that content type.

I tried setting the block display path to `node/*/edit*` and checking the appropriate content type on the block display menu, but that didn't work.

# Answer
> 0 votes
I discovered the source of the problem: the block was set to the wrong language, so I wasn't able to see it even though the path (`node/*/edit*`) was correct. Setting the block to the correct language allowed me to use the path `node/*/edit*`.

# Answer
> 1 votes
You could implement hook\_block\_list\_alter() to alter the status of the block. (Replace `$bid` with the block ID, and `$content_type` with the content type you are interested to.)

```
function mymodule_block_list_alter(&$blocks) {
  if (!empty($blocks[$bid]) && ($node = menu_get_object()) && arg(2) == 'edit' && $node->type == $content_type) {
    $blocks[$bid]->status = 1;
  }
}

```

---
Tags: blocks
---


# Question
Title: How to Extract Label of a Field, which is inside FieldCollection?
I have a field collection with the name 'field\_stk\_fld1'.

Inside this field collection('field\_stk\_fld1') there is a field with name 'field\_fld\_stk\_ques1'.

I wanted to extract label of the field ('field\_fld\_stk\_ques1'), Any idea on how to get it?

Note: This field ('field\_fld\_stk\_ques1') is used in multiple places and in each place it has its own label associated.

# Answer
This should do it:

```
$entity_type = 'field_collection_item';
$bundle_name = 'field_some_field'; // Field name the collection is attached to
$field_name = 'field_some_other_field'; // Field name within the field collection

$info = field_info_instance($entity_type, $field_name, $bundle_name);

if ($info) {
  $label = $info['label'];
}

```
> 2 votes

---
Tags: entities
---