# Question
Title: Contextual links for programmatically embedded views
When embedding a View programmatically, using views\_embed\_view, what can I do to have the contextual menu (gear icon) appear over its area?

# Answer
> 2 votes
Views does this by wrapping the render array output with the views\_add\_block\_contextual\_links() function. It checks if the display plugin has contextual links associated with it. If the $display\_id is a block then it will have the contextual links.

```
  if ($view = views_get_view($name)) {
    if ($view->access($display_id)) {
      $output = $view->execute_display($display_id);
      // Before returning the block output, convert it to a renderable array
      // with contextual links.
      views_add_block_contextual_links($output, $view, $display_id);
      $view->destroy();
      return $output;
    }
    $view->destroy();
  }

```

You already understand the $name and $display\_id. The output from this needs the render() function. You can put this in a function that is called in TEMPLATE\_preprocess\_node(), for example, and then use `print render($embedded_view)` in the node.tpl.php template.

---
Tags: views
---


# Question
Title: Panels + Recaptcha : how to add a (re)Captcha in my panels view?
I've just installed Panels 3.1 on my D7 website.

There is no options to add a Recaptcha form on my Panels view.

Where should I find that ?

Thank you,

# Answer
> 1 votes
You don't usually add a recaptcha directly to Panels; you'll want to add it to the appropriate form(s) (comment, registration, etc.) When you do so, adding the appropriate form in Panels should automatically pull in the recaptcha as well.

---
Tags: 7, panels, captcha
---


# Question
Title: Alter/insert into the links variable in a field_collection
I am currently working with the Field Collection module, but I have stumbled into a small problem.

I am trying to alter the links variable (currently there is Edit & Delete links) on a field\_collection, as I want to add a link to it. I believe I have tried everything, such as `hook_entity_view_alter()`, or a preprocess function, but nothing seems to work.

Is there a way to solve this, without hacking core?

# Answer
> 2 votes
In a custom module you can use hook\_field\_attach\_view\_alter(). In this example I'm using the distribution profile eRecruiter so there is a bundle called resume with several field collections and in an entity type profile2. Every time there is a field attached to a field collection this hook is fired recursively but the links are not contained there.

```
/**
* Implements hook_field_attach_view_alter()
*
* @param mixed $output
* @param mixed $context
*/
function helper_field_attach_view_alter(&$output, $context) {
  if ($output['#entity_type'] == 'profile2' && $output['#bundle'] == 'resume') {
    $f = 'do stuff here';
  }
}

```

So you understand how the links work here is some of the code used in field\_collection.module.

The links are created in a render array. Don't worry about 'links\__field\_collection\_view' too much because it doesn't do anything. When the #theme function is called more familiarly as theme('link\__field\_collection\_view', $variables) it looks first for TEMPLATE\_link\__field\_collection\_view(&$variables) or link--field-collection-view.tpl.php however if it doesn't find it, it will use as it does in this case theme\_links();

```
  $links = array(
    '#theme' => 'links__field_collection_view',
  );
  $links['#attributes']['class'][] = 'field-collection-view-links';
  foreach (array('edit', 'delete') as $op) {
    if ($settings[$op] && field_collection_item_access($op == 'edit' ? 'update' : $op, $field_collection)) {
      $links['#links'][$op] = array(
        'title' => $settings[$op],
        'href' => $field_collection->path() . '/' . $op,
        'query' => drupal_get_destination(),
      );
    }
  }

```

hook\_admin\_paths() is used to make the links rendered in the dialog window.

```
function field_collection_admin_paths() {
  if (variable_get('node_admin_theme')) {
    return array(
      'field-collection/*/*/edit' => TRUE,
      'field-collection/*/*/delete' => TRUE,
      'field-collection/*/add/*/*' => TRUE,
    );
  }
}

```

hook\_menu() is set up for the link callback in this case the edit link

```
  $items[$path . '/%field_collection_item/edit'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('field_collection_item_form', $count),
    'access callback' => 'field_collection_item_access',
    'access arguments' => array('update', $count),
    'title' => 'Edit',
    'type' => MENU_LOCAL_TASK,
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
    'file' => 'field_collection.pages.inc',
  );

```

---
Tags: navigation, entities
---


# Question
Title: Uploading images into separate directories for every new content
My page, created using Drupal 7, will contain multiple galleries. I created new "Content Type" - "gallery" with an unlimited numer of "Image" fields. For each content of this type I want all of its images to be placed under different directory, eg. sites/default/files/gallery\_01, sites/default/files/gallery\_02, etc.

There is a "File directory" setting but I don't know how to make it content-dependent (when I create new content I want all uploaded images to be placed in a different directory).

Is there any way I can accomplish this ?

# Answer
Why you would want to do that, I don't know. However, you can use Filefield Paths module with tokens. If you use the timestamp token you can have each directory created named based on timestamp. That will make them unique.
> 2 votes

---
Tags: media, files
---


title: Drupal 7 Site for Displaying PPT or JPG

text:
# Question
Title: Drupal 7 Site for Displaying PPT or JPG
I am relatively new to Drupal and am about to develop a tribute site. It will have a few informational pages but it's main focus is photographs.

There are about 150 photographs which have been sorted into about 10 categories. I have these in raw form, and also in a powerpoint deck. My preference would be to display the photos individually, but I'll use the powerpoint if it proves too difficult.

Ideally users would be able to navigate to a category of photos, then flick through them one at a time, or 'play' a slideshow. Also, if it was not too difficult, I'd like to annotate some or all of the photos.

Where should I start with this? I have installed Drupal 7 but see there is a wide range of modules and approaches for displaying photos. I have experience with CSS, jQuery and PHP...

Any pointers much appreciated!

# Answer
> 1 votes
There are many, many ways to do this in Drupal but I'll outline two basic approaches for D7.

First, you'll definitely have a much easier time working with .jpg than .ppt. As Drupal is open source, it supports open file formats (jpg) much better than proprietary ones (ppt).

Warning: this is not a complete tutorial; writing one would have far too many steps and is out of scope for this site.

**APPROACH 1**

Views Slideshow: This relies on the Views module. If you're new to Drupal, you should definitely learn how to use Views first; Node One has an excellent tutorial on Views. Using Views slideshow, you would roughly do the following:

* Create a content type for your images.
* Create a vocabulary **Categories** using the Taxonomy module and add each individual category as a term.
* Create a node of content type *image* for each picture.
* Configure Views Slideshow to show each gallery on its own page.

Why use this approach? Each picture will be its own node. This allows you to later add different fields to each picture such as a rating (with Fivestar) or the name of the photographer, etc.

**APPROACH 2**

Field Slideshow: This approach allows you to store all of the pictures for each gallery on a single node. To do this:

* Create a content type for galleries and add a field to hold the pictures. Make sure it allows for multiple values.
* Create a node of content type *gallery* for each category.
* Configure Field Slideshow.

Why use this approach? It is somewhat simpler to set up and requires less tinkering with Views. However, it is less flexible.

---
Tags: media
---


# Question
Title: How can I best display code examples on my site?
I'm doing some PHP code examples for a class in a fancy Drupal site.

I have a "Code" content type. I have a "field\_php" that gets processed on the actual node.
I have a view that uses "node/%/code" to display the code formatted via Geshi:

* View PHP Body: Link back to node/1
* View PHP footer: PHP code to pull geshi formatted "field\_php"

```
<?php
  include_once('sites/all/libraries/geshi/geshi.php');

  $page = $view->args[0];
  $node = menu_get_item("node/$page");

  $source = $node['page_arguments'][0]->field_php['und'][0]['value'];
  $language = 'php';
  $geshi = new GeSHi($source, $language);

  echo $geshi->parse_code();
?>

```

**LASTLY** I have a node--code.tpl.php edited to include a "View Code" link at the top of each "code" page. The include\_once/echo at the top is the following:

```
<div class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
  <?php
    include_once('sites/wernercd.php/public/~functions.php');
    echo "<a href=\"" . curPageURL() . "/code\">Code For You!</a>";
  ?>
  <?php if (!$label_hidden) : ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:
    </div>
  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <div class="field-item even"<?php print $item_attributes[0]; ?>><?php print render($items[0]); ?></div>
  </div>
</div>

```

http://mysite.com/node/1

http://mysite.com/node/1/code

I don't know why, but I feel like I'm doing it wrong. It works like I want it, but I just feel like its the "wrong" way to go about doing it.

What would the "recommended" way of getting this desired output be? How could I change this to catch issues unforseen by my naivete?

# Answer
> 3 votes
I would set up an input format for code and set the field\_php to use that. The code input format could use a filter like this http://drupal.org/project/codefilter

# Answer
> 1 votes
From reading what I understand is that you want to post code on your site. And when you are trying to post code on your site, instead of showing it as it is, Drupal is parsing it. If this is the problem you are facing, then I think code highlighting or code formatting scripts are what you need.

For example, if you want to place some PHP code in your code but don't want drupal to parse it. Then you can use syntax highlight library which will work great for you. Check this out: http://www.amitavroy.com/justread/content/articles/present-your-code-better-code-syntax-highlighter

# Answer
> 0 votes
I'm not really answering your question - more discussing some approaches that might interest you.

Keeping the code in the field seems reasonable to me.

Instead of using a view and templates, I would use hook\_nodeapi (or the Drupal 7 equivalent) to add the link to the content object. The link url would be in the node/\[nid\]/code format.

I'd then create a theme template using hook\_theme (something like theme\_nodecode)

I would then use hook\_menu\_alter to add a node/%node/code menu item, with a callback of mymodule\_node\_display\_code or something like that. That callback would do any preflight (like checking for geshi module for example), then call the theme function to render the code.

There's lots of approaches to what you're doing, but hopefully this gives you some ideas.

---
Tags: 7
---


# Question
Title: Modifying the default user registration page
I previously asked this question about modifying the default user registration form. The default form is largely fine, I just want to add some text and some links above and below the form (i.e. instructional advice etc).

One of the answers to my previous question suggested creating a module with the hook `form_alter`. I did this, however, it seemed all that achieved was adding adding new text fields to the form. I don't want to add new text fields, just some additional text/html before and after the form.

Is there any way to do this with `form_alter`, and if so, could you detail the code I'd need to do this (such that is does not add another user visible field)?

If there's another way to modify the page directly (not just the form) could you detail it? Keep in mind I want this to work with all themes, so when I change themes my changes do not disappear (which is why I was hoping to be able to do it in a module).

# Answer
> 1 votes
I use this way to custom my user login page, I think u can also custom form and use same validate/submit function like user\_register\_form did

