# Question
Title: Is there a module or method for processing and generating codes for music download cards?
I'm looking for an easy way to add download card functionality to my Drupal 7/ubercart site.

In case you are wondering, by "Download Card" I mean an actual physical object that a band can sell at a gig. The card has a code on it and a URL. The buyer goes to the URL, enters the code and they are allowed to download MP3 files, etc.

There are plenty of pay options for this (CDBaby, Dropcards...) but a Drupal option would be fantastic. The Drupal site would need to both generate the codes and export them into a spreadsheet or similar so that we could print them out on to cards. The site would, of course, also have to be able accept the codes and only allow users with the correct codes to download their music.

Does something like this exist for Drupal?

# Answer
Well I'm unaware of a turn-key (Drupal Distribution) for a Dropcard ecommerce site per se. The components exist to make such a site using some custom code. Some example modules that fit your use-case are:

TokenAuth

> Token Authentication provides a token for use in the URL to authenticate users to your site. It only works on paths configured in the settings page.

Commerce File

* Ability to limit access to the file with limit settings
* Default limits: duration, download count, IP address count
* Limit default values can be inherited at the product level such that the product always uses the current default value
* After purchase of a file, limits are statically recorded to the line item so that they do not reflect any changes to the product's file limits.
* A user's limits reflect changes to an order, even after order is completed. Order deleted, canceled Line item deleted, update
* Utilizes Rules to control workflow for:
    + File download access: controlling access and reacting to access denied
    + Order workflow: issuing access licenses and revoking access licenses in the order

Views Data Export -- export your authentication links to paper cutouts.

> This module is designed to provide a way to export large amounts of data from views. It provides a display plugin that can rendered progressively in a batch. Style plugins are included that support exporting in the following types:
>
> CSV, Microsoft XLS, Microsoft DOC, Basic TXT, XML.

Commerce Module

> uhh make an eCommerce site using drupal.

Many of these modules likely make use of Drupal core concepts for Entities, Cron Jobs and likely Queues. You may find the Queue API useful to build the authentication tokens for example every hour for new audio content.

The ingredients exist for a developer to create what you're asking for, good luck.
> 1 votes

---
Tags: 7, files
---


title: Drupal 7 Block View include File

text:
# Question
Title: Drupal 7 Block View include File
I have a rather newbie question, I am following a Drupal 7 module examples, specifically an ajax wizard form. All form creation / manipulation is included in ajax\_example\_graceful\_degradation.inc which when is called in file attribute:

```
// A classic multi-step wizard, but with no page reloads.
  // See ajax_example_graceful_degradation.inc.
  $items['examples/ajax_example/wizard'] = array(
    'title' => 'Wizard (with graceful degradation)',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('ajax_example_wizard'),
    'access callback' => TRUE,
    **'file' => 'ajax_example_graceful_degradation.inc',**
    'weight' => 7,
  );

```

Next i would like to create a block which will be included in my template. It seems that i cant include a file attribute in block\_view function. How can I do that? Note: If I include all fuctions of ajax\_example\_graceful\_degradation.inc in .module file then my block works ok.

# Answer
What @anil sagar said is correct. i think you are misunderstanding how `hook_menu()` functions. Remember, `hook_menu()` "enables modules to register paths in order to define how URL requests are handled." a block doesn't really register a path as it is part of the content of a node (content, article, blog, whatever). Hopefully that part makes some sense... let me know if it doesn't.

So you don't necessarily need the `hook_menu()` function for blocks (although exceptions can always been seen). Again, you'll need to write your code in your `my_cool_block.module` using the above stated hooks `hook_block_info()` and `hook_block_view()`.

however, you could `include` a file that has other custom module specific code in there. i tend to write my code with drupal hooks always in the `my_module.module` file. any supporting code i write either in a class or static class
> 1 votes

# Answer
There is no such an attribute in block\_view function, but you can always use something like that (assuming that you have already implemented hook\_block\_info() and you have defined your own MYBLOCKDELTA):

```
function MYMODULENAME_block_view($delta = '') {
  switch ($delta) {
    case 'MYBLOCKDELTA':
      $block['subject'] = t('This is my block');
      module_load_include('inc', 'MYMODULENAME', 'my_inc_file');
      $block['content'] = myblock_contents($delta);
      break;
  }
  return $block;
}

```

Then define function myblock\_contents($delta) in your my\_inc\_file.inc in MYMODULENAME module folder.
> 3 votes

# Answer
Please find answers for your question.

* You can create a block using hook\_block\_info() and hook\_block\_view($delta = '')
* Hooks should be written in .module file not in any other files inside module.
* So, create two functions in your.module file which will implement above two hooks to expose a custom block from module.
* You need to enable the block you created using administer blocks page.
* If you want to embed your block using code any where you can use below code !

$block = module\_invoke('module\_name', 'block\_view', 'block\_delta'); print render($block);

Hope it clarifies you !
> 1 votes

---
Tags: 7, forms, blocks
---


# Question
Title: How to create a horizontal views slideshow of content in views?
I want to create a content slider in drupal 6 similar to what exists here

I am using views 3 on my site.

# Answer
> 0 votes
Finally solved it.

I used the als jquery code to accomplish this. Its very light and loads very fast.

Just follow the procedure they explain and you will be done. One might face difficulty in using this code in drupal 6 as it requires jquery-1.5 or higher. But you can surely find ways to update jquery to required version.

I hope this helps others looking to do similar things.

# Answer
> 0 votes
You can use Views Slideshow module for this.

> Views Slideshow can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.

You can read tutorial here: http://drupal.org/node/755010

Demo: http://drupalmultimedia.org/slideshow

# Answer
> 0 votes
You can also use views\_nivo\_slider or views\_slideshow\_ddblock in Drupal 6. According to the example which you gave it seems you need to create slider using views and create the custom template for view to display the same.

---
Tags: javascript, views
---


title: Drupal 7 - Node Clone Alternatives

text:
# Question
Title: Drupal 7 - Node Clone Alternatives
just want to ask if there are any other suggested alternatives for cloning a node for drupal 7. Now I know most of you will answer "Node Clone Module", but is there any other module out there that can do the same thing? Thanks.

# Answer
> 1 votes
"Drupal way" is to collaborate, not compete. It means that anyone wanting to write his own cloning solution will be asked to cooperate with author of existing one to provide what he finds lacking. Only if that's not possible, and some basic differences in approach or expected results are found, community will welcome new module. Otherwise it'll just die silently, unloved.

That said, you can use node exporting and importing tools to export nodes, edit them or not and import again, possibly under new `nid`. Node export is example of modules that can do that. Probably there are other ways to get content duplicated, and if you can think of basically different scenario, there is a big chance someone got that implemented.

---
Tags: 7
---


# Question
Title: Why do pages not load for one user but do so for me if we use the same login?
A user (who has nearly the same rights as the admin account) logs in and gets the page below. He cannot access any links to perform his duties. The screen shot is below. However, I am able to use the same username and password on my end and I get no errors when I log in or when I click on links--pages come up perfectly. Yet, he has to keep hitting the back button in his browser for something to eventually come up. He's tried different browsers, internet connections, computers, etc. All have the same negative result. Does anyone have an idea why Drupal is behaving this way? why would the results be different if we are both logging in using the same account and thus with the same permissions? (not at the same time, of course).

It appears to have to do with the 302 document has moved, but it doesn't explain why it hasn't moved for me, but yet it has for him.

# Answer
Look at the 0 at the beginning of the output. It is illegal character there. It can confuse browsers, and it seems it's the case for your user. Find a code part that outputs it and remove it, and you should be good.

Second thing - it seems he would fall into infinite redirect loop if not that 0. Page he sees under ntu.tipplers.org.uk says it's 302 redirect to ntu.tipplers.org.uk - possible bad thing, unless I'm missing something. Carefully examine redirect modules you're using. If it's only about adding `/` at the end, consider moving this rule to `.htaccess` as it is way faster and this rule will be called great many times. If it is indeed a loop, find out in your settings why he sees it, and you do not.
> 1 votes

---
Tags: users
---


# Question
Title: If I delete openenterprise module from drupal module folder site is collapse
I am wrongly paste the open enterprise module in drupal module folder. If I try to delete that folder total site is collapsed. How to fix this issue.

# Answer
> 0 votes
You will need to rebuild the registry. The simplest solution is to use Drush and Registry Rebuild. There's also instructions on that page in case you can't use Drush or the command line.

---
Tags: 7
---


title: Clean URL for custom content

text:
# Question
Title: Clean URL for custom content
I have a custom content type movie. Now, when I visit any of the movie content, the url is like:

```
mysite/?q=node/someNumber

```

I want that every movie content will have url like

```
mysite/movie/somenumber

```

or,

```
mysite/?q=book/someNumber

```

How to do this?

I am using Drupal 7.

# Answer
> 6 votes
Enable Clean URL + get Pathauto module, which allows to define custom URL patterns for every type of content

If the Clean URL test fails, the web-server is not configured to support this feature. You need to configure the web-server to support Clean URL.

With Apache HTTPD as web-server, you have to enable `mod_rewrite` and configure the necessary rewrite rules. The rewrite rules can be found in the `.htaccess` file that comes with Drupal. Usually, theses rules are applied automatically, when `mod_rewrite` is enabled, but in some cases, the `AllowOverride` directive is too restrictive to allow this.

See Clean URLs in the Drupal Installation Guide for a more thorough introduction on how to get Clean URLs working in Drupal.

# Answer
> 0 votes
Enable Clean URL, then install and enable the Pathauto module, which allows to define custom URL patterns for custom content.

If the "Clean URL test" fails, you need to enable Apache's `mod_rewrite`.

Usually, it is suffiscient to put this in `.htaccess`:

```
RewriteEngine on
RewriteRule ^en/(.*)$ $1

```

If the above two line don't fix the problem, your web server is not set up to allow rewrite rules. In that case, it is necessary to enable an extension to the Apache web-server known as `mod_rewrite`. You do this with the following shell command:

```
sudo a2enmod rewrite

```

Then navigate to `/etc/apache2/sites-available` and edit the file named `default`. Locate the following block of text:

```
<Directory /var/www>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

```

And change the `AllowOverride` directive to:

```
<Directory /var/www>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
    Order allow,deny
    allow from all
</Directory>

```

When done, restart Apache.

```
sudo service apache2 restart

```

(The above example is assuming you're running a standard Apache configuration on Ubuntu ver. 12. YMMV, and you may have to dig out the documentation for your system to see how to do something similar.)

---
Tags: uri
---


# Question
Title: How do I 'programaticaly' create a new content type with hook_install in D7?
I am trying to create a .INSTALL file which creates a content type (Apples) for my module (Fruit). I have dropped the following file (fruit.install) into my module folder with the .INFO file and .MODULE file. After enabling the Fruit module, I look into the database and find that there is no new entry in the node\_type table. I must be missing a vital step? or I have made an obvious mistake, I think?

```
<?php

/**
 * Implements hook_install()
 */

function fruit_install() {

    // * If the content type does not exist then create it.
    if (!in_array('Apples', node_type_get_names())) {
        $type = array(
            'type' => 'apples',
            'name' => 'Apples',
            'base' => 'node_content',
            'custom' => 1,
            'modified' => 1,
            'locked' => 0,
        );
        $type = node_type_set_defaults($type);
        node_type_save($type);
        // * Set 'Apples' options
        variable_set('node_preview_apples', 0);     // Set 'Preview before submitting' to 'Disabled'
    }
}

```

# Answer
> 2 votes
The reason I was not seeing my 'Apples' content type appear in the node\_type table was because I did not realise that I had to uninstall my module then reinstall it every time I wanted to test my code changes. I was just disabling the 'Fruit' module and expecting my .INSTALL file to do its work when I re-enabled the module again. You have to disable ***and*** uninstall (not just disable) then re-enable. Apparently you can manually remove the module from the system table also, but I did not go there.

The code I pasted in above does work - although it may not be the 'correct' way of creating a content type. I'm not sure. My method mirrors how I would acheive the same with the Field UI: Add a new content type, set the content type options, add any new fields, then create the required instances of those new fields. This seems logical to me, but you may find the other solutions suggested here to be better.

# Answer
> 1 votes
You can look at what the Forum module does.

* forum\_install() sets the node\_options\_forum Drupal variable
* forum\_enable() creates the vocabulary referred from that field, the taxonomy field to use with the Forum content type, and adds the body field to the content type

It doesn't call node\_type\_set\_defaults(), nor node\_type\_save(). Eventually, `forum_enable()` calls node\_types\_rebuild(), which calls any implementation of hook\_node\_info(), including the one done from the Forum module itself.

```
  foreach (module_implements('node_info') as $module) {
    $info_array = module_invoke($module, 'node_info');
    foreach ($info_array as $type => $info) {
      $info['type'] = $type;
      $_node_types->types[$type] = node_type_set_defaults($info);
      $_node_types->types[$type]->module = $module;
      $_node_types->names[$type] = $info['name'];
    }
  }

  // …

  if ($rebuild) {
    foreach ($_node_types->types as $type => $type_object) {
      if (!empty($type_object->is_new) || !empty($type_object->disabled_changed)) {
        node_type_save($type_object);
      }
    }
  }

```

Another module, which doesn't need to add any field to the content type, except the node body, does all in blog\_install().

```
function blog_install() {
  // Ensure the blog node type is available.
  node_types_rebuild();
  $types = node_type_get_types();
  node_add_body_field($types['blog']);
}

```

In short, creating a content type just require two steps (if the content type doesn't use extra fields):

* Implement `hook_node_info()`
* Call the following functions: `node_types_rebuild()`, node\_type\_get\_types(), node\_add\_body\_field()
* Change the value of specific Drupal variables, if values different from the default ones are going to be used

# Answer
> 0 votes
First thing: Don't put all that code inside `hook_install()` itself. Instead, declare another function, perhaps in an include, that creates your content type, and call it from `hook_install()`.

The functions you'll want to create are instances of `hook_node_info()` and `hook_form()`:

```
//CREATE NEW CONTENT TYPE
function fruit_node_info() {
  return array(
    'event' => array(
    'name' => t('Apple'),
    'base' => 'event',
    'description' => t('An apple content type'),
    'has_title' => TRUE
    ),
  );
}

function apple_form($node,$form_state) {
  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => t('event Title'),
    '#default_value' => !empty($node->title) ? $node->title : '',
    '#required' => TRUE,
    '#weight' => -5
  );
  return $form;
}
//END CONTENT TYPE

```

(This is adapted from this stackoverflow question. I have not personally tested it.)

The code you're using doesn't appear to make use of `hook_node_info()` or `hook_form()` at all, which could be the reason your node type isn't showing up. I also notice that your function doesn't return anything, and that you're setting variables after you've already saved your node type, all of which could be contributing to your problem.

---
Tags: hooks, installation
---


# Question
Title: Pathauto URL alias not working (using nginx)
I'm having several problems with URL paths (Drupal 7). I think they are related with nginx configuration, because I'm experiencing this problems since I migrated the site from an apache server to an nginx server. I'm not a programmer/sysadmin and new to nginx, so it's probably (99%) a simple problem of misconfiguration.

The symptoms are the following:

* Not aliased paths (node/15 for example) works OK always
* Aliased paths works only when I create the alias manually (node by node editing in admin/config/search/path).
* Aliased paths created via pathauto never works (alias are created but they when you open the aliased path you get "page not found").
* Bulk update option (admin/config/search/path/update\_bulk) gives me "Access denied" after clicking the "Update" button, but works when I deactive the clean URLs (the same happens also with theme selection, flush caches and probably other things: I get "access denied" with clean URLs activated and works OK with clean URLs deactivated.

I've tried several nginx configurations found in pages related with drupal and not related with drupal, all without any luck (most give me a 502 bad gateway, like for example this http://wiki.nginx.org/Drupal).

One of the few that "works" (it gives no errors and works for non-aliased paths, but doesn't work for aliased paths) is the following:

```
server {
 root /path/to/drupal;
 index index.php index.html index.htm;

 server_name example.com;

 location / {
    try_files $uri $uri/ /index.php;
 }

 location ~ \.php$ {
    #fastcgi_pass 127.0.0.1:9000;
    # With php5-fpm:
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
 }
}

```

# Answer
I'm pedrogon (the user that asked the question). I can't access my Stack Exchange account, but I've managed to solve my problem, and I want to post the solution for anybody in my situation.

I had two different problems (not related with each other) that were causing the "symptoms" described in my question:

1. The problems with clean URLs, theme selection, etc. where caused by nginx misconfiguration. The line "try\_files $uri $uri/ /index.php;" should be "try\_files $uri $uri/ /index.php?q=$uri&$args;"
2. The problems with the Pathauto module were caused by multilingual configuration. I've created nodes in one language and then turn the site to another language. Aparently the Pathauto module doesn't work in this situation. I had to change the language of all the nodes (using VBO) and then the Pathauto module started to work.
> 1 votes

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


# Question
Title: RDBMS-independent way to get table primary key?
Let's assume we have Drupal instance with second database connection. Tables in that second database are shared between many systems and thus **was not created using Drupal's schema** functionality. How do I get the name of the primary key, in a universal way that doesn't dependent on the RDBMS? Is there a way that will be equally good for all databases?

For MySQL I can use db\_query and:

```
SHOW INDEX FROM {table} WHERE Key_name = "PRIMARY"

```

and for SQL-92 compatible ones:

```
SELECT pk.TABLE_NAME, c.COLUMN_NAME primary_key
  FROM information_schema.table_constraints pk
  JOIN information_schema.key_column_usage c
    ON c.table_name = pk.table_name
   AND c.constraint_name = pk.constraint_name
 WHERE constraint_type = 'primary key'

```

Thanks to T I's answer on stackoverflow.

What happens with Oracle or Apache Derby? I know I can find specific solutions, but I wonder if there is a Drupal way. I couldn't find one outside schema.

# Answer
> 1 votes
### For non-Drupal tables

I don't think there is a cross-db drupal way to do this currently.

It would have to be added to the database schema class for each database type. For example, see the mysql database schema class and look at something like addIndex.

Something similar could be done for `showIndex()`. If it is added for all the different database handlers, it would then be able to be safely used.

Then a database API function would have to be added for easy calling.

For example you would need a `db_show_index()` function in database.inc like db\_add\_index().

### For Drupal defined tables

You can use drupal\_get\_schema() and get the schema for a table; then, get what you need from that. It will return a schema as defined in hook\_schema().

You might also be interested in some of the other schema API functions.

The schema will only be what was defined in hook\_schema though. It won't pick up anything that has been added or changed outside of that.

---
Tags: 7, database
---


# Question
Title: How to theme webform elements (radio buttons etc.)?
I would like to know **how to theme Drupal 7 Webform elements?** I want to change the HTML structure of every element, not just wrap form with div or something like that. And I want to leave theme's elements as they were.

EDIT: I would like to add class to label and input type radio button.

# Answer
Each webform element has it's own file in the "components" sub-directory of the webform module folder.

If you look in those files there is a \_webform\_theme\_COMPONENTTYPE() function, for example \_webform\_theme\_date() for the date fields.

This function defines the theme functions for that field type.

These theme functions are what you can use to override the themeing of the fields.

For exmaple theme\_webform\_date() can be overridden as THEMENAME\_webform\_date(&$variables) and you can change the output.

If it is things like the field wrappers or labels you want, then look at overriding the theme\_webform\_element() function.

That will let you do things like change where the label is printed in relation to the field.

You can use `$element['#type']` to single out specific field types in that theme function.

**Note:** Webform components are a special case. Normally you can find themeable things by looking in the MODULENAME\_theme() function. In this case webform\_theme().

**Specifically, to set classes on radio button fields:**

You requirement of adding the class to a radio button is unfortunately a bit different. This is because webform doesn't use it's own themeing, it uses drupal core's

So what you want is theme\_radios() and/or theme\_radio() and/or theme\_form\_element\_label().

Something like these (there are comments to tell you what has changed):

```
/**
 * Theme a set of radio buttons.
 */
function THEMENAME_radios($variables) {
  $element = $variables['element'];
  $attributes = array();
  if (isset($element['#id'])) {
    $attributes['id'] = $element['#id'];
  }
  $attributes['class'] = 'form-radios';
  if (!empty($element['#attributes']['class'])) {
    $attributes['class'] .= ' ' . implode(' ', $element['#attributes']['class']);
  }
  if (isset($element['#attributes']['title'])) {
    $attributes['title'] = $element['#attributes']['title'];
  }

  // Add custom classes.
  // To target specific elements you can use the $element variable.
  // You can target the label using:
  // .your-custom-class label
  $attributes['class'] .= 'your-custom-class another-custom-class';

  return '<div' . drupal_attributes($attributes) . '>' . (!empty($element['#children']) ? $element['#children'] : '') . '</div>';
}

/**
 * Theme a single radio button.
 */
function THEMENAME_radio($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'radio';
  element_set_attributes($element, array('id', 'name','#return_value' => 'value'));

  if (isset($element['#return_value']) && $element['#value'] !== FALSE && $element['#value'] == $element['#return_value']) {
    $element['#attributes']['checked'] = 'checked';
  }
  _form_set_class($element, array('form-radio'));

  // Set custom classes.
  // Use $element to target specific fields.
  $element['#attributes']['class'][] = 'your-custom-class';
  $element['#attributes']['class'][] = 'another-custom-class';

  return '<input' . drupal_attributes($element['#attributes']) . ' />';
}

```

Unfortunately it is not possible to add classes to a label except for overriding theme\_form\_element\_label() because of this bug.

The are two possible ways to address this in the theme layer.

One is to add the class to the field wrapper and then target the labels via that in your css or js.

The other is to override theme\_form\_element\_label() like this:

```
/**
 * Theme a form element label.
 */
function THEMENAME_form_element_label($variables) {
  $element = $variables['element'];
  // This is also used in the installer, pre-database setup.
  $t = get_t();

  // If title and required marker are both empty, output no label.
  if ((!isset($element['#title']) || $element['#title'] === '') && empty($element['#required'])) {
    return '';
  }

  // If the element is required, a required marker is appended to the label.
  $required = !empty($element['#required']) ? theme('form_required_marker', array('element' => $element)) : '';

  $title = filter_xss_admin($element['#title']);

  $attributes = array();
  // Style the label as class option to display inline with the element.
  if ($element['#title_display'] == 'after') {
    // Changed to make class an array.
    $attributes['class'][] = 'option';
  }
  // Show label only to screen readers to avoid disruption in visual flows.
  elseif ($element['#title_display'] == 'invisible') {
    // Changed to make class an array.
    $attributes['class'][] = 'element-invisible';
  }

  if (!empty($element['#id'])) {
    $attributes['for'] = $element['#id'];
  }

  // Add your classes here.
  // If you are using variables to make the class use the drupal_html_class()
  // function.
  // To target specific elements you can use the $element variable.
  // For example, based on field type:
  if ($element['#type'] == '') {
    $attributes['class'][] = 'your-custom-class';
    $attributes['class'][] = 'another-custom-class';
  }

  // The leading whitespace helps visually separate fields from inline labels.
  return ' <label' . drupal_attributes($attributes) . '>' . $t('!title !required', array('!title' => $title, '!required' => $required)) . "</label>\n";
}

```
> 19 votes

---
Tags: 7, forms, webforms, theming
---


# Question
Title: How to override breadcrumbs defined by a module using a custom module?
Is it possible, using a module, to override a breadcrumd definition defined in another module's hook\_node\_view()?

* Module `property_bc` sets a custom breadcrumb for nodes of type `Property`.
* Module `property_bc_plus` wants to override that behaviour.

`property_bc` implementation of `hook_node_view` would be:

```
<?php
/**
 * Implementation of hook_node_view().
 */
function property_bc_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'property') {
    $breadcrumb = array();
    $breadcrumb[] = l(t('Home'), NULL);
    $breadcrumb[] = l(check_plain($node->name), "user/$node->uid");
    $breadcrumb[] = l(t('Properties'), "user/$node->uid/properties");
    drupal_set_breadcrumb($breadcrumb);
  }
}

```

# Answer
Different solution depending of your context.

* Change the module order by changing their weight: http://drupal.org/node/110238
* Use an other hook than is called later like hook\_node\_view\_alter
* Add a flag in your node and test against it

First module

```
 <?php
 function property_bc_node_view($node, $view_mode, $langcode) {
      if ($node->type == 'property') {
        $breadcrumb = array();
        $breadcrumb[] = l(t('Home'), NULL);
        $breadcrumb[] = l(check_plain($node->name), "user/$node->uid");
        $breadcrumb[] = l(t('Properties'), "user/$node->uid/properties");
        $node->custom_bredcrumb_is_set = TRUE;
        drupal_set_breadcrumb($breadcrumb);
      }
    }

```

In your other module

```
    <?php
    function property_bc_plus_node_view($node, $view_mode, $langcode) {
      if ($node->type == 'property' && isset($node->custom_bredcrumb_is_set) && $node->custom_bredcrumb_is_set != TRUE) {
        $breadcrumb = array();
        $node->custom_bredcrumb_is_set = TRUE;
        drupal_set_breadcrumb($breadcrumb);
      }

}

```
> 3 votes

---
Tags: hooks, breadcrumbs
---


title: How to translate mouse overs?

text:
# Question
Title: How to translate mouse overs?
I am using the field 'image' and have the 'alt' and 'title' options for the image. The 'title' shows on mouseover. How do I translate this? Or if it isn't translatable how can I show another field that is translatable as the mouse over?

# Answer
> 0 votes
The title mouse-over is translatable. I needed to enable the content type-\> edit -\> publishing options -\> multilingual settings and it works.

---
Tags: i18n-l10n
---


# Question
Title: D7 Views: content associated with a user via tags
I want to display a View of all content relevant to the logged in user based on tags that are defined in a node referenced by the user. Something that follows this relationship:

Logged in User --(references)--\> Customer Subscription -(shares tags with)-\> Content

The view should show all the Content associated with the user based on this logic. I prefer to do this via modules and not code.

Any ideas? Thanks!

# Answer
Maybe these links could be a good starting point, as they provide a step by step guide of how to configure views with a relationship to the current user:

http://blog.hsl.virginia.edu/drupalpress/show-users-any-content-that-matches-any-taxonomy-term-in-views/

http://blog.ampli.fi/filtering-a-drupal-7-view-based-on-a-user-profile-field/
> 0 votes

---
Tags: 7, views
---


# Question
Title: How do I allow a free product into a cart, but only if cart net value is above $10?
I'm interested in running a promotion ...

I'd like to make a product free if the customer's cart total is $10.

I was able to do that with this module: http://drupal.org/project/uc\_discounts\_alt

Everything is working great, but I don't want my customer to be able to add the product to their cart unless they are buying $10 worth of regular products.

The products I'm giving away could be placed in another ubercart class, but I can't find a module that will allow me to prevent the node from being sold unless the cart total is $10 or more.

Any ideas or help would be greatly appreciated.

I've already explored the "free" checkout options; I'm really simply looking how to make a product not sellable unless the cart total has a minimum of $10.

# Answer
To prevent your customers to add the product to their cart if it's $10 with regular products, You can use ubercart hook\_add\_to\_cart .

for example:

```
function MODULENAME_add_to_cart($nid, $qty, $data) {

 $contents= uc_cart_get_contents();
 //check your condition such as total, and product type based on cart contents
  if (condition true) {
    $result[] = array(
      'success' => FALSE,
      'message' => t('Sorry, you can not add this product now!.'),
    );
  }

  return $result;
}

```
> 1 votes

# Answer
Take a look at the Ubercart Restrictions module.

> This module will do its best to prevent the wrong sort of people from ordering the wrong sort of goods, or to ship them to the wrong kinds of places.
>
> For example, some products cannot be ordered by minors, or some products cannot be shipped to certain states
> 0 votes

# Answer
This link setting\_minimum\_price\_order\_can\_be\_submitted mentions that you can go to `admin/store/settings/cart/edit`. This might also help as it gives more details of achieving the task you require. I am not sure if your using drupal 6 or 7. This link is the url for the module ProductMin . I found uc\_product\_minmax module. Let me know if you need something more specific or if these are useful.
> 0 votes

# Answer
Learning the Rules framework could really help you here.

there is an excellent tutorial here by Johan Falk just follow along and you will be able to do the above in no time.
> 0 votes

# Answer
Rules can be the better solution to it as you don't want to restrict the user every time but just on some special products. Here is a general flow of what you can do.

1. Add a cck/ubercart class to the products that you want to add to the promotion
2. Then create a rule, and in there, add a condition to check whether that field which you added is set. If so, don't, add an action to not allow user to proceed to checkout.

This should work as far as I know.
> 0 votes

# Answer
I suppose **Minimum order subtotal** to $10 **admin/store/settings/cart/edit/basic** and Conditional Action/Rule for that product is not an option because you still want to sell other products...

Try `uc_discount` module and setup Conditional Action with *Check an order's product* condition and *Apply a discount* action.
> 0 votes

---
Tags: 6, ubercart
---


title: Cache warming in drupal7

text:
# Question
Title: Cache warming in drupal7
I have a drupal 7 website that uses Varnish for caching (through drupal's Varnish module). I want a cache warming mechanism that would automatically cache the latest version of the pages after the cache expiration time has passed.

How can i do this?

# Answer
> 2 votes
You could try the cache warmer module, which apparently does just that.

There are also a bunch of blog posts on the topic around the web.

---
Tags: caching, proxies
---


title: Overriding custom page variable

text:
# Question
Title: Overriding custom page variable
I created a template file (page-classifieds.tpl.php) for a classified page. I would like to override variables of this particular page preferably using a preprocess function.

How can I do that?

`hook_preprocess_page()` overrides variables for all the pages. I don't want that to happen.

# Answer
Try this:

```
/**
 * Variable preprocessor for the page template.
 */
function THEMENAME_preprocess_page(&$variables) {
  if (arg(0) == 'classified') {
    // Do things here.
    $variables['my_new_variable'] = 'Something';
  }
}

```

Note that the template page-classified.tpl.php will also match all sub paths of that page too, like:
yoursite.com/classified/something
yoursite.com/classified/something/something
> 1 votes

---
Tags: theming, 6
---


title: Describe my "special" table to views

text:
# Question
Title: Describe my "special" table to views
I'm developing a module, and there is a table that needs views integration. The table is not so special, but can't find a solution yet.

This is how my table looks: **nid\_a|nid\_b|data**

I would like to join this table to the node base table, with nid\_a as joining key, and nid\_b should come from a contextual filter (aka argument).

How can I achieve this?

System: Drupal 7.x and Views 3.x

# Answer
> 1 votes
Create a custom module and use the hook\_views\_Data. Here is a link for doing that

---
Tags: views
---


# Question
Title: How to sql-sync prefixed multi-site installations within the same database with drush?
I am running several Drupal 7 multi-sites that share same code base as well as the same database with prefixed tables per multi-site (some tables are shared too).

I chose this setup, because i need several sites, each representing a region. They share the same code but not the same content. (This is why i didn't chose Domain Access). The reason, why all multi-sites share the same database instance with prefixed tables is because i need cross-multi-site queries to aggregate global information. A context-switch within one database (by changing the table prefix whith `db_set_active`) is much "cheaper" than initializing a new database connection for every of the N regions.

Now I need to sync the data of one multi-site with the data of another multi-site within the same database. I thought Drush could easily do the job with:

```
drush sql-sync [from multi-site1] [to multi-site2]

```

But i recognized, that the sync is done per database and not based on prefixed tables... That sounds logical!

So the command above would sync \*\[same\_database\]\* with \*\[same\_database\]\*, but what i need is a script that runs like this:

```
sync [all prefixed1_ tables] with [all prefixed2_ tables] within same database

```

Now my question: Has anyone worked on synchronization of multi-sites within the same database before, or has anyone a hint on best practice for my synchronization-needs?

Edit: I found out, what my needs really are. Drush's sync is not a real "sync" it is more like a "export from and import to". So it is quite more simple than a complete synchronization-task with "insert", "merge" and "delete". So i am going to write my own drush's script to fulfill my needs.

# Answer
> 2 votes
sql-sync does not support prefixed database tables. There is work going on in the issue queue to support removal of cache tables via wildcard expressions. Perhaps this code could be adapted to support prefixed tables as well, if a motivated contributor would write and submit a patch.

# Answer
> 1 votes
Your safest, if not fastest, bet is to use Feeds. You can export data that needs to get synchronized from one site using Views, maybe Views Data Export. This little tool will create XML. It can be created on cron run and stored on your server's HDD. Then Feeds can use it to import nodes that needs importing.

Direct database manipulation is faster, but you are asking for trouble with node IDs and revisions, unless all you want is 1:1 content copy.

---
Tags: 7, database, multi-sites, drush
---


# Question
Title: Considerations displaying page titles in page or node template
This is very similar to this, hopefully its different enough to warrant its own question: How to display a field before node title?.

On our Drupal sites we have a dozen content types, many of which have custom node templates to control how they are rendered. We like this setup because our design/web production team can edit the template files easily but not more heavy drupal code.

However, we currently have only 1 page.tpl.php (we have a custom theme loosely based on bartik). In this template, we have ugly if-statements to make the page print different things based on the content type. Unfortunately, as the number of nodes increases this page.tpl.php is becoming unwieldy. The problem is that each node usually has different fields printed above and below the title, and usually modifies the ID of the title attribute.

What are the alternatives to adding more IF-statements into the page.tpl.php?

* Move the printing of the title (and content above and below the title) down into each node.tpl.php
* Modify the way that we are adding content above and below the title to use the existing title\_prefix and title\_suffix arrays
* other?

If we switch to render arrays method, I worry that coming up with the ordering and formatting of the content above and below the title will become more difficult for non-coders.

# Answer
It would be a much better practice to move most of this logic to the theme's preprocess\_page: http://api.drupal.org/api/drupal/includes--theme.inc/function/template\_preprocess\_page function so you can keep the separation of logic and presentation and make things easier on your designers.

You could add variables that could contain the different fields and classes that change based on the nodes content type in the preprocess\_page.
> 1 votes

# Answer
I would rather implement hook\_preprocess\_page() to add suggestions for the template files used instead of page.tpl.php.

```
function mymodule_preprocess_page(&$variables) {
  if (!empty($variables['node'])) {
    if (empty($variables['theme_hook_suggestions'])) {
      $variables['theme_hook_suggestions'] = array()
    }

    array_unshift($variables['theme_hook_suggestions'], 'page__' . str_replace(array("/", "\\", "\0", '-'), array('', '', '', '_'), $variables['node']->type));
  }
}

```

In this way, for the "Blog" content type, the template file used would be page--blog.tpl.php, if that file exists. In that way, there would not be the need to use IF-statements that change the output basing on the content type of the node being shown.

If the part that would change from a template file to the other is minimal, then (as suggested by acouch) I would implement template\_preprocess\_page() in the template.php file. The logic part should be kept in that file, rather than in the template files.
> 1 votes

# Answer
Personally, I don't like the multiple `page.tpl.php` solutions. I prefer to have one of these that gets used for everything, that also gets kept simple.

We typically employ a solution based on Panels. In your case, you can create a Node View template along with content type selection rules. The possibilities are pretty endless once you get to this point. You really need to try it out to see what is possible, but you can do what you are asking without much work.
> 0 votes

# Answer
Use Display suite and display suite extra. Goto admin/structure/ds/list/extras and enable "Page title options" in the "Other" tab. then you can disable default page title and place yours.
> 0 votes

---
Tags: theming
---


title: Custom CKEditor buttons or wrong way?

text:
# Question
Title: Custom CKEditor buttons or wrong way?
I need to setup a textarea field which will provide game cheats. So I have small gifs of each and every button of Xbox, PLaystation and so on. So when someone wants to publish a cheat for Xbox he needs to insert this small gifs into the text area field. How could I go about this? I thought it would be possible to setup a custom button for each gif in the ckeditor but I can not find out how to do it. Or is there a better way? Thanks

# Answer
One Option might be BUEditor if you're not tied to CKEditor. BUEditor buttons are easily and highly customizable.
> 0 votes

---
Tags: wysiwyg
---


title: Redirect to 404 or 403?

text:
# Question
Title: Redirect to 404 or 403?
When you set the 404/403 error pages to nodes with a path, how then can you have Drupal go to the 404 path or 403 path instead of outputting the message on the page?

For example, if I type in www.mydomain.com/skdjhfjsdhfjsh, it shows the custom 404 text from my node. But, is there a way to make Drupal send the user to www.mydomain.com/404, so I can use Contexts/Blocks with in the content area of this specific page?

# Answer
> 4 votes
I agree that redirecting a 404 page is a bad idea. One way customize error pages is the blocks404 module.

# Answer
> 3 votes
Another method for showing blocks is possible with Panels.

You can configure Drupal to display a node for a 403 and/or 404. You can then configure your node view panel template appropriately. What I don't recall us being able to use the error code in play to use as visibility rules for pane content.

# Answer
> 0 votes
The Custom Error module lets you set up custom 403 and 404 error pages. You can also do custom redirects for 404.

Disclosure: I am the co-maintainer for Custom Error.

---
Tags: 6, blocks
---


# Question
Title: Views: showing similar terms on term page by another term reference field
I've got 2 vocabularies, for example, artists and styles.

When viewing one of the Artists term i want to show another artists terms in a block, marked with the same term from styles vocabulary by reference field.

How to achieve it?

I tried to set the relation to Taxonomy Term: Styles (field\_styles) and various contextual filters but without success.

Any help is appreciated! Thanks in advance

# Answer
Assuming that you have a term reference field attached to the Artist vocabulary showing terms from the Styles vocabulary, and assuming that you wish to display a list of other Artists with the same Styles in a block ...

Create a block view showing taxonomy terms from the Artist vocabulary.

Set a Conceptual filter on `Taxonomy term: Tid` and provide a default value of *Term ID from URL*.

Add a relationship on `Taxonomy term:Styles (field_styles)` and check *Require this relationship*.

Add a second relationship to `Taxonomy term: Taxonomy term using Styles`. Configure it to use the relationship \*term from field\_styles\* and check it as required.

Go to your view fields and edit the `Taxonomy term: Name` field. Configure it to use the \*field\_styles\* relationship.

Go to *Advanced \> Other \> Query options* and select *Distinct*. This type of query can produce duplicates.

Place the block on your taxonomy pages and it will give you a list of Artists with the same Style(s) as the current Artist.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Writing image value to field_collection object
I'm creating a field collection item and saving it via entity\_create, and it all works great as long as I don't have an image tied to it. As soon as I do, I get an error, and it looks like this in the watchdog table:

```
    a:6:{s:5:"%type";s:12:"PDOException";s:8:"!message";s:516:"SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'fid' cannot be null: INSERT INTO {file_usage} (fid, module, type, id, count) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4); Array
(
    [:db_insert_placeholder_0] =>
    [:db_insert_placeholder_1] => file
    [:db_insert_placeholder_2] => field_collection_item
    [:db_insert_placeholder_3] => 50
    [:db_insert_placeholder_4] => 1
)
";s:9:"%function";s:16:"file_usage_add()";s:5:"%file";s:43:"C:\xampp\htdocs\mysite\includes\file.inc";s:5:"%line";i:663;s:14:"severity_level";i:3;}

```

My code looks like this:

```
$values = array(
    'field_name' => 'field_bp_images',
    'field_bp_image_title' => array( LANGUAGE_NONE => array(array('value' => $title)), ),
    'field_bp_image_file' => array( LANGUAGE_NONE => array(array('value' => $fid)), ),
    'field_bp_image_photographer_name' => array( LANGUAGE_NONE => array(array('value' => $photographer)), ),
    'field_bp_image_photo_flag' => array( LANGUAGE_NONE => array(array('value' => $is_photo)), ),
  );
}

$field_collection_item  = entity_create('field_collection_item', $values);
#Attach to the node
$field_collection_item->setHostEntity('node', $node);

// # Save field-collection item.
$field_collection_item->save();

```

My $fid is definitely populated, but I am still getting that error telling me my fid cannot be null. I'm guessing I need to provide more elements to the array, but not sure what keys to give, or how many. Any thoughts?

# Answer
> 1 votes
The column name for an image field is `fid` (not `value`), so you just need to change this bit of your `$values` array:

```
'field_bp_image_file' => array( LANGUAGE_NONE => array(array('fid' => $fid)), ),

```

---
Tags: 7, nodes, entities
---


title: New Content type formatting

text:
# Question
Title: New Content type formatting
I have a person who wants to have feature jobs on his site.

I've already got the descrption allow full html and got WYSIWYG going so he can add pictures and descriptions beside the pictures etc. but he wants it even simpler. He wants to have images and then a description that goes beside each image, then be able to add more images with descriptions as necessary. He wants them to look as follows:

\*image1 \*description1

\*image2 \*description2

With description one being a bunch of text most likely bullet points.

He's wanting the image/descriptions to be tied to one another. I'm pretty new so not sure how to do that. I am comfortable being able to use CSS to format the content if I can create a type that ties the image/description together like this.

# Answer
> 1 votes
If you dont mind installing a new module you should check the double fieldmodule.

> Double field is a small module written to provide extensions to Drupal's core Fields. By this module you can divide your fields into two seporate parts.

By using this module you can actually tie two fields together, and by clicking on add more you will have an image and its description tied together

---
Tags: nodes
---


title: Changing colors of drupal tables

text:
# Question
Title: Changing colors of drupal tables
I noticed that drupal always use grey as background and line color with tables.

I prefer to avoir modifying the code of my template. Is there any way to modify the ugly grey drupal tables ?

# Answer
> 2 votes
There are a couple of ways to do it. Here are two of them:

**Through your theme**

* write your own mainstyle.css file.
* place it in your active theme directory (directly or in a folder that you create there)
* go to that theme directory and open the file: \[themename\].info (e.g. bartik.info or myAwesomeTheme.info)
* add `stylesheets[all][] = mainstyle.css` after the existing stylesheets. (or `stylesheets[all][] = css/mainstyle.css` if your stylesheet is placed in a folder called 'css').
* flush your cache

This way drupal will include your stylesheet.

**A simpler way to do it** , with the help of a **module**, so that you don't touch any of your files, is

* download the module css injector
* enable the module
* go to configuration -\> development -\> css injector (admin/config/development/css-injector)
* create a new rule and give a name to the rule: e.g. table styling
* Finally in this rule write your CSS e.g. `td {background-color: red;}` etc

Tip: If you want to target your elements (e.g. tables) correctly, then you may need firebug, which is an extension for Firefox.

---
Tags: theming
---


title: Display node data in a blank page

text:
# Question
Title: Display node data in a blank page
Is it possible to display a set of nodes and display it on a blank page without the default template around it? This node data is meant for printing and I want it to display on the screen as it would appear on a printout.

# Answer
Sounds like you should look at the Printer, email and PDF versions module. It is designed to create alternate versions of your pages for print and documentation purposes. It allows you to specify different template files for the output, and you can customize it any way you wish.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Pass custom variable from template.php to *.tpl.php
template.php \> THEMENAME\_field\_CONTENT\_TYPE(&$variables) I am trying to check each field as it passes through...

```
if( $variables['element']['#field_name'] == 'field_I_am_looking_for' )
{
    if( $variables['element'][0]['#title'] == 'value_I_am_looking_for' )
    $variables['newVariableName'] = 'NewVariableValue';
}

```

or for Booleans...

```
$variables['newVariableName'] = True;

```

But in \*.tpl.php file, when I do this...

```
<?php if( isset( $content['isIcebreaker'] ) ): ?>
<pre>It's What You're Looking For!</pre>
<?php endif; ?>

```

...Nothing happens.

**Specific Details...** The custom content type is called 'Netrunner Card' and all cards have 0 or more 'subtypes'. The subtypes field is a taxonomy\_reference field. One of those subtypes is 'Icebreaker' and I'm trying to set $variables\['isIcebreaker'\] = True; whenever a card has the subtype of 'Icebreaker' and then test against that in node--netrunner-card--full.tpl.php.

Basically, in regular-speak, when a card has 'Icebreaker' as one of its subtypes, I want to add in some custom div's and other content in the node--netrunner-card--full.tpl.php for those cards. But the custom variable isn't making it over. I'm uncertain as to what I'm doing wrong.

**SIDE NOTE** If there is a better way to do what I am trying to do, I would appreciate those answers as well. However, regardless, I would still love to know the appropriate, Drupal Best Practices way of passing custom variables from template.php to a \*.tpl.php file.

**CODE VIEW** I have split off my template.php and included the new file as sort of an extended template.php. Here are posts of both my template.php and my tpl file.

template\_netrunner\_card.php

node--netrunner-card--full.tpl.php

**ANSWER:** I used the preprocess\_node function like so...

# Answer
> 4 votes
Every element key in the root of the `$variables` array will be available in the template file as an actual variable. The mechanics behind this is in `theme_render_template()`, which uses PHP's `extract()` function on the theme's variables.

So when you look at `$content` in the template file, that corresponds to `$variables['content']` in the preprocess function.

Similarly, if you add `$variables['newVariableName']` in the preprocess function, it will be available at `$newVariableName` in the template file.

If you want to add it to the content array, you need to do so explicitly in the preprocess function, e.g. `$variables['content']['newVariableName'] = ...`

Bear in mind that the content array is supposed to be a render array, so that's probably not the best place for it. The way you have it currently is fine, just use `if (isset($newVariableName)):` in place of your current `array_key_exists` condition.

Your current method is considered best practice for passing variables from preprocess functions (whether in template.php or a module file) to template files, you don't need to change anything in your thinking there.

---
Tags: nodes, theming
---


title: Passing a Solr search query to a view

text:
# Question
Title: Passing a Solr search query to a view
When a user enters a search query into an Apache Solr Search box, is it possible to pass that query onto a view - specifically to a Apache Solr Views view?

# Answer
While you could technically do this by implementing a `hook_form_alter`, to capture and overwrite the submit handler, if you're already using the Apache Solr Views module, you'd be better off creating an exposed filter, setting the exposed filters to display in a block, and then using that instead of the default search form block. You can do that without custom code.
> 2 votes

# Answer
You may try to use Search API with Solr support as it has better integration with Views and Drupal Recruter distribution is using exactly the same approach as you described. It has support for autocomplete, spell checker etc. as well.

So by creating exposed block in solr View, you're able to pass the query onto a view.
> 0 votes

---
Tags: views, 6, search
---


# Question
Title: Basic page still showing in view that filters out basic page content from view
I made a view that is only supposed to show Album, Mixtape, and Artist content types, but the basic page I made called "About Us" is showing up. I've tried deleting that content and re-making it and then doing the same with the view but it *still* shows up!

I'm attaching a couple of pictures to show you what I mean.

# Answer
I never found out why this was happening, but I found a workaround for it. Add another filter that says content cannot be of type: Basic Page. It's not pretty and I would prefer to not have to use that and fix the problem instead, but if you're pressed for time this will work.
> 0 votes

---
Tags: 7, nodes, views
---


title: Cancel vote when user is deleted

text:
# Question
Title: Cancel vote when user is deleted
Is there any way to cancel user votes (if there are any) when I completely delete a user account?

# Answer
Thanks kiamlaluno for the first guide. I'm really lost about writing even a mini-module.

Here's the code for what i was needing:

```
// Cancel / subtract user vote from 'poll_choice' table, when user account is cancelled.
// The code (db_update) which subtract users vote is a copy from poll.module
function MODULE_NAME_user_delete($account) {
    $uid = $account->uid;
    $votes_id = db_query("SELECT chid FROM {poll_vote} WHERE uid = :account_id", array(':account_id' => $uid))->fetchAll();
    foreach ($votes_id as $vote_id) {
        db_update('poll_choice')
        ->expression('chvotes', 'chvotes - 1')
        ->condition('chid', $vote_id->chid)
        ->execute();
    }
}

```

This is for MODULE\_NAME.install. We need it to make sure poll\_vote table is not update before this module function is executed.

```
function MODULE_NAME_install(){
  db_update('system')
    ->fields(array('weight' => -1))
    ->condition('name', 'MODULE_NAME', '=')
    ->execute();
}

```
> 0 votes

---
Tags: 7, rating
---


# Question
Title: Attach #ajax to submit button created in hook_form_alter with #markup
I created a custom submit button for the user-login form using #markup because I couldn't alter submit button html to resemble what I needed. The second custom submit button with the needed html is added with:

```
$form['submit2'] = array(
  '#markup' => '<p class="submit"><button type="submit" name="submit"><i class="icon-arrow-right icon-large"></i></button></p>');

```

I then added a "hideme" class to the orginal button with `$form['actions']['submit']` `['#attributes']` (deleting it stopped the other submit from working).

So far so good. But now I would like to validate the login form using AJAX. Only if I add the `#ajax` key to `$form['submit2']`, the callback is never called. This only seems to work with regular form items.

Is it possible to trigger an Ajax callback on a `#markup` element (in `hook_form_alter`)? I'm using Drupal 7.

# Answer
> 3 votes
You cannot, since the #ajax attribute is not used for the markup item. You can use an image\_button form element.

If the image\_button form element doesn't render as you want and it is not possible to alter it the way you want, you need to implement a new form element with `hook_element_info()`, using the definition of the image\_button form element as guide.

```
  $types['image_button'] = array(
    '#input' => TRUE,
    '#button_type' => 'submit',
    '#executes_submit_callback' => TRUE,
    '#limit_validation_errors' => FALSE,
    '#process' => array('ajax_process_form'),
    '#return_value' => TRUE,
    '#has_garbage_value' => TRUE,
    '#src' => NULL,
    '#theme_wrappers' => array('image_button'),
  );

```

The theme function that renders that form element is theme\_image\_button(). Changing the value of #theme\_wrappers, you can alter the way your form element is rendered.
Keep in mind that theme wrappers, as any other theme functions, need to be declared with `hook_theme()`.

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


# Question
Title: Change the number of returned results in a taxonomy item list?
Clicking a taxonomy term in a Node leads to a URL like `taxonomy/term/7` with a list of nodes with that taxonomy term. However, my Drupal installation is only showing 3 nodes/page in that list. Is there a way to customize the number of results the default taxonomy term search shows?

# Answer
The Views module has a default View for that page. If you enable it you can adjust it the way you want like you would normally do with Views.

Without Views: see comments.
> 2 votes

# Answer
The root cause of your problem is because of a setting found here: admin/config/system/site-information. This is the admin page for setting 'site' information, such as the site name, email address, etc.

One of these settings is called 'Number of posts on the front page'. Changing this value changes not just the front page but ALL taxonomy term display pages.

This is why you were only seeing 3 posts. Using the Views option to override the default Drupal taxonomy term pages is a good option, but it does have some side effects. For example, I'm not sure in D7, but in D6 I noticed that I lost the ability to filter terms on these pages when using the Views override. In D7, I lost the ability to display on the term page any fields including the term description associated with that taxonomy term.
> 0 votes

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


title: Drupal Form to Choose Embedded View

text:
# Question
Title: Drupal Form to Choose Embedded View
I'm trying to create a form that will allow a user to select a View from a list and then display that View on the same page. For instance:

```
$options = array();
$options['view_one'] = 'view_one';
$options['view_two'] = 'view_two';
$options['view_three'] = 'view_three';

$form['chooseview']=array(
    '#title'=>'Choose a View',
    '#description'=>'Which View do you want to display?',
    '#type'=>'select',
    '#name'=>'chooseview',
    '#required'=>TRUE,
    '#options' => $options,
    );

print views_embed_view($form_state['values']['chooseview'],'block_1');

```

My question is how do I accomplish this? Drupal is not printing the embedded View from `form_submit`. I don't need Ajax.

# Answer
**Method #1: (No subit button, requires JS, loads all views at once but shows conditionally)**

```
<?php
function MYMODULE_my_custom_form($form, &$form_state) {
  $options = array();
  $options['view_one'] = 'view_one';
  $options['view_two'] = 'view_two';
  $options['view_three'] = 'view_three';

  $form['chooseview']=array(
    '#title' => t('Choose a View'),
    '#description' => t('Which View do you want to display?'),
    '#type' => 'select',
    '#name' => 'chooseview',
    '#required' => TRUE,
    '#options' => $options,
  );
  foreach ($options as $view_name) {
    $form['display'][$view_name] = array(
      '#type' => 'markup', // Not necessary - just to be clear.
      '#markup' => views_embed_view($view_name, 'block_1'),
      '#states' => array(
        'visible' => array(
          ':input[name="chooseview"]' => array('value' => $view_name),
        ),
      ),
    );
  }
  return $form;
?>

```

(short, eh)

**Method #2: (Submit button, JS-independent, loads only view when necessary)** Note we pass `$form_state` to the form builder function by reference.

```
<?php
function MYMODULE_my_custom_form($form, &$form_state) {
  $options = array();
  $options['view_one'] = 'view_one';
  $options['view_two'] = 'view_two';
  $options['view_three'] = 'view_three';

  $form['chooseview']=array(
    '#title' => t('Choose a View'),
    '#description' => t('Which View do you want to display?'),
    '#type' => 'select',
    '#name' => 'chooseview',
    '#required' => TRUE,
    '#options' => $options,
  );
  $form['show_me'] = array(
    '#type' => 'submit',
    '#value' => t('Show me, please!'),
  );
  if (!empty($form_state['values']['chooseview'])) {
    $form['display'][$view_name] = array(
      '#type' => 'markup', // Not necessary - just to be clear.
      '#markup' => views_embed_view($form_state['values']['chooseview'], 'block_1'),
    );
  }
}

function MYMODULE_my_custom_form_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
}
?>

```
> 2 votes

---
Tags: views, forms
---


# Question
Title: View with pagination to have a single url per pagination page
I was doing a View for a last news from a site, but those news won't be accesible from outside, so only will be able to see the content by the view.

This view has a Pagination, and is printed as page. The problem is that I need to implement the facebook comment plugin, and I need that every page listed by the pagination, to have a unique url, I thought that it could be the same as the node url.

I tried by doing something with panes, but I could't override the View page. I'm Using Drupal 7 and the lasted version of views.

Thanks

# Answer
> 1 votes
The url's are unique. If the page view has a url of `/news`, then each page can be referenced individually as `/news?page=0` for the first page, `/news?page=1` for the second page and so on.

---
Tags: views, panels, paging
---


title: theming date format

text:
# Question
Title: theming date format
I am kind of lost here for hours, trying to make a translated date format work for my content type(Drupal 7.22). There are the 2 configuration issues:

**1. Format**

I want my formated date (say Apr 27) to be wrapped as following:

```
<span class=date>
  <span class=month> Apr </span>
  <span class=day> 27 </span>
</span>

```

Although I create the date format I can't find the way to template it the way I want. The month and date shown in these spans is set when I create a content type (through a custom field populated with the help of date module), and so I should do sth like `<?php echo render($content['field_date']); ?>`. Unfortunately this renders the date with a different markup than the one I want and so I believe I have to change sth in a preprocess function.

**2.Translation**

Say I have a date: Apr 27 and I want it to be in my language (greek) which would be Απρ 27.

I imported the greek http://localize.drupal.org/ successfully and inside this .po I can see

```
msgid "Apr"
msgstr "Απρ"

```

After a very helpful answer and a good comment below I now understand that translation isn't the way to go, since I only want to change the values of the months, and not translate the whole site. So what I look for is a function to do this.

P.S. I could make 2 seperate questions but I feel that they fit well under the title: configuring date formats. Also I have been trying for hours to find clear(to me at least) solutions and it proved harder than I thought. Can anyone help?

# Answer
> 0 votes
after some searching and experimenting, I came up with this solution for my first problem:

* I went to my theme in the template.php file
* I created a function:

```
<?php  //if the opening php tag exists already, then don't put it again here :)

function awesome_preprocess_node(&$variables) {

// checking if this field_mydate has a value
if (isset($variables['field_mydate']['und'][0]['value'])) {

  //if it has, let's cache this point down the path
  $date1 = $variables['field_mydate']['und'][0];

  // I create a instance of the DateObject here. I pass the $date1['value'] which
  // corresponds to the date-path produced by my custom field of type: date. I found
  // this path with the help of helper function: kpr($variables);

  $date_object = new DateObject($date1['value'], new DateTimeZone($date1['timezone_db']));
  $date_object->setTimezone(new DateTimeZone($date1['timezone']));

  // Using the following 2 calls of function date_format_date I manage to
  // seperate month and day.
  // These variables will be available for my .tpl.php files

  $variables['date_month'] = date_format_date($date_object,'custom','M');
  $variables['date_day'] = date_format_date($date_object,'custom','j');
  }
}

```
* In my node.tpl.php I use

```
<span class="date">
  <span class="day"> <?php print $date_day; ?> </span>
  <span class="month"> <?php print $date_month; ?> </span>
</span>

```

(**take into account** that 'awesome' is the machine name of my custom theme. If someone else uses it, they'll have to provide their own theme name. Also the 'field\_mydate' is the machine name of the date field I created. This will also need changing for another person's needs)

Although this does the trick, it seems (a bit) hacky and also it doesn't seem to load the \[attributes\] that used to be there before. Is there a better, clearer solution?

maybe overriding theme\_date\_display\_single ?! or

maybe using sth like `$event = node_load($nid);` inside the preprocess function to get the date object from there instead of creating a new one is preferable ?!

As for my second question, I see nothing else than translating the whole site

# Answer
> 1 votes
Translations in Drupal are global, and will effect the entire site when you enable a non-english default language. However, for translations to be acted upon, you need to wrap the term you want translated in the `function t()`.

So to have 'Apr' in the snipped below translated, you must do something like this:

```
<span class=date>
  <span class=month> <?php echo t('Apr'); ?> </span>
  <span class=day> 27 </span>
</span>

```

However, if you do not want to use Drupal' localization machinery, and just display the 4th month in greek, you may do something like this:

```
<span class=date>
  <span class=month> Απρ </span>
  <span class=day> 27 </span>
</span>

```

Also note Drupal let you define standard date format string if you navigate to `Home » Administration » Configuration » Regional and language » Date and time`. These get localized to your site's language when you set language, and have the added advantage of enforcing consistent date formats throughout the site.

---
Tags: 7, theming, i18n-l10n, datetime
---


# Question
Title: How to programmatically create a custom panel pane
I created a custom panel layout with Panels 3 (following this excellent link) and my layout is ready. Now I have my static markup ready for a node (I can use it on the article or a custom content type) and I want to find out how to create a custom panel pane programmatically. I don't won't to do it through the UI as I want to totally control the dynamic markup of a node. to make things specific (but keeping a certain level of generality), imagine

```
<div class="post">
  <h3 class="title">
    <span class="date">
      <span class="day"> !!php dynamic day of the date!! </span>
      <span class="month"> !!php dynamic month of the date!! </span>
    </span>
    <a href="#"> !!php dynamic title of the node!!  </a>
  </h3>
  <div class="content">
    <p> !!php dynamic content(body) of the node!! </p>
    <div class="read-more" >
      <a href="#"> !!php dynamic read more text!! </a>
    </div>
  </div> <!-- end: content -->
</div> <!-- end: post1 -->

```

How can I achieve to manage the above dynamic node (and let's suppose I want to achieve an exact, specific markup)?

# Answer
> 0 votes
Ok my question maybe was not the best but at least I hope the following will help new themers get on track.

* I created a custom content type called: seminar
* I created this node--seminar.tpl.php and placed it inside /sites/all/themes/awesome (the name of my theme)
* Inside this file I copy pasted the code found in /modules/system/node/node.tpl.php and I tweaked the code as follows.

```
<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> post clearfix"<?php print $attributes; ?>>
<?php print render($title_prefix); ?>
  <?php if (!$page): ?>
    <h3 class="title">
      <span class="date">
        <span class="day"> <?php print $date_day; ?> </span>
        <span class="month"> <?php print $date_month;?> </span>
      </span>
      <a href="<?php print $node_url; ?>"><?php print $title; ?> </a>
    </h3>
  <?php endif; ?>
  <?php print render($title_suffix); ?>
  <div class="content"<?php print $content_attributes; ?>>
    <?php
      hide($content['comments']);
      hide($content['links']);
      print render($content);
    ?>
    <div class="read-more">
      <?php print render($content['links']); ?>
    </div>
  </div> <!-- end: content -->
</div> <!-- end: post1 -->

```

Keep in mind that in order to achieve this

```
<span class="day"> <?php print $date_day; ?> </span>
<span class="month"> <?php print $date_month;?> </span>

```

so that $date\_day and $date\_month correspond to sth meaningful, I had to go through this. Othewise by default drupal outputs sth like `<span> Apr 30 </span>` and we can't target Apr and 30 seperately for CSS styling.

---
Tags: 7, theming, panels
---


title: Perform custom Ajax on Views

text:
# Question
Title: Perform custom Ajax on Views
My problem is quite complex here:

I have a view table with pager. However, I don't want the "items per page" to be a select list. I want it to look like links: 5 | 10 | 15 | all. My solution for now is edit the views template and add the links with `href=?items_per_page=5"`and it works fine. But I really don't like that I have to reload the page everytime the link is clicked.

That's why I was thinking if it's possible to bind an onclick event to these links that will change the value of the `<select>` and then send an ajax post submit to the views form. I tried to do some simple `$('form').submit()` but didn't get the expected result (can't remember what I got, but I think either no changes or got redirected to somewhere else). I could not figure out how to mimic an ajax sumbit that views perform on this form.

# Answer
> 1 votes
I believe you can utilize theme\_pager to accomplish your goals. Look for examples on how `theme_pager` is implemented. But `theme_pager` is definitely what you want.

# Answer
> 0 votes
Set Use Ajax Property to Yes :

---
Tags: 7, views, ajax
---


# Question
Title: new domain url for multi sites linked to sub domain drupal install
Because my drupal install is not in the root of document but in a subdomain, everything is a little more difficult for setting up multi-sites.

I found a way of adding multiple subdomains successfully to the subdomain containing drupal install but now that I am wanting to add a new domain url pointing to same IP obviously it keeps wanting to direct to document root and if I set it up in virtualhosts what happens is it makes it so you have to go to URL example.com/drupal/install.php which obviously I don't want because I want it to 'appear' as other multi-sites in the exact url not path to drupal folder.

Do I need to use a symlink for this to work? See I have two domains pointing to the ONE IP but as I have the drupal core in a SUBDOMAIN of the main IP then the second domain name doesn't want to follow the same rules as the other subdomains running off drupal core subdomain and direct from vhost to html/drupal and APPEAR in subdomain url. Rather the second name url is following the path LITERALLY and so I can never install anywhere but path to drupal folder.

So completely stuck on what to do from here. How can I make my second domain url POINT to the subdomain root drupal install and not the root of IP which is static?

# Answer
> 0 votes
So finally figured this all out.

If like me you are weird and want to use a Sub-domain for your main drupal install and then create multi-sites from that you can just add your **virtual hosts** to the **custom conf file** or wherever you keep that.

I found that to do away with **.htaccess** in favour of the **/etc/httpd/conf.d/custom.conf file as well as httpd.conf on linux vps.**

BUT if you want to add a new domain directing to same IP it will obviously keep searching for doc root,so even if you add the Drupal folder direction in virtual host it will just go there and not install at your actual URL.

So you need to create a **symlink** in this case and then add that directive to your virtual host. so it would be something like **/var/www/html/drupal/nameofmysite.com** which would be a **symlink** to the actual folder in **sites** folder of **subdomain.**

---
Tags: multi-sites
---


# Question
Title: I am learning Drupal 7 and want to know the way to learn modules
I am learning Drupal 7. I have read the docs about modules.

But still want to know the correct way to learn modules eg. how to use it, how to install extended modules etc.

# Answer
I think the most important is experience. Just installing and enabling some modules, trying them out gives you a feeling of how things work. There are many youtube videos that show you exactly what to do. But I can't stress this too much: experience is what we need. Don't make the same mistake as I did in the beginning when I studied more than I tried.

Don't be afraid to try things out, even if they don't seem to work in the beginning. Be persistent and follow the guidelines out there. Should you need specific advice on a module, feel free to ask here or in drupal.org where you should become a member. (if you are not already!)

I don't think there is an "officially correct way to learn". If there is, then I bet it is called **persistence**! So get involved and see you out in the field :D.
> 2 votes

---
Tags: 7
---


# Question
Title: Showing user image for custom comments created in a view
I am using a Drupal view for displaying comments.

I have the show: in the format field set to comments.
Therefore I won't be able to add extra fields in the field's section.

I have a custom URL where I show the contents of a node along with its comments and a comment box which I have custom coded.

How can I add a user image along with my comments?

# Answer
Try adding a "Relationship" to the comment author, and then add the user picture from the updated field list.
> -1 votes

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


# Question
Title: D6 - Rule to simply redirect path to login
Currently I'm trying to add create a rule that simply redirects anyone from /node/add to /user/login. It's intended to be part of a larger rule, but I'm having No luck with this

Steps of the rule are

1. Trigger - User is going to view a page
2. If path has alias(es) - /node/add
3. Do page redirect to - /user/login

Instead, it just goes to the /node/add page as usual. Why is this simple rule is not working?

Here is the rule exported.

```
array (
  'rules' =>
  array (
    'rules_30' =>
    array (
      '#type' => 'rule',
      '#set' => 'event_init',
      '#label' => 'Redirect to login if accessing /node/add',
      '#active' => 1,
      '#weight' => '0',
      '#categories' =>
      array (
      ),
      '#status' => 'custom',
      '#conditions' =>
      array (
        1 =>
        array (
          '#weight' => -1,
          0 =>
          array (
            '#weight' => 0,
            '#info' =>
            array (
              'label' => 'Path has alias(es)',
              'module' => 'Path',
              'eval input' =>
              array (
                0 => 'src',
              ),
            ),
            '#name' => 'rules_condition_url_has_alias',
            '#settings' =>
            array (
              'src' => 'node/add',
            ),
            '#type' => 'condition',
          ),
          '#type' => 'OR',
        ),
      ),
      '#actions' =>
      array (
        1 =>
        array (
          '#weight' => 0,
          '#info' =>
          array (
            'label' => 'Page redirect /user/login',
            'label callback' => false,
            'module' => 'System',
            'eval input' =>
            array (
              0 => 'path',
              1 => 'query',
              2 => 'fragment',
            ),
          ),
          '#name' => 'rules_action_drupal_goto',
          '#settings' =>
          array (
            'path' => '/user/login',
            'query' => '',
            'fragment' => '',
            'force' => 0,
            'immediate' => 0,
          ),
          '#type' => 'action',
        ),
      ),
      '#version' => 6003,
    ),
  ),
)

```

# Answer
> 3 votes
One easy option is to set the 403 Access Denied page at:

*admin/config/system/site-information*

to:

```
user

```

That way, if the user is not authenticated, they can login and view the node/add page.

I think the reason your Rule isn't working is because `/node/add` isn't an "alias" per se, but a system path.

Another option is something like

```
/**
 * Implements hook_init
 */
function MODULENAME_init(){
  if($_GET['q'] == 'node/add' && !user_is_logged_in()){
    drupal_goto('user/login');
  }
}

```

# Answer
> 1 votes
A more general solution is available by using the LoginToboggan module. WHen you configure LoginToboggan at `/admin/user/logintoboggan` simply Enable the option to *Present login form on access denied (403)*.

As far as the rule is concerned, `node/add` is a system path, not an alias, and it leads to the Add Content page. You might be able to get the rule to work if you use a data comparison on `node/add/*` but if the user does not have access I doubt the rule will trigger.

---
Tags: path-aliases, rules
---


# Question
Title: How to render-print content type fields in an article?
I am building a Drupal website and came across with an issue.

I have created a content type called "comments" with 4 fields :

```
    -comment1 with machine name: **field_comment_1**

    - comment2 with machine name: **field_comment_2**

    - image1 with machine name: **field_image_1**

    - image2 with machine name: **field_image_2**

```

I have created an article and put the code below:

```
<div class="green-box-comment">
    <?php print render($content['field_comment_1']);?>
    <?php print render($content['field_comment_2']);?></div>
<div class="green-box-images">
    <?php print render($content['field_image_1']);?>
    <?php print render($content['field_image_2']);?></div>

```

Unfortunately nothing shows... Any idea what I am doing wrong?

Many thanks for your help!

# Answer
> 1 votes
ok, here is what I would do:

* Create a subtheme as per this video, let's call it mytheme
* Go to sites/all/themes/mytheme and create a file there called

```
node--comments.tpl.php

```
* Go to modules/node/node.tpl.php, open it and copy eveything inside
* Paste that inside the node--comments.tpl.php that was created in second bullet
* Inside the `node--comments.tpl.php`, **substitute `print render($content);`** with your code

```
<div class="green-box-comment">
  <?php print render($content['field_comment_1']);?>
  <?php print render($content['field_comment_2']);?>
</div>
<div class="green-box-images">
  <?php print render($content['field_image_1']);?>
  <?php print render($content['field_image_2']);?>
</div>

```

The reason we subsitute `print render($content);` with your code is that your content-type has 4 fields and through your code you render all 4 of them one by one, so nothing is left for `print render($content);` to do.
* Go to appearance, enable and set default mytheme
* Lastly, **clear cache** to be sure all the changes are picked up (configuration -\> development -\> performance)

In this way, I would achieve to have my styling changes in a subtheme. So anytime I want to change something I can do it there and it will override what would be shown by the base theme, without changing core. This is following Drupal's best practices and keep my styling seperate from core, which makes the site more robust and easily maintained (& upgraded)

note: by creating the file `node--comments.tpl.php` and following these directions, you will just change the output of the custom content type called: comments, while leaving the rest of the nodes to be handled by the node.tpl.php, without interference.

P.S. you can do without step 1 and go straight to themes/bartik/templates (if bartik is your default theme), create there the node--comments.tpl.php and continue from there, and although this is faster, I think it is bad practice for the reasons explained above :)

---
Tags: theming, entities, nodes
---


# Question
Title: Add large number of images to drupal site
I am trying to create an image gallery in my drupal site from the backend. Also I want to add images to existing content types since there are large number of nodes and attaching image to each of them from the front end is not feasible. What I have understood follows here:

The database contains the table named files that consists of path and type of each file uploaded from fronted. The fid corresponding to each of these paths is used in corresponding content type table to produce images at required node.

Plase tell me if this approach is wrong:

I wanted to upload images in bulk and add image names and there path in the files table as well as corresponding fid's in the content type tables.

But this does not work. Can someone help me with this. Have I analysed it wrongly?

# Answer
> 0 votes
I spent some time in understanding how Drupal 6 retrieves images to show on front-end. Since drupal is heavily database intensive, all the files and images are retrieved from the database itself.

If you are using CCK in your site, you must have created image fields for some content types. Now if you open the database and check the table for respective content type, you will find that there are three columns created for each image cck field namely field\_name\_fid,field\_name\_list,field\_name\_data .

The field "field\_name\_fid" is the key field that maps images to this content type. The ***fid*** is the key that is matched to the fid of the table "***files***". If you open this table, you will find that the primary key of this table i.e fid is used to map images throughout Drupal content.

**Here comes the solution**

1. Upload an image from the frontend to test where is your file saved physically in you drupal directory. For every image uploaded to any node from front-end there will be an entry in the files table with its filename, filepath, filemime, file size, status and timestamp.
2. The fields that you should take care about in the **files** table are filename, uid, filepath, filemime, and status.
3. All you have to do is, Place all your files in that physical location.
4. Run SQL queries to first fill all the fields stated in #2. and match the fid of **files** table to the **field\_name\_fid** of respective content type.

And you are done.

---
Tags: media
---


title: Use node_load via Ajax

text:
# Question
Title: Use node_load via Ajax
I'm using horizontal parallax jQuery plugin and have a page--front.tpl.php file. That's my structure:

MENU:

```
<li><a id="mymenu" href="#/menucontent">news</a></li>

```

When I click this menu item, go to DIV:

```
<div id='menucontent' class="fancyscroll-section" style="left:1600px">

    <?php
    $view_mode = 'full'; // Or 'full' for example
    $node = node_load(52);
    $view = node_view($node, $view_mode);
    print render($view);
    ?>

    </div>

```

But I have a big problem. When i click my site adress, loading all content and items in one time. So, my site is slowly. I thinking use node\_load function via Ajax. Searched site and drupal.org but not found a good info.

Is it possible? What can I do for my site speed? Ajax is a good solution?

# Answer
Ajax could actually complicate your situation further, since you'd be asking your site to bootstrap once again asynchronously in order to serve the node. Not to say it isn't an option, you can write your own method to retrieve only the information you need via ajax.

I would personally look into caching methods. If your site gets anonymous traffic, try boost. Easily the best improvement for Drupal performance (in my opinion) is APC cache. Hopefully you have root access and can install the APC extension for PHP and then the APC module, the site starts flying after that, for both auth and anon traffic. I'm afraid you might already know this so I'll stop there.

If you still wanna do AJAX stuff, you could install views datasource to output JSON, and add a jquery call the page with $.get and push the content into the DOM. Using views gives you some native caching options as well.

Hope it helps.
> 1 votes

# Answer
Yes, you can use ajax for this.

1 Create menu item via hook\_menu() with callback

```

function mysite_menu() {
      $items['ajax/load_node/%'] = array(
        'page callback' => 'mysite_load_node',
        'page arguments' => array(2),
      );
      return $items
    }

function mysite_load_node($nid) {
     $view_mode = 'full';
     $node = node_load($nid);
     $view = node_view($node, $view_mode);
     return drupal_json_encode(render($view));

   }

```
2 Write ajax function for loading content and add to your links nid attribute, for example

.... id="mymenu" nid="52" href="#/menucontent">

```
$('a').live('click', function(){
    var nid = $(this).attr('nid');
    $.ajax({
      url: "/ajax/load_node/" + nid,
    }).done(function(result) {
       // you can load result for needed dom element
    });
  });

```

> 1 votes

---
Tags: ajax, javascript, nodes
---


# Question
Title: Commerce Email: HTML Mail not reading template
I am attempting to make a custom template for my Commerce Email emails. CE uses Variable Email and HTMLMail. I have put the template (named htmlmail--variable\_email--custom\_email\_order.tpl.php) into the root of my theme folder. Nothing. The test htmlmail template is in the same place and works fine. I have cleared caches on the performance and in PHPMyAdmin, and run cron. Still doesn't work. Is this peculiar to Variable Email or HTMLMail?

# Answer
It's not enough to leave the theme selection entry as Current theme; you must explicitly state that you want to use the theme you are already using. Now everything works.
> 1 votes

---
Tags: commerce, emails
---


# Question
Title: Change homepage template, depending on admin setting
**Problem:** I have a content type called "Homepage" of which there is only one node instance (which is pointed to as the front page), that contains a bunch of editable fields so the client can update certain front page content in several places.

They want to be able to, now and then, change the front page to a slightly different layout to focus on a call to action. This will probably be an

* extra content-editable text area
* a driver image

That will take the place of an image on the front page. This image is output in `node--homepage.tpl.php` as you might expect.

**My proposed solution**:

* Create two new fields in the Homepage content: driver text, driver image.
* Create an admin page, or add to an existing admin form a button: "Driver mode". When this button is enabled,
* Make the Homepage content type reference a new template that hides the old image and outputs the new fields.

Is it possible to do this - use a new template depending on some set variable, or should I have some logic in my `node--homepage.tpl.php` that conditionally outputs one bunch of HTML or another depending on the variable set in the admin? E.g. (rough code, ignore syntax/logic errors)

```
<?php

if (variable_get('driver_mode'))
{
   print render($content['field_driver_image']);
   print render($content['field_driver_text']);
}
else
{
   print render($content['field_homepage_image']);
}

?>

```

So basically, I'm asking what you think is a simple, clean and/or Drupal way to solve my problem above? Note that the code above is just a general example to support what I'm trying to achieve, no need to analyse it's correctness, I'm more interested in what your approach would be - should I perhaps be preprocessing the output in template.php depending on whether driver mode is on or off, so that I only output one variable, which produces the desired output depending on state?

# Answer
> 1 votes
My version is:

1. Create needed fields (driver image and driver text) for node type
2. Add checkbox field to the frontpage node type ('Driver mode')
3. Use template\_preprocess\_node(&$variables) or hook\_node\_view() to make some changes if checkbox field is checked

---
Tags: 7, theming
---


# Question
Title: is there any module which gives domain list as content type field
we are using domain access. we need to add domain list as a field to one content type so based on that result we need to display the result on main domain itself. is there any field module for it? Thanks.

# Answer
That feature has been developed for the pending Drupal 8 release https://drupal.org/node/1917780 but is yet to be available for D7 (afaik)
> 0 votes

---
Tags: domain-access
---


title: How to add fields with number values

text:
# Question
Title: How to add fields with number values
I need to add some fields than can take numeric values and enable Drupal to calculate it. I chose an integer field, tried to do some simple math, but Drupal 7 treats values of integer field as text. Moreover, integer field type widget can be only set up as text. Can anybody help me, and tell me how to add field with number values?

# Answer
The reason why the widget for an Integer field is a text field is that the form element used from a browser is a text field. This means the browser is always returning text for an integer field.

This should not be a problem, since:

* When you add an Integer field to an entity, the field value is validated to be an integer; an input containing characters that are not digits (e.g. *2A*, *Q3*, *2.0*) is not accepted, and the users get an error message requiring them to enter only numbers for that field.
* PHP generally accepts a string containing only digits instead of an integer without to report errors. If you execute the following code, you would get 15 as result. (It requires the Devel module.)

```
$a = "3";
$b = "6";
$c = "2";

dpm($a + $b * $c);

```

You would get the same result if `$a` is set to `"3A"`.
> 1 votes

# Answer
I maintain a small module called SpinInt on drupal.org which allows you to specify a scrolling integer widget in your field setup. Not sure if that's any interest but it's a bit friendlier than a text field I guess.
> 1 votes

# Answer
By using Computed Field module you can achieve your goal, You need to have a good working knowledge of PHP and the Drupal API to use this module.
> 0 votes

---
Tags: entities
---


# Question
Title: What's the best way to insert a user reference field value into the database?
I use the references module. I have a custom form, into which I capture names into a user reference field via the autocomplete widget. So, on the form, if a user types Joe, the following appears in the input box:

```
Joe [uid: 5]

```

Now, I do not want to insert this into my database as it is because my 'Name' field is expecting just the uid. So I need to pass '5' to the database, not the string `Joe [uid: 5]`.

To accomplish this, before I write my record to the database I pass the string `Joe [uid: 5]` through this code:

```
// * Search for match (integer) to regular expression and put in $integer.
preg_match_all('!\d+!', $form_state['values']['name'], $integer);

// * Return string representation of array elements.
$name_uid = implode(' ', $integer[0]);

```

`$name_uid` now contains '5' and is ready to be inserted. Is there an existing function that already does this? or does anyone have a better way?

The downside of my method is that you cannot have numbers in names, like 'Joe 2'. I've looked in user\_reference.module, but it's not obvious, to me, how they do it.

Thanks

# Answer
> 0 votes
I couldn't make `user_reference_autocomplete_validate()` work for me so I turned my own code into a function, which now solves my numbers in names problem. I can't see why it would ever fail, but if anyone has a better solution, please let me know.

```
/**
 * Search for regular expression matches and return the last match.
 */

function extract_id($subject) {
    preg_match_all('!\d+!', $subject, $matches);
    return end($matches[0]);
}

```

---
Tags: nodes, users
---