```
$form['#validate'][] = 'user_register_validate';
$form['#submit'][] = 'user_register_submit';

```

---
Tags: 7, hooks
---


title: Multiple taxonomy/term/% views

text:
# Question
Title: Multiple taxonomy/term/% views
I am using Views 3. is it possible to have multiple taxonomy/term/% view? That's because i need different theme for every vocabulary

# Answer
Use Page manager and Panels, this allows you to use different Views, and much for each vocabulary.

1. Enable the Page Manager and Panels.
2. Enable the term template
3. Create a variant of type "Panel", add to it a selection rule on the vocabulary.
4. Place View that you want to use in a suitable location.
5. Save
> 1 votes

# Answer
Sounds like a job for the Taxonomy Views Integrator module. It allows selective overriding of taxonomy terms and/or vocabulary with the view of your choice.
> 2 votes

---
Tags: 7, views
---


# Question
Title: Updating a modified image file across entities using it
I have a content type named "Affiliate" which has among others a field storing a logotype image. The image is then displayed in a ticker (jCarousel) using a dedicated image style.

After I created one node and attached a logotype to it, I made several copies of that node, differing in text, but sharing same image. I was aware of situations where a logotype has to change but thought that solution would be "scalable" due to the fact that the image reference is shared. Now - kaboom! - the image has to be replaced with a new version. I thought I'd get away if I replaced the original image on the server and then deleted the derivative styled copies from the `styles` directory to make Drupal recreate them afresh. No go.

The problem is that the new image is used but with old dimensions (both in the node display and ticker), which causes distortions. I have to relink the node with the image, one by one to make it notice the new dimensions. Is the size of the original image stored somewhere in the node? What is the sneakiest way to go in such situations?

# Answer
> 0 votes
The image width and height are stored in the field tables (`field_data_FIELD_NAME`/`field_revision_FIELD_NAME`), in the `FIELD_NAME_height` and `FIELD_NAME_width` columns.

If you know the file id (fid) of the file you need to change the data for, and the width and height of your new image, you can just run the following queries against the database:

```
UPDATE field_data_FIELD_NAME
SET FIELD_NAME_width = WIDTH, FIELD_NAME_HEIGHT = HEIGHT
WHERE FIELD_NAME_fid = FID

UPDATE field_revision_FIELD_NAME
SET FIELD_NAME_width = WIDTH, FIELD_NAME_HEIGHT = HEIGHT
WHERE FIELD_NAME_fid = FID

```

---
Tags: media, files
---


# Question
Title: Does "exclude from display" on views affect performance?
I really wonder if it differs in calculation time to exclude an item from display.

For example:

I have 500 rows in a view. Each row has two fields: title and author.

Does generating the same view with excluded "author" field takes the same time as displaying "author field"?

# Answer
> 3 votes
You should profile this and see. It totally depends on your system.

Install the Devel and Performance modules. Then enable the **Query log** (in the D7 version it is at "admin/config/development/devel"). Visit some view pages, and look at the queries at the bottom of the page. Tweak your views and re-run. Just be sure to disable caching (including MySQL query caching) when you do this, as it may skew results.

You can also copy/paste the SQL from the view config page (enable from "admin/structure/views/settings"), into Query Browser or another tool and look at the execution time. If you do this, bypass the query cache, to make sure you get accurate results.

Also keep in mind that buffer sizes, etc, can affect results since data may or may not need to be read from disk. You should really have an optimized MySQL instance before you profile.

---
Tags: views, performance
---


# Question
Title: Up to how many nodes Drupal can handle without affecting performance?
Is there a kind of known number of nodes Drupal can handle without visible performance down?

I suppose the more nodes we have on a site the slower it will load pages. However does it matter if the number of the nodes is like a couple of thousands?

# Answer
It very much depends on your hosting and server configuration.

For example one of the projects I worked on handled without performance issues about 10 millions of nodes. But it lived on a cluster of 4 dual-core servers with lots of memory on each, and the cluster was behind load balancer and reverse proxy caching (Varnish).

On another project I had performance issues after something like 1000 of nodes, that was a shared hosting.
> 2 votes

---
Tags: 6, performance
---


title: Displaying geo data on openlayers

text:
# Question
Title: Displaying geo data on openlayers
Is there any module I can use to display limited points on OpenLayers using bbox-filtering in Drupal?

# Answer
> 2 votes
try http://drupal.org/project/views\_geojson

with the latest version of views\_geojson and openlayers you can define a view (of type geojson) that accepts a bounding box as a parameter.

With openlayers you can set the layer to use a bbox strategy so when you drag the map around it will send the bbox coords to the geojson view and just return points within that area.

I am new to Drupal and Im not going to lie this was a bit of a bastard to setup because there is not much documentation. I couldn't get the bbox contextual filter to work so I setup a custom filter that used top,bottom,left,right then wrote a rewrite rule in an .htaccess file that split the default parameter passed from the openlayers front end (a GET variable like BBOX=42,124,43,125) into the four filter parameters. This will NOT work if you expect your map to cross the equator or 0 meridian. But it works for me and I still hope to get contextual filters working at somepoint.

# Answer
> 0 votes
I would think you'd simply define this in the OpenLayers config admin/structure/openlayers/maps however, I didn't find it unfortunately. I think it's somewhere buried in the config options though.

---
Tags: location, google-maps, javascript
---


# Question
Title: Slow loading of text in WYSIWYG with TinyMCE 3.5 in Chrome Browser
On an node edit page with WYSIWYG (TinyMCE) it takes over a second for the text to show up, see this video.

FireFox doesn't seem to have this issue. Has anyone chrome across this?

# Answer
turned out to be an issue with CSS\_Injector module, this is the fix.
> 1 votes

---
Tags: 7, wysiwyg
---


# Question
Title: How can I display lots of rows of information from a database in my drupal module?
In the example\_page I believe it shows something like this:

```
function foo() {
    return array('#markup' => t('bar'));
}

```

And the function foo would be used for a page callback in the menu hook to create a page. However, In my module I plan on using a db\_query to access a database table and with it display many rows of data.

Is there a better way to do this than stuffing all of my output into #markup? It could be done with lots of concatenation, but it would be rather messy and it seems like there should be a better way.

# Answer
If you're looking to build an HTML table then the `theme_table()` function will help a lot. See the docs page for full details but this is a basic example:

```
function MYMODULE_page_callback() {
  // Header for the table
  $header = array('id', 'name');

  // Get your data
  $data = db_query('SELECT id, name FROM {my_table}')->fetchAllKeyed();

  // Loop through the data and add rows to the table
  $rows = array();
  foreach ($data as $id => $name) {
    $rows[] = array(
      $id,
      $name
    );
  }

  // Return the themed table
  return theme('table', array('header' => $header, 'rows' => $rows));

  // You could also use:
  return array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows
  );
}

```
> 2 votes

---
Tags: database, 7
---


# Question
Title: Module to add keyword search capability to content admin page?
Is there any module or technique for D7 that can provide this functionality?

# Answer
The Admin VBO Views module provides a complementary content admin page, with a search by title (and other fields) enabled by default.

It wouldn't take much to edit the View provided by that module to provide further exposed filters to search the content with.
> 1 votes

---
Tags: 7, search, nodes, users
---


# Question
Title: Installation profiles: add module/theme search path?
I'm trying to create a "base" installation profile with the modules and settings i need for every project which the specific project-profiles should derive from. It's no problem to run the install-part of my basic profile, but is there a way to use modules and themes that are stored in the 1st profiles folder?

# Answer
> 0 votes
Currently, there is no way to "inherit" that way between profiles. My team uses a small script that symlinks the modules directory from the base profiles into the modules dir of the subprofile, to solve this.

So the structure becomes

```
profiles/base-profile/modules
profiles/base-profile/modules/ctools
profiles/sub-profiles/modules/modules         <-- Symlink to base-profile/modules
profiles/sub-profiles/modules/modules/ctools  <-- From symlink
profiles/sub-profiles/modules/views

```

---
Tags: distributions
---


title: How to replace value of text box?

text:
# Question
Title: How to replace value of text box?
I have 2 input fields in my drupal form. When end user inserts some value in first input, I want to auto insert the second input field. How can I achieve this.

Here is my code.

input form element 1

```
// total fee of the payment schedule
    $form['fee'] = array(
        '#type' => 'textfield',
        '#title' => 'Fee Amount:',
        '#default_value' => (isset($fee_details->fee)) ? $fee_details->fee : '',
        '#maxlength' => 5,
        '#required' => TRUE,
        '#description' => t('Fee amount'),
        '#id' => "fee",
        '#element_validate' => array('element_validate_integer'),
'#ajax' => array(
            'callback' => 'replace_fee_instalment',
  'wrapper' => 'replace_textfield_div',
),
    );

```

Input field 2nd is

```
 $form['amount'] = array(
    '#type' => 'textfield',
    '#title' => t('Instalment'),
    '#title_display' => 'invisible',
    '#default_value' => ($amount) ? $amount : '',
        '#maxlength' => 5,
        '#element_validate' => array('element_validate_integer'),
  );

```

# Answer
> 1 votes
I think u need to use javascript for this. on the keypress event handler for the first textbox, u can get the text of the first textbox and update the second textbox using javascript itself

---
Tags: forms, input-formats
---


# Question
Title: Convert an already created custom content type into a new module
Is there a tool that automates (or helps) the creation of a module based on a current custom content type ? I have two new content types (forms) created using the Drupal user interface, now I realize I need to customize it further and would like to create a module to pack them all. Since I already done a lot of work building the (big) forms I was wandering if there is some kind of trick (or module) to accomplish this.

# Answer
Use Features. It's main job is to export such configuration into code. While not primarily intended to be manipulated afterwards, it's definitely possible, as I've done so several times myself.

You can even add custom directly into the generated .module file and features will respect and keep that if you do further changes from the UI later.

This way you can keep using the UI to make most of the changes to the content type, yet keep custom logic in the same module.
> 5 votes

# Answer
Take a look at the Features module. It allows you to export content types as features which can then be installed similar to modules.
> 2 votes

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


# Question
Title: User Profile Picture Cached After Change
When changing your profile picture (using core pictures support) the image is uploaded correctly but is saved with the same file path as the old image.

The result is even though the image is uploaded correctly, the browser has cached the old one and still displays it, making it seem as though the new picture wasn't uploaded.

Forcing a refresh `Ctrl`+`F5` resolves the problem, but this is not normal user behavior and has already caused confusion.

Is there a way to force a reload for this, for example changing the image path or setting an expires header?

# Answer
Good point! It's easy to change the default behavior, however, with a module roughly along these lines:

```
function YOUR_MODULE_form_user_profile_form_alter(&$form, &$form_state) {
  if (variable_get('user_pictures', 0))
     $form['#validate'][] = '_YOUR_MODULE_user_validate_picture';
}

function _YOUR_MODULE_user_validate_picture(&$form, &$form_state) {
  $source = $form_state['values']['picture'];
  if (! empty($source)) {
    $destination = /* TODO: generated random filename */;
    file_move($source, $destination, FILE_EXISTS_RENAME);
  }
}

```

Or, even better, use the Unique Avatar module. :-)
> 2 votes

# Answer
use a random tail after the filename like http://www.domain.com/filename**?122492834932** it will detect your file as a new file and browser cache will not read it as the same as the old one
> 3 votes

---
Tags: 6
---


title: get the vid of last saved vocabulary

text:
# Question
Title: get the vid of last saved vocabulary
How can I get the last saved vid. `taxonomy_vocabulary_save($vocabulary);` is not returning the vid. I have used the following way.

```
$vocabulary = new stdClass();
$vocabulary->name = 'Currencies';
$vocabulary->machine_name = 'currencies';
taxonomy_vocabulary_save($vocabulary);
// get the vid of currency
$vocabulary = taxonomy_vocabulary_machine_name_load('currencies');
//save a variable for vid
variable_set('currencies_vid', $vocabulary->vid);

```

Is there any better method?

# Answer
> 2 votes
The vocabulary object that you pass to `taxonomy_vocabulary_save()` will automatically be populated with the new `vid`, so you don't need to reload the vocabulary after you've saved it.

This code will work fine:

```
$vocabulary = new stdClass();
$vocabulary->name = 'Currencies';
$vocabulary->machine_name = 'currencies';
taxonomy_vocabulary_save($vocabulary);

variable_set('currencies_vid', $vocabulary->vid);

```

---
Tags: taxonomy-terms
---


# Question
Title: Gmap Views - Proximity filter for user locations based off of a specific node location
I am trying to build a view that shows the location of any users that are within a certain radius of a node's location. I can get a specific node's location to show up using its nid as the argument, and I can get the users' locations to show up (content profile location), but I can't get BOTH to display on the same map.

I'm thinking the problem is that I only have one option for the datatype that views uses to generate the markers. I've also tried displaying the node's marker through a gmap macro, but when view is displayed, the marker information from the macro is gone, and only the locations rendered by the view's fields are displayed.

# Answer
This is really a Views question. You can specify a Relationship and a Contextual Filter under the Advanced tab in Views.

I don't know the specifics for Gmap Views, but the principle is the same: You'd make a view of users, with a contextual filter of content:NID. Then you'd create a relationship to nodes based on the location. Gmap Views might give you a way to say 'within x miles of'... This is Views' way of creating a JOIN query.

Then on your content you'd add a Viewfield and tell it to pass the NID to the view. This will attach the view to your node and generate the view of users nearby.

Helpful tutorial about relationships here. Start at about 1:00 if you're impatient. :-)
> 1 votes

# Answer
Your problem is double.

**Retrieve all nodes 'near' a point.**

Here MySQL queries are absolutely not the best choice. You can find example here :

So your MySQL Query would look as ugly as :

```
SET @lat = $lat;
SET @long = $long;
SET @radius = $radius;

SELECT
  poi_id
FROM poi AS p
WHERE 6371 * 2 * ATAN2 ( SQRT ( ( SIN( ( RADIANS(p.latitude - @lat) / 2 ) * SIN( RADIANS(p.latitude - @lat) / 2 ) + COS ( RADIANS (@lat )) * COS ( RADIANS ( p.latitude ) ) * SIN ( RADIANS(p.longitude - @long) / 2 ) * SIN ( RADIANS(p.longitude - @long) / 2 ) ) ) ,  SQRT ( 1 - (SIN( RADIANS(p.latitude - @lat) / 2 ) * SIN( RADIANS(p.latitude - @lat) / 2 ) + COS ( RADIANS (@lat) ) * COS ( RADIANS (p.latitude) ) * SIN ( RADIANS(p.longitude - @long) / 2 ) * SIN ( RADIANS(p.longitude - @long) / 2 ) ) ) ) < @radius;

```

To keep Views integration, I would strongly suggest you to switch on Apache SOLR. You'll need it's 3.4 or 4 version. So you can user Apache SOLR Spatial Search ( http://wiki.apache.org/solr/SpatialSearch ). You can check out Apache SOLR / Views integration (drupal.org/project/apachesolr\_views )

Your last solution is to use MongoDB which also provides a fast geospatial search. (www.mongodb.org/display/DOCS/Geospatial+Indexing )

**Your views problem.**

Here you can use ApacheSOLR integration or write your own handler in case of any other solution. You might also bypass views for this specific need. And write a concrete GMAP/Mongo module, for example.
> 1 votes

# Answer
Just throwing it out there, but what you can perhaps do is obtain the locations through your Views, and then use a GMaps Macro to draw it manually, either by using a Global Custom Text field with tokens to substitute for the coordinates or some other method.

You can also make a custom query at the template level for the coordinates and again draw it using GMaps Macro (the GMaps module contains great documentation specifying how that can be done).
> 0 votes

# Answer
I'm not familiar with a way to achieve this using GMap. But I can at least tell you about one way that works: Use Address Field, OpenLayers, and Openlayers Proximity (also requires Geofield and Geocoder modules). It's not the easiest thing to set up, but is probably the most reliable and robust way to do it (in D7, which I'm assuming here).

In this implementation, you would have Address Fields on users as well as on nodes, and use Geofield+Geocoder to get coordinates for those addresses. You would then set up a view listing users that has the OpenLayers Proximity filter. You will need to feed the proximity filter a location to center around (the location of the node in your example). I'm not sure whether there's a way to set the value of that filter based on a field or argument from the View. If it's not possible, you would need to set the location for the Proximity filter using some custom module code.

In your code you would implement a views hook, obtain the Node ID for the node you want to use as your proximity center, find that node's location, and set the Proximity filter in the view to use that location as its center.
> 0 votes

---
Tags: views, google-maps
---


# Question
Title: Form API adds word "edit" in ID of every Form element
FORM API adds word "edit" before the id of any form element. When I have to use the element in JS I have to add "edit" before element id.

Example if I have element $form\['curdate'\] then in drupal\_add\_js('#edit-curdate');

Why so

# Answer
Drupal adds `edit` to denote that the element is an input element. It helps to identify form elements through CSS, and reduces the possibility of ID clashes with other elements on the page.

In case you're interested, this is done in the `form_builder()` function...and there's no easy way to override it system-wide.

You can easily override it for individual form elements though if it's bothering you:

```
$form['element'] = array(
  '#type' => 'textfield',
  '#title' => 'Some title',
  // ...
  '#id' => drupal_html_id('my-new-id')
);

```
> 2 votes

---
Tags: forms
---


# Question
Title: Type of drupal cache to be cleared on new hook implementation
If I implement a new hook which cache type(like menu, css+js, etc) should I clear for the changes to take effect?

# Answer
If you look at the `module_implements()` function, it uses the following code to reset the hook cache:

```
cache_set('module_implements', array(), 'cache_bootstrap');
drupal_static_reset('module_hook_info');
drupal_static_reset('drupal_alter');
cache_clear_all('hook_info', 'cache_bootstrap');

```

You can just use the same code to do it yourself.
> 7 votes

---
Tags: caching, drush
---


title: Use node_save with a custom nid

text:
# Question
Title: Use node_save with a custom nid
On our system (D5) two nodes have been deleted (by mistake). I need them back but I can't simply load a backup as there's a lot of new content created. I want to create these two new nodes again, manually, and they will obviously have a bigger nid.

Then, I would like to simply change the nid to the old (the deleted one) nid. This way, all node references will work again. (Node references from other content types).

I tried the following:

```
//load the newly created node
$node_new = node_load(1234580);

//put the
$node_new->nid = 81580; //this is the nid of the deleted node
$node_new->vid = 81580; //and its vid

node_save($node_new);

```

And if I print\_r $node\_new at the end, it says the nid is 81580, but on the database there's no node with that nide.

How can I create a node and specify the nid manually??

# Answer
> 2 votes
You'll need to change the nid manually in the database. As far as I know, only the D7 node\_save() allows you to specify the nid during initial save (because it allows you to set $node-\>is\_new as well instead of overriding it).

And no version will ever allow you to change the nid in an update.

---
Tags: nodes, 5
---


title: Why do I get these errors in my module?

text:
# Question
Title: Why do I get these errors in my module?
I am trying to use the Date module in a module I am writing, but I get the following errors:

> Warning: Missing argument 1 for myform\_data\_entry\_form() in myform\_data\_entry\_form() (line 28 of D:\wamp\www\drupal\sites\all\modules\myform\myform.module).
> Warning: Missing argument 2 for myform\_data\_entry\_form() in myform\_data\_entry\_form() (line 28 of D:\wamp\www\drupal\sites\all\modules\myform\myform.module).

This is the code I am using in my module.

```
function myform_help($path, $arg) {
switch ($path) {
      case "admin/help#myform":
        return '<p>'.  t("Displays links to nodes created on this date") .'</p>';
        break;
    }
 }

function myform_menu() {
  $items['myform/data_entry_form'] = array(
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
    'page callback' => 'myform_data_entry_form'
  );
  return $items;
}

function myform_permission(){
  return array(
    'access myform content' => array(
      'title' => t('Access content for the myform module')
    )
  );
}

function myform_data_entry_form($form,&$form_submit) {
  $form['curdate'] = array('#type' => 'date_popup', '#title' => 'Date', '#date_format' => 'd/m/Y');

  return $form;
}

```

# Answer
> 5 votes
Drupal forms should be called using the `drupal_get_form()` method, even from menu callbacks. Your menu item needs to look like this:

```
$items['myform/data_entry_form'] = array(
  'type' => MENU_CALLBACK,
  'access arguments' => array('access content'),
  'page callback' => 'drupal_get_form',
  'page arguments' => array('myform_data_entry_form')
);

return $items;

```

Make sure you clear Drupal's caches each time you make a change in `hook_menu()`, otherwise it won't get picked up.

---
Tags: forms
---


# Question
Title: How to rewrite the ouput html of the image field for a node page?
I have an image field where people can upload an unlimited number of photos to a node. By default, drupal 7 outputs these images with html similar to the following:

```
<div class="field-items">
    <div class="field-item even">
        <a rel="gallery-170" class="colorbox init-colorbox-processed-processed cboxElement" title="" href="http://tourismbuilder1.hokkaido-select.com/sites/default/files/gaikan_5.jpg">

            <img width="580" height="386" title="" alt="">

```

This is fine, but for my application, I would like to be able to print a unique number to identify the image in the class or as an id - so, instead of field-item even, field-item-012 even, for example. Should this be done in the template file or in template.php file?

Thanks!

# Answer
> 0 votes
Thank you for all the answers. I realized after some reading and digging my question was a little misleading. Baysaa and Varshith your suggestions worked fine, but in reality what I ended up needed was that all fields that could have multiple items that each one have its own unique label.

After digging around I found the theme\_field() function, which I overrode as mytheme\_field(). Here is how I did it. Although it's a tad long, the only thing I did was add $x to the function and increment it (at line 14). Is there anything wrong with this approach compared to the others?

```
/**
* Implements theme_field
*/
function nobo_field($variables) {
$output = '';

// Render the label, if it's not hidden.
if (!$variables['label_hidden']) {
$output .= '<div class="field-label"' . $variables['title_attributes'] . '>' . $variables['label'] . ': </div>';
}

// Render the items.
$output .= '<div class="field-items"' . $variables['content_attributes'] . '>';
$x = 0;
foreach ($variables['items'] as $delta => $item) {
$classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even') . ' field-item-' . $x;

if($x == 0){
    $classes .= ' primary-photo'; // add class for the very first photo if different sizing needed
}

// for this particular template, we are only showing 3 photos: 1 large and 2 small. However, other
// photos can be visible in the slideshow overlay. Thus, hide all photos after the 3rd photo (array index 2)
if($x > 2){
    $classes .= ' other-photo'; // add class for the very first photo if different sizing needed
}

$output .= '<div class="' . $classes . '"' . $variables['item_attributes']    [$delta] . '>' . drupal_render($item) . '</div>';
$x++;
}
$output .= '</div>';

// Render the top-level DIV.
$output = '<div class="' . $variables['classes'] . '"' . $variables['attributes'] . '>' . $output . '</div>';

return $output;
}

```

# Answer
> 3 votes
This looks like output coming from `theme('field')` theme function in field.module. You can override the output by putting the following function in your template.php:

```
/**
 * Implements template_preprocess_field
 */
function mythemename_preprocess_field(&$vars) {

}

```

More info on the preprocessor (with examples of how to add additional classes) is here: `template_preprocess_field`

**EDIT:** Actually looking at the theme function, it seems that in your case I think you need to implement both a preprocessor and a template file for your field. So in the preprocessor you create a variable for the class:

```
/**
 * Implements template_preprocess_field
 */
function mythemename_preprocess_field(&$vars) {
  $element = $vars['element'];
  if ($element['#field_name'] == 'field_myfieldname') {
    $number = 123; // This variable should get the value you wish to attach to the class
    $vars['field_myfieldname_custom_class'] = 'field-item-' . $number;
  }
}

```

And then create a field template file `field--field_myfieldname.tpl.php` and put `<?php print $field_myfieldname_custom_class; ?>` where the class should appear.

# Answer
> 0 votes
You can do this by having a custom field.tpl.php file for your theme. Take the default field.tpl.php from "modules\field\themes\field.tpl.php" and add it to your theme dir. Then you can modify it to add an unique number to "field-item" div.

---
Tags: 7, theming
---


title: "changed by" on nodes

text:
# Question
Title: "changed by" on nodes
```
mysql> select nid, uid, created, changed from node;
+-----+-----+------------+------------+
| nid | uid | created    | changed    |
+-----+-----+------------+------------+
|   1 |   8 | 1336040166 | 1336046390 |
+-----+-----+------------+------------+

```

I'd like to have an "changed by" column on the `node` table, exactly as we have a "created by" (the uid field). This would keep track of who made the last change on that node. I know that this could be derived from the `node_revision` table but this depends on the revisions being enabled for the content types I'm interested.

So, what is the best way to do this? And why doesn't Drupal core offer this by default? I thought that "changed by" is a pretty standard piece of information that a CMS should attach to content.

# Answer
> 18 votes
I thought this would be quite tough to do, but as it turns out it's fairly easy.

You just need to create a custom module that adds a column to the node table on install, implement `hook_schema_alter()` so Drupal knows about the new column, and add some logic to provide a value before the node is saved.

Here's a small module that will do the trick:

File: node\_table\_alter.info

```
name = Node Table Alter
core = 7.x

```

File: node\_table\_alter.install

```
function node_table_alter_install() {
  // Add the new field to the node table
  $field = array(
    'description' => 'Stores the user id of the last user to alter the node',
    'type' => 'int',
    'unsigned' => TRUE
  );

  db_add_field('node', 'changed_by', $field);
}

```

File: node\_table\_alter.module

```
function node_table_alter_schema_alter(&$schema) {
  // Add the new field to the schema cache
  $schema['node']['fields']['changed_by'] = array(
    'description' => 'Stores the user id of the last user to alter the node',
    'type' => 'int',
    'unsigned' => TRUE
  );
}

function node_table_alter_node_presave($node) {
  // Populate the changed_by column with current user's id
  $node->changed_by = $GLOBALS['user']->uid;
}

```

You may want to add logic to remove the field again on uninstall, and add an index to the table for the `changed_by` column (see `db_add_index()`), but this should give you a good place to start.

The beauty of this method is that you have effectively added a new property to the node. You'll be able to use `node_load()`, `EntityFieldQuery`s, etc. with it as if it were any of the other standard properties for a node.

God bless Drupal for being so extendable!

# Answer
> 1 votes
I guess you could add a entity reference field (let's call it `field_changed_by_user`) to the content type you need to track. Then you could use `hook_node_presave` to save the user id to the node like this:

```
function hook_node_presave($node) {
  if ($node->nid && $node->type == 'content_type_to_track_changes_for') {
    global $user;
    $node->field_changed_by_user['und'][0]['target_id'] = $user->uid;
  }
}

```

I think it's also possible to update the field with the user's id just by creating a rule. You can read more here.

---
Tags: 7, users, nodes
---


title: How to add id to a block

text:
# Question
Title: How to add id to a block
For example I have the code:

```
function contact_block_view($delta = '') {
$block = array();
switch ($delta) {
  case 'contact_block':
  $block['content'] = drupal_get_form('contact_form');
break;
}
return $block;
}

```

How to set inside this block the id or class attributes?

# Answer
> 12 votes
You will not be able to add an `id` or class `attribute` to the block in your `hook_block_view` implementation. At this stage you are not yet dealing with the markup of the block itself but only the markup for its content. In order to set the `id` or `class` of the block markup, you will need to use `hook_preprocess_block()` or `hook_process_block()` to add a usable variables to the `block.tpl.php` template. Then you will need to actually use the variables in the template itself.

Fortunately, the default `block.tpl.php` file already provides variables for both the `id` and `class` attributes of your block (`$block_html_id` and `$classes`). Actually, `template_preprocess_block` already sets the id to `'block-' . $variables['block']->module . '-' . $variables['block']->delta`. So in your case, using the default template, your block will have `block-contact-contact-block` as `id`. But it can be changed if needed. In any preprocessor functions, you can add and remove CSS classes by manipulating `$classes_array` variables. Both are illustrated in the following code.

```
function MODULE_preprocess_block(&$variables) {
  if ($variables['block']->module == 'contact' && $variables['block']->delta == 'contact_block') {
    $variables['block_html_id'] = drupal_html_id('your-id-here');
    $variables['classes_array'][] = drupal_html_class('your-class-here');
  }
}

```

---
Tags: 7, blocks
---


# Question
Title: How can I track statistics regarding the number of sign-ups vs. account deletions?
I'm working on a social networking site in Drupal 7 that I haven't launched yet. However, once I've launched I would like some basic metrics to track how I'm doing, particularly the number of sign-ups per week (or some other arbitrary interval) and the number of users who have cancelled/deleted their accounts.

Is there a way to track this from within Drupal?

# Answer
> 2 votes
Views is your friend. You can build a view that shows the total number of registrations per week, for example. You can use an exposed filter to change the date ranges.

You can use user stats to keep track of last login time and then built a similar view.

If you user userpoints you can get stats based on activity (or the lack thereof).

# Answer
> 1 votes
First of all I wouldn't allow users to delete accounts themselves.

I would suggest to use Webform to gather requests for account deletion and additionally query users about the reason to delete account.

Then the site administrator would use a report based on Views Bulk Operations to delete accounts.

You can gather statistics based on urls used by users to register and to delete account. See http://drupal.org/documentation/modules/statistics.

For more data analysis I use Google Analytics.

---
Tags: nodes
---


# Question
Title: What is the "right" way to track a custom patch to a contributed module?
I need to apply this patch to my site: http://drupal.org/node/483176#comment-5939648

What is the "right" or "responsible" way to track this change? We use Git for version control.

# Answer
> 4 votes
I keep all of those in the projects make file, which makes it easy to apply the patch again should the module be updated without it commited, and remove it when it's no longer necessary.

This answer makes the most sense in context of my answer to the question Should I source control contribed modules in my project?.

---
Tags: 6, version-control
---


# Question
Title: How to add newsletter functionality (just stable modules if possible)?
I've searched a little and I needed to add newsletter functionality to a Drupal 7 installation. I've found Simplenews, which is in Beta version for Drupal 7 nothing more. I don't need anything really complicated, just these functionalities:

* Guest user can subscribe to newsletter by leaving their email address in a field
* Registered users can tick a checkbox in their profile to choose whether to receive newsletters
* Users can unsubscribe from newsletter by clicking a link in the newsletter
* A WYSIWYG editor for sending newsletters (but, I think this can be accomplished with the WYSIWYG module)

nothing more. If any of you tried the development version of Simplenews, please provide your experience.

# Answer
Simplenews is really your only way of going. I have personally been holding off on it's implementation in 7 because of its state as well. More specifically, emails were not being sent (test ones were) and it's lack of mimemail support.
> 5 votes

# Answer
There is also a module called Newsletter which might be ok, have a more user centric UI (all the features are on a panels not spread out like in Simplenews). Newsletter can also handle multiple newsletter lists and also have a more complex form for collecting the data: e.g you can gather up the subscriber names, age, sex etc.
> 3 votes

# Answer
You can also use MailChimp module. It's does what you described and it free for the first few members (can't remember how many users.)

> This module provides integration with MailChimp, a popular email delivery service. The module makes it easy for website users or visitors to control which of your email lists they want to be on (or off), lets you generate and send MailChimp email campaigns from your site, and lets you and your users view a history of emails they have been sent from MailChimp. More generally, it aspires to makes your email delivery world efficient and to make your user's email receipt and control simple and precise. Thanks to MailChimp's ongoing sponsorship, this module is actively maintained and regularly adding features.
> 0 votes

---
Tags: 7
---


# Question
Title: How do I send data to a template page on form submission?
I am building a weather API in Drupal 7, and I am unable to send weather report to my custom template file. Everything is working fine but the result is not displayed; everything is working as expected except result display.

### .info

```
name = BM Weather API Part 2
description = Display the current weather condition of a specific location
package = BM API
version = VERSION
core = 7.x

```

### .module

```
<?php
function BM_weather_API_part2_theme() {
  return array(
    'BM_weather_API_part2' => array(
      'template' => 'BM_weather_API_part2',
      'variables' => array('msg' => NULL),
    ),
  );
}

function BM_weather_API_part2_menu() {
  $items['BM_weather_API_part2'] = array(
    'title' => 'Weather API - Part 2',
    'page callback' => 'BM_weather_API_part2_view',
    'access arguments' => array('access content'),
    'file' => 'BM_weather_API_part2.pages.inc',
  );

  return $items;
}

```

### .inc

```
function BM_weather_API_part2_view() {
  $dis = drupal_get_form('BM_weather_API_part2_form');
  return $dis;
}

function BM_weather_API_part2_form() {
  $form['location_name'] = array(
    '#title' => 'Location',
    '#type' => 'textfield',
    '#description' => 'Enter Location Here.',
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Get Weather Report',
    '#submit' => array('BM_weather_API_part2_get_weather_report'),
  );

  return $form;
}

function BM_weather_API_part2_get_weather_report($form, &$form_state) {
  $loc_name = $form_state['values']['location_name'];

  if (ctype_digit($loc_name)) {
    form_set_error('BM_weather_API_part2_character_required', t('Please Enter Proper Location Name.'));
    return;
  }
  elseif ($loc_name == '') {
    form_set_error('BM_weather_API_part2_character_required', t('Please Enter Location Name'));
    return;
  }

  $freport =  get_weather_from_google($loc_name);

  return theme('BM_weather_API_part2', array('msg' => $freport));
}

function get_weather_from_google($loc) {
  // $finalreport contains the final report coming from google
  return  $finalreport;
}

```

### .tpl

```
print $msg;

```

# Answer
Form submission handlers (in your case, `BM_weather_API_part2_get_weather_report()`) don't return any value. See user\_login\_submit(), and user\_register\_submit() as examples of form submission handlers.

What I would suggest for your form submission handler is the following:

* Set `$form_state['rebuild']` to `TRUE`, and `$form_state['BM_weather_API']['weather_result']` to the value obtained from the weather service; this would cause the form builder to be called again.
* At this point, the form builder should verify if the content of
`$form_state['BM_weather_API']['weather_result']` is not empty, and show the output obtained from the weather service, for example using code similar to the following one.

```
// First case.
$form['result'] = array(
  '#theme' => 'BM_weather_API_part2',
  '#msg' => $form_state['BM_weather_API_part2']['weather_result'],
);

```

```
// Second case.
$form['result'] = array(
  '#markup' => $form_state['BM_weather_API_part2']['weather_result'],
);

```

In the first case, `$form_state['BM_weather_API_part2']['weather_result']` is the value obtained from the weather service, which needs to be passed to the theme function; the code would cause the theme function to be called, and get the value of `$form_state['mymodule']['weather_result]` as value for the `$msg` variable used in the template file. In the second case, `$form_state['BM_weather_API_part2']['weather_result']` is the value obtained from the theme function, which got the weather service's result.

The code I would write is similar to the following one.

### .module

```
<?php
function BM_weather_API_part2_theme() {
  return array(
    'BM_weather_API_part2' => array(
      'template' => 'BM_weather_API_part2',
      'variables' => array('msg' => NULL),
    ),
  );
}

function BM_weather_API_part2_menu() {
  $items['weather/report'] = array(
    'title' => 'Weather API - Part 2',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('BM_weather_API_part2_form'),
    'access arguments' => array('access content'),
    'file' => 'BM_weather_API_part2.pages.inc',
  );

  return $items;
}

```

### .inc

```
function BM_weather_API_part2_form() {
  $form['location_name'] = array(
    '#title' => 'Location',
    '#type' => 'textfield',
    '#required' => TRUE,
  );

  if (!empty($form_state['BM_weather_API_part2']['weather_result'])) {
    $form['result'] = array(
      '#markup' => $form_state['BM_weather_API_part2']['weather_result'],
    );
  }

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Get the weather report',
    '#validate' => array('BM_weather_API_part2_form_validate'),
    '#submit' => array('BM_weather_API_part2_form_submit'),
  );

  return $form;
}

function BM_weather_API_part2_form_validate($form, &$form_state) {
  if (BM_weather_API_part2_check_location($form_state['values']['location_name'])) {
    $form_state['BM_weather_API_part2']['weather_result'] = FALSE;
    form_set_error('location_name', t('Please enter a proper location name.'));
  }
}

function BM_weather_API_part2_form_submit($form, &$form_state) {
  $form_state['BM_weather_API_part2']['weather_result'] = theme('BM_weather_API_part2', array(
    'msg' => BM_weather_API_part2_get_weather($form_state['values']['location_name']))
  );

  $form_state['rebuild'] = TRUE;
}

function BM_weather_API_part2_get_weather($loc) {
  // ...
}

```

I will add some notes about your code.

* In the implementation of `hook_menu()`, the array keys are the paths associated with the menu callbacks; in your case, as you use `$items['BM_weather_API_part2']`, the URL for that menu callback would be http://example.com/BM\_weather\_API\_part2 (replace example.com with the URL of your site). It is preferable a path like *weather*, or *weather/report*, which is similar to the paths used from Drupal, such as *node/1*, *user/1/edit*.
* When defining a menu callback, you can use `'page callback' => 'drupal_get_form'` and pass as first argument of "page arguments" the name of the form builder; there isn't the need to define a function such as `BM_weather_API_part2_view()`, whose only purpose is to call `drupal_get_form()`.
* The form submission handlers don't check if the submitted values are correct; that is a task for the form validation handlers. That is why I am using a form validation handler, in my example code.
* If the users need to enter a value for a form field, then you can simply use `'#required' => TRUE` for that form field, as I did.
* `ctype_digit()` returns `TRUE` when the parameter it gets is a string containing only digits. I am not sure that is what the user should input in your case, as a number is not what I would consider a location name. If the user really needs to enter a number, the description for the "Location" form field should say that, and it should also explain what type of input the form it is expecting (e.g. a zip code).
* The first argument of form\_set\_error() is the form field ID. As you don't have any form field that uses "BM\_weather\_API\_part2\_character\_required" as ID, `form_set_error('BM_weather_API_part2_character_required', t('Please Enter Proper Location Name.'))` is not highlighting any form field, which is part of the purpose of `form_set_error()`. In your case, you should use `form_set_error('location_name', t('Error string'))`, as location\_name is the form field ID for the field you are reporting an error.
* All functions implemented in a module should be prefixed with the short name of the module (after an underscore, if the function is "private"); in this way, there isn't any collision between different modules, which is what happens if two different modules would define a `get_weather_from_google()` function.
* If the template file just prints the value it gets between its variables, then there isn't the need of a template file, or a theme function; you just use code similar to the following one:

```
function BM_weather_API_part2_form_submit($form, &$form_state) {
  $form_state['BM_weather_API_part2']['weather_result'] = BM_weather_API_part2_get_weather($form_state['values']['location_name']));
  $form_state['rebuild'] = TRUE;
}

```

I wrote the example code assuming that your template file does more than just printing a variable it gets, and you didn't show all the code for the template file; if the template file does only that, then the template file, and the theme function are not necessary.

As side note, if the short name of your module contains uppercase characters, you will have problems with hook\_update\_N() being executed. You should always use lower case characters in the short name of your module.
> 2 votes

---
Tags: theming
---


# Question
Title: Remove a code from core module without modifying it(using hooks?)
Referring to my question about the removal of "Add new comment" link from the book page links area, is there a way to remove the code with the help of *hooks*. I am new to implementing *hooks*. I have found the solution to the problem, but I need a better way to implement it(maybe by hooks, idk).

**Edit**
I did face a similar problem when I had to comment out the `print $tree` from the core *book module's* `book-navigation.tpl.php`, as it was printing the tree at the bottom of every node, and I didn't want it that way. I used the *tree navigation* block in my sidebar to navigate through the tree structure. Is there a quick way to do this?

# Answer
1) The suggested hook\_link\_alter() (in your linked question) does not exist in Drupal 7 so it doesn't work like you already found out. On the API page there's hook\_node\_view\_alter() being mentioned which can be used instead. You can implement this specific hook both in a module and your theme's template.php file. To unset the comment link the following should work (updated based on the comment by Ajit):

```
function myThemeOrModule_node_view_alter(&$build) {
  if ($build['#node']->type == 'book') {
    unset($build['links']['comment']['#links']['comment-add']);
  }
}

```

If it's not quite right you can try (in your development environment) finding out what to unset by adding the following line inside the function: `drupal_set_message('<pre>'.var_export($build['links'], TRUE).'</pre>');` (until you have a better tool available).

2) Overriding template files is handled like paul-m already mentioned by creating a copy of the necessary tpl.php file inside your theme folder and doing all the changes there.

3) If you end up needing to override theme functions then you should create a copy of it inside your theme's template.php file where you can modify it.

Don't forget to clear the caches after adding a new function or template.
> 3 votes

# Answer
To solve the `print $tree` problem, you'd create a new `book-navigation.tpl.php` template file that doesn't print the $tree. You'd do this in your own theme, which could easily be a subtheme of whichever one you're using.

As for the previous question, md2 got it right. Implement this non-theme hook by creating a module. It's not that hard. The Examples project might help you a little, though it doesn't directly address this issue.
> 1 votes

---
Tags: 7, hooks
---


# Question
Title: What would cause certain buttons to not appear on specific fields using the CKEditor?
I am using the CKEditor module for Drupal 6 (not the WYSIWYG module). It's successfully showing the editor on a variety of textareas.

However, on a certain content type the editor is behaving differently on the body field than on other CCK textarea fields. Specifically, several buttons are not appearing on the Body field editor that do appear on other textareas in that same form. Additionally, if I change the button order or appearance in the CKEditor Profile, it does update on the other textarea fields but no the Body field. That field keeps the same button set.

I've tried a variety of things:

1. Deleted and recreated the Global Settings and Profiles for CKEditor
2. Tried to forcefully show the buttons via CSS
3. Confirmed there is no config in sites/all/modules/ckeditor/ckeditor.config.js
4. Confirmed no JavaScript is acting on the CSS class wrapper of one of the buttons being hidden.

I'm stumped. What else could be causing CKEditor to load for the body field differently?

# Answer
> 0 votes
Wow, I am really, really, blind. I missed an errant CSS style that was hiding a child elements of the CKEditor elements in question.

---
Tags: 6, theming, wysiwyg
---


# Question
Title: Why can't I override my views theme template files?
I am using D7. I am using one of the template file names suggested in the theming information in the view. Putting that template file in my theme templates folder. saving it and clearing the cache. The .tpl.php does not seem to be recognized and/or overwrite the default file. What am I doing wrong?

# Answer
> 3 votes
Be sure you use the Rescan button in the Theme: Information dialog. Also, be aware that pasting names not carefully enough can put white space in front of the file name. You wont see the spaces in FileZilla or TC, but it can leave your file unrecognized. So watch out when pasting.

---
Tags: views, theming
---


# Question
Title: Menu Block (or custom menu display): expand immediate children of active item
I need to show a menu which only displays nodes one or two levels into the menu hierarchy, unless these nodes are immediate children of the node currently being viewed, in which case they should also be shown. (I explain what I'm after more fully in the lengthy 'example' below.) The Menu Block module almost lets me do this, but lacks a setting to expand the immediate children of active item. I added this as a feature request for Menu Block but have had no reply. Is there any way I can implement this myself, either using Menu Block or writing code to display the menus myself? Any code pointers would be very helpful.

(*Background info:* I'm using Drupal 7)

# **An example of what I'm after**

Suppose you have a menu with these items (with the number of dashes before them representing their level):

```
-i1
--i2
--i3
---i4
---i5
----i6
--i7

```

If in Menu Block I set my menu block up with 'Starting level' = '1st level' and 'Maximum depth'=1 then it'll look like:

```
-i1
--i2
--i3
--i7

```

However, I'd like there to be an 'expand the immediate children of the active item' setting in Menu Block. If this setting were chosen then if the active item were i3 or i4 you should see:

```
-i1
--i2
--i3
---i4
---i5
--i7

```

And if it were i5 or i6 you'd see:

```
-i1
--i2
--i3
---i4
---i5
----i6
--i7

```

# Answer
Like we figured out in the comments the problem was that the "Expand all children of this tree" option was checked for the menu block. Without checking this the children will only be shown if the user is on a related page, which was the desired result.
> 2 votes

---
Tags: routes, blocks
---


title: can't log in to my off-line drupal site

text:
# Question
Title: can't log in to my off-line drupal site
I deleted the navigation-log-in pane.

I logged out, and when needed to log back in, wrote: "mysite/user" and the message I keep getting is as follows:

" Not Found

The requested URL /pancher/user/ was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request. "

# Answer
I've had some cases where clean url-s aren't working in offline mode. You should be able to log in using '?q=user' instead.
> 1 votes

---
Tags: users, navigation
---


# Question
Title: bartik_links__system_main_menu() doesn't work
When I implement `bartik_links__system_main_menu($variables)` in my `template.php` file, there is nothing different in the main menu than the previous one. I've changed some of the markup in this function; I checked it in the theme developer, and the function that is responsible for the main menu is still `theme_links()` rather than `bartik_links__system_main_menu($variables)`.

Why?

# Answer
> 1 votes
Make sure that:

1. `theme('links__system_main_menu', ...` is actually used to output the menu.
2. There are no issues with your code.
3. Caches have been cleared after adding the function (admin/config/development/performance).

To better understand what `system_main_menu` is all about check keithm's answer here. The main part of the explanation is this:

> `links__system_main_menu` is a theme hook pattern of the form `[base
>  hook]__[context]`. When links are themed with `theme('links__system_main_menu', $vars)`, `theme()` will search for and use `theme_links__system_main_menu()` if it has been defined. If not, it will use `theme_links()`.

Official documentation about it can be found here.

---
Tags: theming
---


# Question
Title: Where does the $settings array come from in uc_quote_condition_order_shipping_method?
I've been trying to write my own shipping module based on this tutorial. The 'payment method' pane doesn't pick up all the accessorial information until the shipping quote is recalculated. Moving on to the 'review' page exposes a repeated error that was caused by the request for a shipping quote done via ajax on the previous page:

`warning: in_array() expects parameter 2 to be array, null given in .../ubercart/shipping/uc_quote/uc_quote.module on line 351.`

Obviously this is a very effective way of frightening off customers.

Line 351 (`in_array($line_item['title'], $accessorials)`) is asking for the `$accessorials` array, which I've defined correctly in my module, but which isn't being seen by this function because it looks for `$accessorials` with

`$accessorials = $methods[$settings['method']]['quote']['accessorials'];`

When I use `dpr($settings)`, I find that it is an array containing two arrays, each pertaining to shipping quotes that have been deleted and had their methods disabled and uninstalled: `ucflatrate_1` and `minpercentrate_2`.

Where is this information coming from?
How can I delete it, or replace it with my own?

My module code is below. I'm really stressing about this one.

```
<?php

/**
 * Implementation of Ubercart's hook_shipping_method().
 */

function uc_lathes_delivery_shipping_method() {
  $methods = array();
  $enabled = variable_get('uc_quote_enabled', array());

  $methods['lathes_delivery'] = array(
    'id' => 'lathes_delivery',
    'module' => 'uc_lathes_delivery',
    'title' => t('Royal Mail first class'),
    'enabled' => $enabled['lathes_delivery'],
    'quote' => array(
      'type' => 'order',
      'callback' => 'uc_lathes_delivery_quote',
      'accessorials' => uc_lathes_delivery_accessorials(),
    ),
    'weight' => $weight['lathes_delivery'],
  );
  return $methods;
}

function uc_lathes_delivery_accessorials() {
  return array(
    "uk"    => t('Postage and Packing within the UK (1st class Royal Mail)'),
    "eu"    => t('Postage and Packing within the EU (1st class Royal Mail)'),
    "world" => t('Postage and Packing (Airmail)'),
  );
}

/**
 * Implementation of hook_ca_predicate().
 *
 * Connect the quote action with the quote event.
 */

function uc_lathes_delivery_ca_predicate() {
  $enabled = variable_get('uc_quote_enabled', array());
  $predicates = array();
  $predicates['uc_lathes_delivery_get_quote'] = array(
    '#title'    => t('Lathes.co.uk shipping quote'),
    '#trigger'  => 'get_quote_from_lathes_delivery',
    '#class'    => 'uc_lathes_delivery',
    '#status'   => $enabled['lathes_delivery'],
    '#actions'  => array(
      array(
        '#name'         => 'uc_quote_action_get_quote',
        '#title'        => t('Fetch a shipping quote from the custom lathes.co.uk module.'),
        '#argument_map' => array(
          'order'   => 'order',
          'method'  => 'method',
        ),
      ),
    ),
  );
  return $predicates;
}

/**
 * Papers! Is this order from within the EU?
 */

 function uc_lathes_zone($country) {
 $europe = array( 40,  56,  100, 196, 203,
                  208, 233, 246, 250, 276,
                  300, 348, 372, 380, 428,
                  440, 442, 470, 528, 616,
                  620, 642, 703, 705, 724,
                  752,
                );
 if ($country == 826) {return 'uk';}
 elseif (in_array($country, $europe)) {return 'eu';}
 else {return 'world';}
 }

 /**
  * Get the rate
  */

function uc_lathes_rate ($zone, $product_type) {
  $rates = array (
      'uk'    => array("print"         => 2,    // *each*
                       "product_book"  => 0,
                       "drive_belt"    => 0,),

      'eu'    => array("print"         => 15,   // percent
                       "product_book"  => 1,    // each
                       "drive_belt"    => 1,),  // per metre

      'world' => array("print"         => 20,   // percent
                       "product_book"  => 2,    // each
                       "drive_belt"    => 2,),  // per metre
  );
return $rates["$zone"]["$product_type"];
}

/**
 * Standard callback to return a custom shipping rate.
 *
 * @param $products
 *   The order's products.
 * @param $details
 *   Other order details including a shipping address.
 * @param $method
 *   The shipping method to create the quote.
 * @return
 *   An array containing the shipping quote for the order.
 */

function uc_lathes_delivery_quote($products, $details, $method) {

  // Set some sensible defaults.
  $quote = array(
    'rate'          => 5,
    'option_label'  => t('Delivery (custom)'),
    'carrier'       => 'uk',
  );

  // Let's do this thing.
  $accessorials = uc_lathes_delivery_accessorials();

  $zone = uc_lathes_zone($details['country']);
  $amount = 0;
  $rate = 0;

  foreach ($products as $product) {
  $rate = uc_lathes_rate($zone, $product->type);
    switch ($product->type) {
        case 'product_book':
                            $amount += $rate * $product->qty;
                            break;
        case 'print':
                     switch ($zone) {
                       case 'uk':
                         $amount += $rate * $product->qty;
                         break;
                       case 'eu':
                         $pct = ($product->price / 100) * $rate;
                         if ($pct < 2) {$pct = 2;}
                         $amount += $pct * $product->qty;
                         break;
                       case 'world':
                         $pct = ($product->price / 100) * $rate;
                         if ($pct < 4) {$pct = 4;}
                         $amount += $pct * $product->qty;
                         break;
                     }
            break;
        case 'drive_belt':
            $lenth = $product->data['attributes'][5];
            if ($lenth < 1000) {$lenth = 1000;}
            $lenth = $lenth / 1000;
            $amount += $lenth * $rate * $product->qty;
            break;
    }
  }

  $quote['option_label'] = $accessorials["$zone"];
  $quote['rate'] = $amount;
  $quote['carrier'] = $zone;

  //  Format the shipping rate for display.
  $quote['format'] = uc_price(
  $quote['rate'],
  array('revision' => 'formatted-original', 'type' => 'amount')
  );

  // Bundle it into a 1-element array so Ubercart can use it.

  $quotes[$quote['carrier']] = $quote;
  return $quotes;

}

```

# Answer
I found it. By exporting the database as a text file and searching it I found the references to the previously deleted shipping methods. For a while I wondered about editing the serialized array by hand but thought better of it. I realized that the condition that refers to them was actually a tax condition. I'd been using the countries shipping methods (which were split by countries in the EU or not) to decide if VAT should be applied. Once I'd deleted those methods and written my own module this error occurred.

Removing the conditions and creating another based on the delivery country has solved my problem. At last.
> 0 votes

# Answer
It seems like the problem might be that my module doesn't have an admin page. If it means anything to anyone the $settings array contains the keys "negate" and "method", which suggests that it is to do with the CA condition provided by the module. "negate" is always 0 even if I change that within CA.

I've grepped /ubercart/ for 'negate' and found very little.
> 0 votes

---
Tags: 6, ubercart
---


# Question
Title: Drupal 7 doesn't allow search in chinese character
I'm using drupal 7 multilanguage site. When I enter chinese character (UTF8) in search box and search, it gives error like below:

Bad Request

Your browser sent a request that this server could not understand.

Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.

Can I know what's the problem and how to solve it?

Thank you in advance.

# Answer
> 1 votes
This is probably a server configuration issue. I have successfully used Japanese search on both Drupal 6 and 7. Try installing a copy of your site on a local development environment (Acquia Dev Desktop, etc.) and see if the problem recurs.

---
Tags: search, uri
---


# Question
Title: How to configure D7 so files get uploaded to a different server
In Drupal 7, the default path for uploading is set in the File system options in the Public file system path. Is it possible to specify a different server in this path? I have a Drupal 7 web site we are developing that is going to have about 20k files and I'd like to put them on a different server than the web server. If not possible to specify a different server than are there any user contributed modules that can handle this?

# Answer
> 8 votes
I do something very similar. If you're running infrastructure that is capable of this configuration, I recommend serving up a share on your file server (Linux or Windows Server) and just mount it in Drupal's public file path, wherever the public directory is for that particular field.

For example, take the following Samba configuration (found in /etc/samba/smb.conf if you run a Linux-based file server). This comes at the very end of the file after all other configuration options:

```
[data]
    comment = Data directory
    browseable = yes
    writable = yes
    valid users = "@DOMAIN\Domain Admins"
    path = /data
    create mask = 0664
    force create mode = 0664

```

The `valid users` syntax there says "allows this group of users" to access this share. In this case we're using PAM to hook up our file server to Active Directory, and this particular group is made available once you hook the two up.

On your web server, whatever is hosting your Drupal site, navigate to the public files directory. Say the particular field you need to make the files available for is public://field\_with\_20k\_files/. You'd run a similar mount command like so:

```
sudo mount -t cifs -o user=domainadministrator,uid=domainadministrator,gid=apache //fileserver/data /path/to/field_with_20k_files

```

I have the `gid` set to whatever process is running the web server so it has access to that directory. Most likely you'll want to ensure that the web service has read and write access to the web server is actually capable of uploading files.

# Answer
> 5 votes
Also an excellent option would be the Storage API. Here is a quote about it (from the module's project page):

> ... is a low-level framework for managed file storage and serving. Module and all the core functions will remain agnostic of other modules in order to provide this low-level functionality. Submodules are welcome to allow Storage API to interact with other contributed modules, but there shall never be a dependencies\[\] statement in the storage.info file unless it is necessary for the low-level function of this module.
>
> It has the following features:
>
> * Pluggable architecture - it can be extended to work with any storage service.
> * Redundancy - it can be configured to store your files in multiple services and instantaneously change which one is serving. This means your site will not be brought down by a service having problems.
> * Access control API - can be used for e-commerce.
> * Deduplication \- when files that are identical are stored in the same container, only one instance will be created. This saves bandwidth and storage.
> * File and image field integration - enable the "core bridge" sub-module.
> * Audit module - compares a manifest of files with what is recorded in the database to ensure that the record is accurate.

# Answer
> 4 votes
Two modules that may also help in this area are CDN (used by many big sites, including Economist.com) and Amazon S3 (specifically for using Amazon S3 instead of the local file system).

---
Tags: 7, files
---


# Question
Title: How do I hide render elements if a checkbox that controls a form #state is checked?
I have a form where a user can either choose a gallery field to populate or a video field to populate but they have to choose one of the other -- there can't be a video and gallery on a page.

The logical way to do this is make three seperate content types, an article, a video and a gallery. However, since they all function about the same and an article could be about a video or a slideshow. Nevertheless, there isn't a case where a slideshow and video should be together. If they user wants video and images they can embed images through wysiwyg.

Using the #state mechanism, I have a select radios field that has the option of none, video, or image / gallery. This is set to hidden in the content display interface. If they choose image then the file field widget shows and if they choose video then the youtube field shows (once again I could use Media but that is huge and overkill for this application.)

---

**The interface is quite sweet.**

---

.

---

**However, there is a problem because here a slideshow gallery has been created before the user decided to use a youtube video embedded.**

---

What is the best practice for hiding the image gallery if the Youtube setting has been choosen? Do I make the media setting visible and then hide it and the image gallery? This doesn't make good sense because it is processed and therefore ineffient doing extra work. I don't want to force the form field to be deleted because then the work is lost. It just shouldn't be processed rather than have work deleted in the case the user would like to revert from one to the other. Any ideas?

EDIT:

I tried this code which works but I don't know if it's the best practice.

```
function helper_preprocess_node (&$variables) {
  switch ($variables['type']){
    case 'article':
      if (isset($variables['field_article_media'][0]['value'])){
        if ($variables['field_article_media'][0]['value'] == 'gallery'){
          unset($variables['content']['field_youtube']);
        }
        if ($variables['field_article_media'][0]['value'] == 'video'){
          unset($variables['content']['field_image']);
        }
        unset($variables['content']['field_article_media']);
      }
      break;

    default:
      break;

  }
}

```

# Answer
> 1 votes
You are right, a 3rd party module is overkill for this! I often find myself using a small js file to spice up the #states behavior. You can pretty much even bybass #states totally with this mecanism, but hey. #states is the drupal way of doing things. That does not mean it can't be assisted with JQuery.

Here is a quick snippet of my current quick project that is a form in a webform using the techniques (#states + jQuery) to tweak many things in the ui depending on what options are selected. This code should be in a .js file, loaded in module by the module's `.info` file, or you can have it in a drupal\_add\_js call.

I left all in there so you can see how with jQuery you can control fieldsets, option boxes and most anything you can think of. Notice also if you fancy as a bonus you can integrate all the jquery native animation functions like fadeIn() fadeOut(). There are also examples of that in the code below.

```
(function ($) {  // Notice code is in a behavior, use your module name
  Drupal.behaviors.yourModuleNameHere = {
    attach: function (context, settings) {

  // On load hide stuff. This will be shown when options are selected.
  $('#webform-component-inscription--enfant-1').removeClass('collapsed');
  $('#webform-component-inscription--enfant-2').removeClass('collapsed');
  $('#webform-component-inscription--enfant-1').hide();
  $('#webform-component-inscription--enfant-2').hide();
  // $('.form-submit').hide();

  $('#webform-component-inscription--information-supplementaire').hide();
  $('#edit-submitted-inscription-nombre-denfants', context).change(function () {

    var selected_option = $(this).val();

    if(selected_option === "1"){
        $('#webform-component-inscription--enfant-1').removeClass('collapsed');
        $('#webform-component-inscription--enfant-1').fadeIn(800);
        $('#webform-component-inscription--enfant-2').fadeOut(800);
        $('.form-submit').fadeIn(800);
        $('#webform-component-inscription--information-supplementaire').fadeIn(1000);
    }
    else if(selected_option === "2"){
        $('#webform-component-inscription--enfant-1').fadeIn(800);
        $('#webform-component-inscription--enfant-2').fadeIn(1500);
        $('#webform-component-inscription--information-supplementaire').fadeIn(2200);

    } else {
          $('#webform-component-inscription--enfant-1').fadeOut(800);
          $('#webform-component-inscription--enfant-2').fadeOut(800);
          $('.form-submit').fadeOut(800);
          $('#webform-component-inscription--information-supplementaire').hide();
          console.log("in extra information.");
         // $('#webform-component-inscription--enfant-1').addClass('collapsed');
        //  $('#webform-component-inscription--enfant-2').addClass('collapsed');
        }
      });
    }
  };
}(jQuery));

```

Of course, this method I am using *only acts on the presentation layer*, if the fields you want to act on needs to be validated, a server-side call is probably needed anyways and your method is probably better in that case.

---
Tags: theming, entities
---


title: PHP Argument input

text:
# Question
Title: PHP Argument input
Is there a possibility in Views 3 to provide the Argument input by a PHP snippet? I couldn't find an option for this anywhere.

I try to get the input from a query string value. I know this is an option within Views but I don't get that working so I want to try it with PHP.

# Answer
Possible using Views PHP. I have used this module with success. Here is a quote about it (from the module's project page):

> ... allows the admin account (user 1) to add fields, filters and sorts to views which use PHP code. It also supports additional accounts when the core PHP Filter module is enabled.
>
> This is the successor of Views Custom Field for both D6 and D7. The D6 version supports both Views 2 and Views 3.
> 1 votes

# Answer
No need of any other additional module. Enable PHP filter module. You will be able to see some screen like this.
> 2 votes

---
Tags: views
---


# Question
Title: How can menu title be included in breadcrumbs?
I have menu block with title 'Content'. It has several links. Breadcrumbs are made throw template.php by splitting url. Is it possible to include menu name before last link (which is content title) in breadcrumbs? I need to make it for all custom menu block links.

# Answer
> 1 votes
You can make use of `drupal_get_title`

> The title is displayed on the page and in the title bar.

Alter breadcrumb code accordingly.

---
Tags: breadcrumbs
---


# Question
Title: How to consume custom fields in RSS feeds
I'm sharing data between two Drupal sites using the Aggregator and Views modules. This works, but the source server places CCK fields within the description field; when I try to use those fields in the destination view (for example, to filter content), the view doesn't render the CCK fields.

Is there any way to make the CCK fields render as regular fields in the RSS, like title or author?

# Answer
For this situation I prefer using the Services module, then enable a rest server and using the index. Here is an excerpt about it from the module's project page:

> A standardized solution of integrating external applications with Drupal. Service callbacks may be used with multiple interfaces like REST, XMLRPC, JSON, JSON-RPC, SOAP, AMF, etc. This allows a Drupal site to provide web services via multiple interfaces while using the same callback code.
> 0 votes

---
Tags: views, feeds
---


# Question
Title: jQuery error "C is undefined" while making ajax call for pagination
I am using Ajax for pagination for a form in Drupal 6 project. It is working fine on my local machine with default theme but on live server it gives me an error and generates another pagination links below original one.

When I click on Next, Previous or page link it gives me an error "c is undefined http://siteurl/sites/default/files/js/js\_2ebf7f4036f86f9133a99317ed832acf.js/eval/seq/1 Line 1". Every time I click on link, it gives me the same error.

I have searched for some solutions, like http://drupal.org/node/846026, but they are not useful

# Answer
> 1 votes
Finally I fixed it. But I think there should be better way of doing that. All I did was, I added latest jQuery file from Google CDN in the module itself as it was clashing with Drupal 6 dynamically added jQuery 1.2.x and giving me error.

```
 drupal_add_js(drupal_get_path('module', 'my_module') . '/my_module.js');

```

I used some ajax calls for pagination, due to which old jQuery was giving me an error. It is fixed with newer version of jQuery. I also tried http://drupal.org/node/1058168 but it was also not useful.

Please suggest if there is any better way of doing the same.

---
Tags: 6, javascript, paging
---


# Question
Title: Disable modules when browsing mobile site
I have a site that also serves its content to mobile devices. As these sites(desktop/mobile) uses same code. I have a problem in performance since the modules being used in desktop site is also loaded in mobile site even if I'm not using it. Is there a way to excludes those modules(custom/contrib) without hacking each modules? Any good idea in this kind of situation?

Hi Patrick...something like this code I created so far...but I'm not sure if this is feasible.

```
function array_search_regex($pattern, $array) {
        for($x = 0; $x < count($array); $x++) {
            if(preg_match($pattern, $array[$x])) {
                return true;
            }
        }
      return false;
  }

  //Collect all css and place in an array
    $get_all_css = array();
    $get_all_css = drupal_get_css();

    //Put the return html styles in an array
    $ret_all_css = explode("\n", $get_all_css);
    //Get the array index of the matched in the search
    //$lookup_css = array_search('<link type="text/css" rel="stylesheet" media="all" href="/modules/node/node.css?G" />', $ret_all_css);
    $lookup_css = array_search_regex("/<link type=\"text\/css\" rel=\"stylesheet\" media=\"all\" href=\"\/modules\/node\/node.css\?.\" \/>/", $ret_all_css);

    //Unset the searched styles.
    unset($ret_all_css[$lookup_css]);

    //Return all essential styles. This should replace $styles in page.tpl.php
    $styles = implode("\n", $ret_all_css);

```

# Answer
The load caused by modules is handled by the server, so merely having the modules enabled will not affect the performance of your mobile site. In any case, it is impossible to disable the modules because you could be serving web pages to both mobile and desktop machines at the same time.

Instead, what you want to do is add a mobile theme. There are lots of ways to do this but the Mobile Tools module is a good way to get started.

For a more specific solution, you'll have to identify which modules are causing the performance problems on your site so that workarounds can be found.
> 3 votes

# Answer
I can see you don't mind having your hands dirty coding but I suggest to check out available Drupal responsive themes. These automatically recognize the user's device and can provide separate css based on that. I use drupal.org/project/omega and http://drupal.org/project/adaptivetheme.
> 1 votes

---
Tags: 6, performance, theming
---


# Question
Title: Comment migration working? (D5 --> D7) View displaying comments not
I thought I had this piece of the migration sorted, but I'm not sure what's off. As far as I know these are the places comment info is stored:

* comment
* field\_data\_comment\_body
* field\_revision\_comment\_body
* node\_comment\_statistics

I'm using a stored procedure to migrate the comments from the D5 db to the first three tables in the above list, the data appears to match what's generated by the native comment submission. After the stored procedure I run `devel_rebuild_node_comment_statistics();`

The results in the node\_comment\_statistics table look promising but some comments (rather their record in this table) are missing, or (after typing this all out) I'm realizing that this table probably doesn't store a record for every comment, just the last comment for that node (and comment count, etc).

Regardless, some comments won't display, even though their db records appear the same as neighboring comments that do display. I suspect this has to do with a subtle change in how the comment hierarchy is stored?

Also, (could be coincidence), one of the MIA comments did not have a record in the node\_comment\_statistics table, but this may be normal/works as designed.

The SQL statement within `devel_rebuild_node_comment_statistics();` MIGHT be part of my issue (not blaming the function because it may not have been designed for how i'm using it) here is the function's SQL:

```
  SELECT c.nid, c.cid, c.created, c.name, c.uid, c2.comment_count FROM {comment} c
  JOIN (SELECT c.nid, MAX(c.created) AS created, COUNT(*) AS comment_count FROM {comment} c WHERE STATUS = 1 GROUP BY c.nid)
  AS c2 ON c.nid = c2.nid AND c.created = c2.created

```

Let me know if you need more info, or have an approach suggestion. Thanks!

**UPDATE**: So on a clean D7 install w/ devel generate, i'm seeing that a record is created not for every comment, but for every node in node\_comment\_statistics. The zero comment records are probably not related to my issue. Comparing the results of `devel_rebuild_node_comment_statistics();` to native comment storage, everything seems fine w/ the function, so something is wonky in my comment migration.

# Answer
> 0 votes
Things I learned today, yes it took me all day, and I learned a lot. Like to test your assumptions. Test them early and verify the problem you're trying to solve in fact is in the place you are looking.

My debacle outlined above was completely separate from all the comment tables. The maddening part, was I narrowed it down to the comment bodies not appearing (or so I thought) because I was using a view to display the author's name, followed by the comment. Where this view pulled the author name from was the comment table, where the author's name wasn't was in the users table, I hadn't run the user migration in a couple weeks & enough users had joined & commented that, well, you get the picture.

Also contributing to the madness was the lack of information in the error messages, I kept getting malformed entity exceptions, which is probably because I was using views to display the comments.

Something else I noticed, that a comment's initial changed time is a few seconds before it's created time, not sure that's a bug, but definitely a quirk.

---
Tags: comments, migrations
---


# Question
Title: Multi-site installation and one theme: how to know on which multisite user is?
I have Drupal multisite, where I have three different sites. THey all use same theme. Now I would need to do small changes to templates that only visible on some sites. How can I tell on template level that what site is used.

For example on site 1's front page I would like to have:

Some content

But then on site 2's front page I dont want that div to be showed at all. Can I achive this somehow? Is theere "native" way to find out thie right site inside template, maybe in template.php?

Thanks.

# Answer
i would suggest doing multiple themes, one per site/group of sites - where they all have a common theme as parent.

that way you can overwrite specific elements on individual sites without having to worry about adding all the logic to check what site your currently rendering content for.
> 1 votes

# Answer
You may try to use this code. It worked for me perfectly in similar situation

```
// Allow a site-specific user defined CSS file (useful for multisite installations):
// If a CSS file "local-[SITE].css" is residing in the "css" directory (beside "local.css"),
// it will be loaded after "local.css". SITE is the site's host name, without leading "www".
// For example, for the site http://www.mydomain.tld/ the file must be called called "local-[mydomain.tld].css"
global $base_url;
$site = preg_replace("/^[^\/]+[\/]+/", '', $base_url);
$site = preg_replace("/[\/].+/", '', $site);
$site = preg_replace("/^www[^.]*[.]/", '', $site);
drupal_add_css(path_to_theme() . '/css/local-[' . $site . '].css', 'theme', 'all');

```
> 1 votes

# Answer
Since they're using the same theme you could use a condition based on the alias or full path. Hope that helps.
> 0 votes

# Answer
I am not sure if it has anything to do with what you are looking for, but couldn't you just add a condition on $base\_url variable?

Good-luck
> 0 votes

---
Tags: theming, multi-sites
---


title: Form API, Webform, or CCK?

text:
# Question
Title: Form API, Webform, or CCK?
Which module is good to create forms, the Webform module, or the CCK module? Which is best suited to interact with the database?

I want to create a search form that displays a list of employees; each record has an edit, and a delete button. Clicking on "edit" would display the edit form.

Which one is good to use for this scenario?

# Answer
The best solution is to define a content type (CCK) employee, then create a view that list your employees; in your case the search button will an exposed filter with criteria match any of the name, last name, job, or any field you want search for (you can have all of them at the same time to make search more easier). By default views provide for administration a field named node edit link, and delete link so this will let you administrate your employees, but for more advanced administration of employees I advise you to use views bulk operation.

Webform will not gives you the possibility to do this; generally Webform is used for when you want to collect data from users and have statistic of it, like in a customer survey.
> 1 votes

# Answer
I would use the Views module for that; use exposed filters for the employees.

I have a similiar scenario running with events instead of employees.
> 0 votes

---
Tags: forms
---


# Question
Title: How do I override menu items with my own implementation?
My specific use case is this: I don't want users accessing the user/%user/edit menu. This is awkward because it's quite embedded in Drupal, e.g. forgotten password system. I want the drupal form for admins, but I want a different form for end-users because I do not want to expose certain user fields to them, and because some updates they may need to do need to be handled by an external database, so changing them in Drupal is unhelpful.

Using `hook_form_alter()` is not really going to cut it; it really does need to be quite a different form.

I had planned to override the user/%user/edit path by using my own module. This would then check if the accessing user was an admin, and if so, present the stock form, but if not it would `drupal_goto('client/updates');` but this doesn't work; my module's page callback never gets called.

# Answer
> 5 votes
You can use `hook_menu_alter()` to reroute the request for that page to your own module's functions:

```
function MYMODULE_menu_alter(&$items) {
  $items['user/%user/edit']['access callback'] = 'MYMODULE_access_callback';
  $items['user/%user/edit']['page callback'] = 'MYMODULE_user_edit_page_callback';
}

function MYMODULE_access_callback($account) {
  if ($something) {
    return FALSE;
  }

  return TRUE;
}

function MYMODULE_user_edit_page_callback($account) {
  if ($something) {
    return drupal_get_form('some_form');
  }
  else {
    return drupal_get_form('some_other_form');
  }
}

```

---
Tags: 7, routes, users
---


# Question
Title: The right way to validate fields via hook_node_validate
Rather than creating a new field via the Field API, and as a quick workaround, I've added a simple text field to a content type that I'm now attempting to validate via `hook_node_validate()`. Unlike previous versions of Drupal, the value for this field is not simply available as `$node->field_name` or `$form['field_name']`, but instead as a nested array containing a variety of other information.

My question then is this: what is the 'correct' and therefore most future proof way to retrieve the value for this field? Am I supposed to be using the likes of `field_view_value()` or `field_view_field()`, or is it acceptable to simply reference `$node->field_name['und'][0]['value']` for example.

# Answer
`field_get_items()` is the one you're looking for:

```
$items = field_get_items('node', $node, 'field_FIELD_NAME');
$first_value = $items[0]['value'];

```

It also takes care of language selection for you, so no need to worry about that one any more.
> 3 votes

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