# Question
Title: How do I add JavaScript specific for a view?
I have a view in my site that has a specific class name. I want to know, inside the template.php file of a theme, how I can know if a view with specific class name is available in the requested page.

This is very important for me because I need to include specific JavaScript and CSS, when a view with a specific class name (such as image-gallery) is used in a page.

# Answer
You could use the `template_preprocess_views_view()` hook to do this:

```
function THEME_preprocess_views_view(&$vars) {
  $view = &$vars['view'];
  // Make sure it's the correct view
  if ($view->name === 'your-view-name') {
    // add needed javascript
    drupal_add_js(drupal_get_path('theme', 'your-theme') . '/your-js.js');
    // add needed stylesheet
    drupal_add_css(drupal_get_path('theme', 'your-theme') . '/your-css.css');
  }
}

```

Note that you could also check the specific display of the view using:

```
if ($view->name == 'your-view-name' && $view->current_display === 'your-display-id') {
  // include javascript & css here
}

```

You should be able to check for a custom css class like this:

```
if ($view->name == 'your-view-name' && $view->display[$view->current_display]->display_options['css_class'] === 'your-css-class') {
   // include javascript & css here
}

```
> 44 votes

# Answer
You can use views\_get\_page\_view function to find out which view is being served on the page. It return views object. Note that in the code snippet below you should compare with views machine readable name, but of course you can write your own comparaison basing on the view object returned by views\_get\_page\_view

```
function YOURTHEMENAME_preprocess_page(&$variables) {
    $view = views_get_page_view();
    if($view->name == 'YOURVIEW') {
    //Do what ever you want
    }

```
> 9 votes

# Answer
Just in case this is useful to anyone else stumbling across this question, searching like I did for *attach JavaScript to a Drupal View*. In terms of D7 & Views 3.7, the following worked best for me:

```
function HOOK_views_pre_render ( &$view ) {
  /// check to make sure the view has a classname
  if ( $view->display_handler && !empty($view->display_handler->options['css_class']) ) {
    $cln = $view->display_handler->options['css_class'];
    $cls = 'CLASS GOES HERE';
    /// test that the classname contains our class
    if ( preg_match('/(^|\s+)' . preg_quote($cls) . '(\s+|$)/i', $cln) ) {
      /// build the path to the js, which is local to my module, js/view.js
      $sep = DIRECTORY_SEPARATOR;
      $dir = rtrim(drupal_get_path('module', 'HOOK'), $sep);
      $pth = "{$dir}{$sep}js{$sep}view.js";
      drupal_add_js($pth);
    }
  }
}

```

This was beneficial as I wanted to keep the code within my module, rather than the theme — because the enhancements brought by the JavaScript had nothing to do with visual appearance.

> **NOTE:** Obviously `HOOK` should be replaced with your module name, in both locations, and `CLASS GOES HERE` should also be replaced with the class you are searching for.
> 6 votes

# Answer
If you're on drupal 6 or 7 you can also include javascript assets with the module context add assets. Which does require context but you'll rest assure that it'll always be included when the view is being rendered.

https://drupal.org/project/context\_addassets

From the module's project page:

> Have you ever wanted to include javascript or css when a particular view or block is being rendered? Or have you ever wanted to include javascript or css for just the front page without having to write code?
>
> Context add assets allows you to do this. It has an easy to use UI to allow you to do this all without writing any code. Because it uses ctools all of this is also exportable.
> 4 votes

# Answer
Write JavaScript code that searches for specific class in the view, using jQuery's hasClass(), and include your JavaScript file when the condition is satisfied.

Another way is to put a template for your view, and add JavaScript code through that template using drupal\_add\_js().
> 2 votes

---
Tags: views, theming, javascript
---


# Question
Title: Using pathauto to create multiple aliases, one for each term?
If I have a taxonomy `tags` so that I can tag a node with `foo` and `bar` and `baz`, is there any way to make the pathauto module create three aliases?

If it would normally create `content/my-new-node`, is it possible to make pathauto create `foo/my-new-node` and `bar/my-new-node` and `baz/my-new-node`?

# Answer
Under Configuration, if you go to Modules and click on Configure for Pathauto, you should see the option for the URL patterns. There is a section for taxonomy as well. *However*, I realize you want to change a node's URL based on the taxonomy term you've associated with it. At this point, it's just a matter of figuring out what token is going to do that for you.I have not used it, but I would imagine the Field Tokens module may help you do what you want to do. If you search for "pathauto" on that page, some people discuss using it with Pathauto down in the comments.
> -1 votes

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


title: Coloring question

text:
# Question
Title: Coloring question
Is there a way that every time the word green appears, anywhere on my website, that the font shade is the color green? Is there a module that would help, or something in css or scss?

# Answer
> 1 votes
**Answer updated based on comment**

A simple jQuery solution might be ideal here.

In your theme.info add a reference to jquery.highlight.js, custom.js and custom.css files:

```
name = My theme
description = Theme developed by me.
core = 7.x
engine = phptemplate
scripts[] = jquery.highlight.js
scripts[] = custom.js
stylesheets[all][] = custom.css

```

Or you can use drupal\_add\_js() and module or theme, see https://www.drupal.org/node/304255

Rather than using "Highlight Keywords on a Page with Jquery" found at http://hawkee.com/snippet/9854/, let's use a fork of the JQuery Highlight Plugin by Penagwin found at http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html to more efficiently handle multiple colors.

Save this file to your theme as jquery.highlight.js from the source at https://dl.dropboxusercontent.com/u/18269294/penagwinhighlight.js

jquery.highlight.js contains:

```
/*

highlight v4m1

Highlights arbitrary terms.

<http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>

MIT license.

Modified by Penagwin to allow custom css classes.
<dev.penagw.in>

Johann Burkard
<http://johannburkard.de>
<mailto:jb@eaio.com>

*/

jQuery.fn.highlight = function(pat, classn) {
 function innerHighlight(node, pat) {
  var skip = 0;
  if (node.nodeType == 3) {
   var pos = node.data.toUpperCase().indexOf(pat);
   if (pos >= 0) {
    var spannode = document.createElement('span');
    spannode.className = String(classn);
    var middlebit = node.splitText(pos);
    var endbit = middlebit.splitText(pat.length);
    var middleclone = middlebit.cloneNode(true);
    spannode.appendChild(middleclone);
    middlebit.parentNode.replaceChild(spannode, middlebit);
    skip = 1;
   }
  }
  else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
   for (var i = 0; i < node.childNodes.length; ++i) {
    i += innerHighlight(node.childNodes[i], pat);
   }
  }
  return skip;
 }
 return this.length && pat && pat.length ? this.each(function() {
  innerHighlight(this, pat.toUpperCase());
 }) : this;
};

jQuery.fn.removeHighlight = function() {
 return this.find("span.highlight").each(function() {
  this.parentNode.firstChild.nodeName;
  with (this.parentNode) {
   replaceChild(this.firstChild, this);
   normalize();
  }
 }).end();
};

```

Then in custom.js add the following:

```
(function ($) {
  $(document).ready(function() {
    $(".field-name-body").highlight("green", "green");
    $(".field-name-body").highlight("red", "red");
    $(".field-name-body").highlight("blue", "blue");
  });
})(jQuery);

```

And custom.css:

```
.red{
  color: #ED3027;
}
.green {
  color: #497206;
}
.blue{
  color: #0864A6;
}

```

Clear cache and and the color names found inside a `.field-name-body` class will be colored. Change the element name to what best matches your theme structure. For example `article` or `#content` may be more appropriate. Obviously for your use case the jquery.highlight.js function could be optimized to use the pattern as the highlight classname, but this gives you more freedom in naming classes.

---
Tags: theming
---


# Question
Title: An exposed filter works only with certain taxonomy terms (weird to me)
I have a "commercial property" and "residencial property" node types. One for offices, cellars, etc and the other to houses, apartments, etc

They share some fields (price, address, etc) and also a field that I called "Kind of property" that is a taxonomy dictionary:

Kind of property:

* Office
* Cellar
* House
* Apartment
* Estate

I have a View that works like a "Property search" and I have exposed the field "Kind of property". I created a menu for each one, so the visitor can go to "Sales - Apartments" and the View will show all the available apartments that are on sale.

This is the example URL for Apartments on sale: http://www.asir.com.co/inmuebles/buscar?asignacion\[\]=Venta&field\_tipo\_de\_inmueble\_tid=18

See that "asignacion" is a field that I use to mark the property if it is for sale or for rent (in this case Venta means Sale)

And also see that "field\_tipo\_de\_inmueble\_tid" point to the taxonomy term that is on the field "Kind of property".

The issue that I'm having is that *field\_tipo\_de\_inmueble\_tid=18* works good, and also *field\_tipo\_de\_inmueble\_tid=19* workds good, but if *field\_tipo\_de\_inmueble\_tid=**20*** then it dosen't work and the view result is empty. (18 = Apartments, 19 = Houses, 20 = Estates, wich are the taxonomy terms).

I checked the nodes and there are nodes created that are using the termin id 20, but the View is not showing them so don't know how to troubleshoot this, any idea?

Thanks a lot for your time!

# Answer
> 0 votes
Found my mistake. I rechecked every value on the View filters, and the city filter had a value on it, so I left empty the city and now the property is showing ok, because that property is not on the city that was the default.

---
Tags: 7, views
---


# Question
Title: Grouping by day + events spanning several days
This is a question that has already been asked on Drupal.org. It's exactly what I need on my view, but it hasn't been answered yet.

```
Posted by Amanda-333 on April 12, 2011 at 5:58am
I wanted to ask how I can group events by day in a view.

It works fine if I only have events that have their start- and endtime on the same day.
2011-04-12
2011-04-12 10:00 – 2011-04-12 18:00 Event 1
2011-04-12 12:00 – 2011-04-12 14:00 Event 2

2011-04-13
2011-04-13 10:00 – 2011-04-13 18:00 Event 5
2011-04-13 12:00 – 2011-04-13 14:00 Event 8

The problem: I have some events that take several days or weeks.
Example: I create one event with the start date of 2011-04-12 10:00 and the end date of 2011-04-15 19:00 for example.

This event now shows up in the grouped view as
2011-04-12 - 2011-04-18
2011-04-12 10:00 - 2011-04-15 19:00 Event 11

I would like to have that event sorted into the regular day groups (split that event into day parts):
2011-04-12
2011-04-12 10:00 - 2011-04-15 19:00 Event 11

2011-04-13
2011-04-12 10:00 - 2011-04-15 19:00 Event 11

2011-04-14
2011-04-12 10:00 - 2011-04-15 19:00 Event 11

2011-04-15
2011-04-12 10:00 - 2011-04-15 19:05 Event 11

Similar to how it is done in the calendar – day view. But with a simple text list format.
I can not find a way to do this? Perhaps someone can give me a little help?

```

https://www.drupal.org/node/1124616

# Answer
Make 2 or 3 computed view fields (which will require some php):

* 1field for `day of event`
* 1 or 2 fields for start time and end time dates.

You can group the View output by the first field. Then create the event time range by inlining the 2 other fields.

With these 3 pieces of info the calendar should be able to see the start and end datetimes and make a line representing the event duration.
> 1 votes

---
Tags: views, datetime
---


# Question
Title: Drupal 7 : Tons of HTTP requests from Media Vimeo module
I am using the Media module

And two of its sub-modules - YouTube and Vimeo

As a result - front end page for some reason sends 4 HTTP requests for each Vimeo video on the page and they totally slow down page loading - http://snag.gy/dKEjv.jpg

**Question :**

If there is somebody familiar with these modules or with Vimeo API - could you explain what are these requests for?

# Answer
> 1 votes
Those HTTP requests look like (slightly broken) video analytics tracking requests via the service conviva.

It might be possible to opt-out of conviva with Vimeo

See also Make Vimeo Faster - Opt Out of Conviva

---
Tags: media
---


# Question
Title: How to approach scheduled rules to real deathline?
Hello Im facing a problem, I made an app that makes use of a lot of scheduled rules, I could notice that those rules are not executed exactly in the time that is indicated in the schedule, those rules executes with the CRON, so for example if the rule reaches the deathline it only is executed after run of CRON.

So I had to set the CRON to run more frequently but is there another way of make the rule executes exactly in the set deathline?

my app needs to be very accurate in the execution of those scheduled rules so that's why...

Thank you

# Answer
Rule scheduler works with CRON only so you have to run CRON frequently, but you can use Elysia Cron module, where you can specify different schedule for different `hook_cron()`, so if you want your rules scheduler to run frequently then configure `rules_scheduler_cron()` to run say every five minutes and configure other `hook_cron()` to run every two hours.

In that way you run reduce the load.
> 2 votes

---
Tags: 7, cron, rules
---


# Question
Title: how to prevent applying discount for a product
I'm trying to change the product price based on the purchase type. I have added two radio buttons in `add to cart` form, one is retail and another one is wholesale. The default value is retail, so the default action will be executed. When user selects `wholesale` option I need to set the price of`whole sale price` and want to disable the discount for this product.

Here is my code :

```
function mycart_commerce_product_calculate_sell_price_line_item_alter($line_item){
    $pid = menu_get_object();
    $pid=$pid -> field_product['und'][0]['product_id'];
    $product=commerce_product_load($pid);
    $wh_price=$product->field_wholesale_price['und'][0]['amount'];
    $wh_currency=$product->field_wholesale_price['und'][0]['currency_code'];
    $line_item->commerce_unit_price['und']['0']['amount']=$wh_price;
    $line_item->commerce_unit_price['und']['0']['currency_code']=$wh_currency;
}

```

from above code I'm able set the product price to `whole sale price`. But I don't know how to disable `discount` for this particular product.

Can anyone please help me to solve this.

# Answer
You can just alter the rule that commerce discounts provides and add a condition by the products you want to exclude. Bear in mind that when you alter the rule that commerce discounts provides, you can't modify the discount from the discount interface anymore.

If you've created a discount through the Commerce Discount interface, you can exclude products using the Negate checkbox.
> 0 votes

# Answer
I haven't used discount rules before. But I did use tax rules. I altered it by this hook also . I think you can do same thing in this hook.

First, use kpr($line\_item-\>commerce\_unit\_price) to check all the values. Then change them in this hook.

For my case, the price is:

```
$line_item->commerce_unit_price['und']['0']['amount']=$myPrice;
$line_item->commerce_unit_price['und']['0']['data']['components']['0']['price']['amount']=$myPrice;

```

And the tax is:

```
$line_item->commerce_unit_price['und']['0']['data']['components']['1']['price']['amount']=$myTax;

```

Hope this will be helpful.
> 0 votes

---
Tags: hooks, commerce
---


title: Panels Page Title CSS?

text:
# Question
Title: Panels Page Title CSS?
I have created a Panels Page but can't find out how and where to put the class for the title? Right now it uses the core Page Title CSS but I wan't every Panels Page Title to be unique.

Edit: I've noticed that this is the way for all my panels. I can't seem to be able to set a CSS Class to Pane Titles at all.

# Answer
> 1 votes
If you have set panel title like this

you can use the class "pane-title" to write the css.

# Answer
> 0 votes
In Drupal 7 Panels, you can add unique class to your pages. Using page class you can add CSS to your Page Title

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


# Question
Title: How to get changes in database done by someone else?
We are working on features in team. My team-mate have done some changes & synced the cloud database.

I also have some database changes locally, now I want those changes in database which he synced.

I can't use `drush sql-sync` becauses it asks to drop all the tables. So my local changes will gone.

what should I do?

# Answer
Unlike code Database changes cannot be synced easily.

Try using Features Module This module exports your database settings to code so that they can be added to Version Control took like Git.

Tip : Create one feature for every independent functionality, so that it will be easy to manage. There are other supporting module for Features, which can reduce your efforts.
> 1 votes

---
Tags: drush
---


title: How can I add image map on drupal?

text:
# Question
Title: How can I add image map on drupal?
I am working on a website that is about history and there are some map for this website.

I am using map tag of HTML to select a part of image(map), how can I merge that `<map>` to `<img>` that uploaded by drupe

or how can I put the image address and merge map to it:

```
<img src="file:///C|/xampp/htdocs/geo/sites/default/files/field/image/aa.jpg"  alt="" width="800" height="531" usemap="#Map"/>
<map name="Map">
  <area shape="poly" coords="396,270,516,286,549,324,502,353,447,342,406,343,384,366,400,396,386,414,353,344,346,293,345,263,389,235,428,223,470,234,487,252,596,243" href="#">
</map>

```

**Where is the path (address) of files on drupal that I can link to it insted of the path that I give on top source** `<img src=" I Mean here"/>`

# Answer
Try the jQuery Map Hilight module

> It enables the simple addition of mouseover highlighting of hotspots to HTML image maps without requiring the editing of theme files or knowledge of javascript/jquery.

**Features**

1. provides simple interactive graphics via HTML image maps (no flash required).
2. easy to use: either select the 'highlight all image maps' default setting or simply add class="jq\_maphilight" to the tag of any specific image map you wish to highlight.
3. no jquery or javascript knowledge required: plugin configuration is handled via an admin/settings screen rather than having to enter jquery code.
4. fully configurable: options for fill, fill color, fill opacity, outline, outline color, outline opacity, outline thickness, as well as a fade effect.
5. per image map settings: add image map specific options with an additional class.
> 2 votes

---
Tags: media, files, uri
---


# Question
Title: Is there a way to programatically create a commerce coupon fixed amount?
I'm using the Commerce Coupon Fixed Amount module to create fixed coupons, which works fine in the interface. But I'm wondering if there is a way to programmatically create them.
I'm able to create normal commerce coupons with this helpful snippet of code.

# Answer
Using this tutorial and the above modules/code It makes making a commerce coupon fixed amount (or in this case, a gift card) easier to see. The only difference between making a regular coupon and one with a fixed amount is that the product (gift card product) price needs to be loaded before hand and the amount of the coupon being created upon gift card purchase needs to load the price from that gift card:

```
$coupon->commerce_coupon_fixed_amount[LANGUAGE_NONE][0] = array(
'amount'  => $product->commerce_price[LANGUAGE_NONE][0]['amount'],
'currency_code' => $product->commerce_price[LANGUAGE_NONE][0]['currency_code'],
);

```
> 3 votes

# Answer
This isn't a way to do it programmatically, but you can use the Commerce Coupon Batch module, which quickly allows you to generate a large number of coupons through the UI, which you can then export to Excel, etc.

It integrates with the Coupon Fixed Amount module.
> 1 votes

# Answer
The code i used was :

```
      $coupon = commerce_coupon_create($type);
      $limit_length = variable_get('commerce_coupon_default_code_size', 8);
      $coupon->commerce_coupon_code[LANGUAGE_NONE][0]['value'] = commerce_coupon_generate_coupon_code($limit_length);
      $coupon->commerce_coupon_number_of_uses[LANGUAGE_NONE][0]['value'] = 1;
      $coupon->commerce_coupon_fixed_amount[LANGUAGE_NONE][]  = array(
        'amount' => 2000,
        'currency_code' => 'EUR',
      );
      commerce_coupon_save($coupon);

```
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: Make Conditional Field work with Price widget
I would like to know if there's a way to make the Conditional field module here work with the Price widget. For example, I want to allow the user to input a price when he checks something with a checkbox.

# Answer
Conditional field module is base on the States API. You can probably do this via a hook\_form\_alter in a module.

The example below will make the field 'my\_field\_price' visible and required when 'my\_checkbox' is checked.

```
  $form['my_field_price']['#states'] => array(
    // Show and make the field required if 'my_checkbox' is checked.
    'visible' => array(
      ':input[name="my_checkbox"]' => array('checked' => TRUE),
    ),
    'required' => array(
      ':input[name="my_checkbox"]' => array('checked' => TRUE),
    ),
  ),

```
> 0 votes

---
Tags: entities
---


title: English translation as drupal message

text:
# Question
Title: English translation as drupal message
I am trying to add the English title as a drupal\_set\_message on all node pages if available - (Ive done something similar on the CMS) and if the user has node edit permissions (this can be checked using the node\_access function).

Code for cms example mentioned. Inside a hook form alter.

```
// Translation display on CMS page
$nid = (isset($form['nid']['#value'])) ? $form['nid']['#value'] : false;
if($nid) {
    $node = node_load($nid);

    if($node) {
        $lang = 'en';
        $translations = translation_node_get_translations($node->tnid);

        $translated_node = (isset($translations[$lang])) ? node_load($translations[$lang]->nid) : $node;
        $translated_title = '<h3>English Translation: ' . $translated_node->title . '</h3>';
    }
}

$form['#prefix'] = (isset($translated_title) && $translated_node->title != $node->title) ? $translated_title : '';

```

I am now wanting something similar but as a drupal\_set\_message on all node pages.

# Answer
I achieved it by using the following code in the template file.

```
$node = menu_get_object();

if (node_access('update', $node)):
    $lang = 'en';
    $translations = translation_node_get_translations($node->tnid);
    $translated_node = (isset($translations[$lang])) ? node_load($translations[$lang]->nid) : $node;
    if(is_object($translated_node)):
?>
  <div class="title-container">
    <div class="container">
      <h3>English title: <b><?php print $translated_node->title; ?></b></h3>
    </div>
  </div>
<?php endif; ?>
<?php endif; ?>

```
> 1 votes

---
Tags: i18n-l10n
---


# Question
Title: How to change the default images path and direct it to the external directory
I just want to know if there is anyway set drupal to upload images to the directory outside the drupal installation like loc\*lhost/site-name/image-upload/... rather than loc\*lhost/site-name/drupal/sites/all/default/.... My drupal installation directory is loc\*lhost/site-name/drupal/

Thank you JOnas

# Answer
Use **Private File System**, go to `admin/config/media/file-system` and provide the private file system path. After saving it, select **Private local files served by Drupal** as `Default download method`. After that edit your image field and choose `Private Files` as **Upload Destination**

Note : It should be writable by Drupal and not accessible over the web.
> 1 votes

# Answer
You can use absolute URLs. So assuming that you drupal directory is at /loc\*lhost/site-name/drupal and you want the files to be stored in /loc\*lhost/site-name/image-upload, you can enter /loc\*lhost/site-name/image-upload in the public or private image directory. Make sure that this directory is writeable by the web server.
> 0 votes

---
Tags: media, files, uri
---


title: Folder permissions, owner/groups

text:
# Question
Title: Folder permissions, owner/groups
I am using the FileField Sources module

One of the features is that it allows you to transfer images from a URL to your drupal folder directly, instead of having to save the image on your computer and then selecting it for upload.

The problem I am having is that it won't let me transfer the file.

> http://anywebsite.com/picture.jpg could not be copied, because the destination directory is not properly configured. The folder permission is set to 775, as it should be.

I think it has something to do with the Owner/Group of Ubuntu.

# Answer
In such cases, Drupal first downloads the image to the temporary directory and then moves it to the public directory. Go to admin/config/media/file-system. Make sure that both temporary and public directories are defined and both are writeable by the web server. The easiest way to do this is to make the web server user the owner of the directory. The command is:

```
sudo chown -R www-data <directory>

```

where www-data is the web server user. Depending on your OS and web server, the user could be apache2 or httpd as well.
> 1 votes

---
Tags: files
---


title: Version scheduling for nodes

text:
# Question
Title: Version scheduling for nodes
I'm looking for a way (simple) for my editor to save a draft version of an already published node to a later date.

So in other word a way to publish changes on a later date!

Having the possibility to have more than one version on bank would be nice.

Thanks!

# Answer
You can keep your versions of nodes using Revisioning module.In addition to it you can use Diff Moudule to compare between two versions of nodes.

And you can use Scheduler Module. to schedule the node publish.
> 2 votes

# Answer
Use the Revisioning and Revisioning Scheduler modules. You will need to clone the git repo of Revisioning Scheduler since it's in sandbox.

Standard Scheduler module doesn't work well with scheduling of revisions.
> 0 votes

---
Tags: nodes
---


# Question
Title: Drupal 7 open image in colorbox when a “button” on the image is clicked, otherwise go to content
I am using Drupal 7 and Colorbox module with Views 3.

In my view I have an image field. Right now based on my settings when I click the image it can either go to the content or open the image itself in Colorbox. What I want to achieve is maybe have a button (or a link?) at the bottom right corner of the image, when this button is clicked, image opens in Colorbox, if image itself is clicked, it brings you to the content (node page).

How can I achieve this?

# Answer
In Drupal 7 you can achieve it by the following steps

Steps

* Create a new VIEW and add the following fields
* **Background image** : Add the image which you want to show as background image using imagestyle. Also add the link to the node using **Link image to**. And check **Exclude from display**.
* **Colorbox image** : Add the image which you want to show inside COLORBOX using imagestyle. Dont add the link to this image and check **Exclude from display**
* **Image icon** : Add the image which is used to render on the top of the background image using imagestyle. And check **Exclude from display**.This image we will use in **COLORBOX TRIGGER** field.
* **Colorbox Trigger** : Add this field and make **Image icon** field as the **TRIGGER FIELD** and **Colorbox image** as its CONTENT by use **"Replacement patterns"**.
* **Custom text** : Add **Global: Custom text** field and add the below html inside it and make sure you should replace \[Background image\] and \[Colorbox Trigger field\] using **"Replacement patterns"**. It act like a container.

```

<div class="image-wrapper">
     <div class="outer-image">[Background image]</div>
     <div class="inner-image">[Colorbox Trigger field]</div>
</div>

```

OUTPUT

Note : Arrange the **image icon** above the **background image** using CSS
> 1 votes

---
Tags: views, javascript
---


# Question
Title: Find a particular menu item within the primary links
Let's say we have a menu inside the primary links, in my case the Misc menu.

As it seems under Misc menu it can be any Content Type (of course and on every other menu)

The question is how can I make it to appear ONLY the Misc menu somewhere in my website without reconstructing it as a separate menu?

I want it to stay in the primary links.

So far I've tried it with the context module, but seems that is not working properly with the sub menus under the Misc menu. It works only for the Misc page.

Even if I do this: menu\_set\_active\_menu\_name ('primary-links') it's still working only for the Misc menu, not its childrens.

Creating a block with only the needed menu item and the use of the template\_preprocess\_block is another approach but not recommended, while I have to refer to the block through the block ID (`$bid`).

# Answer
Menu block \- it provides configurable blocks of menu trees starting with any level of any menu.
So if you’re only using your theme’s Main menu links feature, you can add and configure a “Main menu (levels 2+)” block. That block would appear once you were on one of the Main menu’s pages and would show the menu tree for the 2nd level (and deeper) of your Main menu and would expand as you traversed down the tree. You can also limit the depth of the menu’s tree (e.g. “Main menu (levels 2-3)”) and/or expand all the child sub-menus (e.g. “Main menu (expanded levels 2+)”).
> 0 votes

---
Tags: 6, routes
---


# Question
Title: Newbie Form Question: I'm only getting hidden fields
I am trying to produce a form that only consists of 1 button. I have created a tab in the user menu screen with the following...

```
  $items['user/%/user_options'] = array(
    'title' => 'Newsletter/Membership Subscription',
    'description' => 'Allows user to subscribe or unsubscribe to the newletter and membership.',
    'page callback' => 'user_options_subscribe_choices',
    'page arguments' => array(1),
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'file' => 'user_options.user.inc',
    'type' => MENU_LOCAL_TASK,
);

```

...then in user\_option.user.inc I have this...

```
function user_options_subscribe_choices($wildcard) {
$build = array();

//check that the user id is valid...
if (is_numeric($wildcard) && ($account = user_load($wildcard))) {

    //return correct forms...
    if(in_array('Newsletter Subscriber', $account->roles)) {
        $build['form_one'] = drupal_get_form('delete_newsletter_subscription_form');
    } else {
        $build['form_one'] = drupal_get_form('add_newsletter_subscription_form');
    }

    if(in_array('Paying Member', $account->roles)) {
        $build['form_two'] = drupal_get_form('delete_membership_form');
    } else {
        $build['form_two'] = drupal_get_form('add_membership_form');
    }

    return $build;
    //return drupal_get_form('add_membership_form');
}else{
    return drupal_not_found();
}
}

function add_newsletter_subscription_form(&$form_state){
$form = array();

$form['submit'] = array(
    '#type' => 'submit',
    //'#description' => 'You are not currently recieving SCiO newsletters.',
    '#value' => t('Subscribe to the SCiO Newsletter'),
    //'#attributes' => array('onclick' => "javascript:get(this.parentNode);"),
);

$form['choice'] = array(
'#type' => 'select',
'#title' => t('Cake or pie?'),
'#description' => t('Would you like cake or pie?'),
'#options' => array(
    'cake' => t('Cake please'),
    'pie' => t('Pie I guess'),
),
'#default_value' => 'cake',
'#required' => TRUE,
);

return $form;
}

```

I have only given 1 example of the form function

...Now the odd thing is, is that I do see 2 forms in the html. BUT! they consist only of hidden fields.

Can anyone help me out?

Thank you.

# Answer
```
function add_newsletter_subscription_form(&$form_state){
    $form = array();

    $form['submit'] = array(
        '#type' => 'submit',
        //'#description' => 'You are not currently recieving SCiO newsletters.',
        '#value' => t('Subscribe to the SCiO Newsletter'),
        //'#attributes' => array('onclick' => "javascript:get(this.parentNode);"),
    );

    $form['choice'] = array(
    '#type' => 'select',
    '#title' => t('Cake or pie?'),
    '#description' => t('Would you like cake or pie?'),
    '#options' => array(
        'cake' => t('Cake please'),
        'pie' => t('Pie I guess'),
    ),
    '#default_value' => 'cake',
    '#required' => TRUE,
    );

    return $form;
    }

```

You missed the first argument of this function $form.

```
function delete_newsletter_subscription_form($form, &$form_state){
$form = array();

$form['submit'] = array(
    '#type' => 'submit',
    //'#description' => 'You are not currently recieving SCiO newsletters.',
    '#value' => t('Subscribe to the SCiO Newsletter'),
    //'#attributes' => array('onclick' => "javascript:get(this.parentNode);"),
);

$form['choice'] = array(
'#type' => 'select',
'#title' => t('Cake or pie?'),
'#description' => t('Would you like cake or pie?'),
'#options' => array(
    'cake' => t('Cake please'),
    'pie' => t('Pie I guess'),
),
'#default_value' => 'cake',
'#required' => TRUE,
);

return $form;
}

```
> 0 votes

---
Tags: forms
---


# Question
Title: How can I print the value of the node body using PHP with the text format applied?
I am printing the node body using PHP on an admin view via a template; however, when I do this, the text comes out as one giant block (spacing is ignored). However, when I go to edit the node, the content is spaced properly.

My code looks like this:

```
print "Body: " . $body[0]['value'];

```

What do I need to change to make sure the spacing/formatting is printed out properly?

# Answer
> 3 votes
I believe you're looking for the `check_markup()` function:

> Runs all the enabled filters on a piece of text.
>
> Note: Because filters can inject JavaScript or execute PHP code, security is vital here. When a user supplies a text format, you should validate it using filter\_access() before accepting/using it. This is normally done in the validation stage of the Form API. You should for example never make a preview of content in a disallowed format.

E.g.

```
$markup = check_markup($body[0]['value'], $body[0]['format']);

```

# Answer
> 1 votes
You can use this drupal default function "field\_view\_field()".

For this to be done you just need to load that particular node by its node id

```
<?php
$node = node_load(10);
$display = array('type' => 'full_html');
 $output = field_view_field('node', $node, 'body', $display);
 print render($output);

?>

```

$display can have option full\_html/filtered\_html etc. You can apply more options to the display options to print it in desired format. You can refer this link Here

# Answer
> 0 votes
depending on the template and the preprocess, but try `render($body)`

---
Tags: nodes
---


# Question
Title: View in views header still displaying when no result
I tried this question: Empty view is rendered even though there is no result

And it didn't work

I have a view of Judge nodes that displays using a contextual filter. Inside that view I have embedded a view block into the header that displays a Featured Judge, passing it the contextual filters and left 'Display even if no results' unchecked. In the Featured Judge view I have set it to not display empty fields. Also I have added a filter to a field as suggested in the question above.

Still I get the following output in the views header:

```
<div class="view view-featured-judge view-id-featured_judge view-display-id-block view-dom-id-0cfff43385fef2dba170ae09d3f818cf"></div>

```

I have dpm'd the views array in preprocess view, and results is empty. I have set it to NULL and it still displays. At present the only solution appears to be to check if the results array is empty and if so add a class to display: none; which is frankly ludicrous.

Anyone have any ideas?

# Answer
> 0 votes
Looks like you have added the filter only for the Featured Judge View.

Try adding a filter in the View that lists the Judge Nodes. This will completely note render the whole view at all.

---
Tags: blocks, views
---


title: Using tokens in block titles

text:
# Question
Title: Using tokens in block titles
Plugging tokens into a block's title only shows the input text instead of what the token's supposed to output.

Is there a way to enable/use tokens in block titles, or maybe an alternative method of getting the results I want?

I've tried using Token Filter module, but it doesn't change the functionality.

I am trying to insert the \[user:profile-realname\] token into a block title (specifically the User Menu block title). The token is in my list of tokens available to use via HELP in the backend.

# Answer
AFAIK, this cannot be achieved using the block title field, however using the Token Filter module, you can just drop the token in the body area of the block and wrap it in an H2 tag and it will appear as if it was the block title. (Just set the block title to `<none>`)
> 7 votes

# Answer
Try the token\_replace() function in the block preprocessor. Example:

```
$node = menu_get_object();  // Get the current node
if ($node) {
  $vars['elements']['#block']->subject = token_replace($vars['elements']['#block']->subject, array('node' => $node));
}

```

Maybe you have to load the user too to have the user tokens available.
> 5 votes

# Answer
Once Support token replacement for block titles is implemented, you'll be able to use the *\[current-user:profile-realname\]* token.
> 2 votes

# Answer
Set Title to empty, and just add a Global Text Area in Views Header! Add here h tags or whatever html you want. Much easier and no coding required...
> 1 votes

---
Tags: blocks, tokens
---


title: How to create Newsletter in drupal?

text:
# Question
Title: How to create Newsletter in drupal?
I want to create a newsletter in drupal. What i want is the ability to subscribe the users that are not registered to the site. I can use the third party or any contrib modules available . Any help ..?

# Answer
Check out Simplenews module.

```
Simplenews publishes and sends newsletters to lists of subscribers. Both anonymous and
authenticated users can opt-in to different mailing lists. HTML email can be sent by
adding Mime Mail module.

```
> 3 votes

---
Tags: emails
---


title: Drupal Commerce Market Place

text:
# Question
Title: Drupal Commerce Market Place
I cannot find a link to add seller/vendor/store in the Commerce-Marketplace module.

I am using Drupal Commerce Kickstart.

# Answer
> 2 votes
As far as I know, there is not a direct solution for this. I have searched google for this,couldn't find a solution. But I will share what I think is correct.

The store in commerce market place is actually similar to an organic group, where you can add members and products. The store is implemented as an entity. If you go to admin/structure/entity-type/commerce\_store/store and add a store, you have created a store. Now, if you try to add a product, you can type the name of the store that you had created, which will auto-fill for you.

Regarding the vendors, you may have to create a role and give permission to create stores for that role.

Let me know how that goes.

---
Tags: commerce
---


# Question
Title: Is it possible to show only node contents in shadowbox pages?
I'm looking for a method to display content (nodes) in a shadowbox overlay without any blocks or menus around it. even if the user is logged in.

Has someone an Idea how to do this are there even better parameters for rel shadowbox than the height and width parameter to reduce the window size?

# Answer
## For Drupal7:

Add to your theme `template.php` (*or add inner of function code to existing function prepropress\_page closer to the end*) next function:

```
/**
 * Override or insert variables into the page templates.
 */
function YOURTHEME_preprocess_page(&$vars, $hook) {
  if (isset($_GET['shadow']) && $_GET['shadow']) {
    $vars['theme_hook_suggestions'][] = 'page__empty';
  }
}

```

Add `page--empty.tpl.php` to your theme folder - take original copy from `page.tpl.php`, but remove printing all header, sidebars, footer regions. E.g.:

```
<?php
/**
 * @file
 * Returns the HTML for Drupal page only with content region = empty page.
 */
?>
<?php if ($title): ?>
  <h1 class="page__title title" id="page-title"><?php print $title; ?></h1>
<?php endif; ?>
<?php print render($page['content']); ?>

```

Make shadowbox scripts added to any page (shadowbox ui settings), and you can do next anywhere:

```
<a href="/node/1?shadow=1" rel="shadowbox" title="About">About</a>

```

So, any link with `url?shadow=1` and `rel="shadowbox"` will shown on shadowbox popup window only content without sidebars. Control size of window on rel="shadowbox" as documented.

For shadowbox links that generated automatically (views, fields) you should override it via settings or template.
> 0 votes

---
Tags: modal-dialogs
---


# Question
Title: Render main menu in page.tpl.php, with override from template.php
In Drupal 7, I'm trying to add a `<span>` tag inside the `<a>` tag of an item in the Main Menu, but it only works for the 'Navigation' menu which is a block, however, I am trying render it within page.tpl.php

I've been searching this up for a while now and can't seem to get it to work. I was attempting to follow the information from How do I insert a \<span\> \</span\> tag inside the \<a\> \</a\> tag on my main menu

Here's a snippet from `page.tpl.php`

```
  <nav id="main-menu" class="navigation span8">
    <?php print theme('links__system_main_menu', array(
      'links' => $main_menu,
      'attributes' => array(
        'id' => 'main-menu-links',
        'class' => array('links', 'clearfix'),
      ),
      'heading' => array(
        'text' => t('Main menu'),
        'level' => 'h2',
        'class' => array('element-invisible'),
      ),
     )); ?>
  </nav> <!-- /#main-menu -->

```

and from `template.php`

```
function THEMENAME_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

//$element['#attributes']['class'][] = 'menu-' . $element['#original_link']['mlid'];

$get_title= $element['#title'];
$element['#title']='<span>' . $get_title .' </span>';

$element['#localized_options'] += array(
    'attributes' => array(),
    'html' => TRUE,
  );

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```

# Answer
The function you need to override is theme\_links() and to do that just for the main menu you can use `mytheme_links__system_main_menu` as the function name. To add span tags you can then modify the part that starts with `if (isset($link['href']))`:

```
if (isset($link['href'])) {
  // Pass in $link as $options, they share the same keys.
  $link['html'] = TRUE;
  $output .= l('<span>'. check_plain($link['title']) .'</span>', $link['href'], $link);
}

```
> 6 votes

# Answer
You could try THEME\_menu\_link\__main\_menu(array $variables)

```
function THEMENAME_menu_link__main_menu(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

//$element['#attributes']['class'][] = 'menu-' . $element['#original_link']['mlid'];

$get_title= $element['#title'];
$element['#title']='<span>' . $get_title .' </span>';

$element['#localized_options'] += array(
    'attributes' => array(),
    'html' => TRUE,
  );

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```
> 0 votes

---
Tags: routes, theming
---


# Question
Title: Render view for specific user, drupal_mail
Is it possible to generate the content of the view as a specific user. So only the content the user has access to is rendered.

```
//Get view
$view = views_get_view("list_nodes");
//Pass arguments
$view->args = $locatie;
//Generate content
$content = $view->execute_display("block");

```

I got a custom module wich gets a list of users, to all those users the content of this view need to be send. But only the content the use has access to.

# Answer
> 1 votes
To render a view programmatically as a specific user, you need to adjust the global $user variable.

```
//Run script as a sepcific user
global $user;
$original_user = $user;
drupal_save_session(FALSE);
$user = user_load($uid);

//Your code goes here
....

//Return global variable to its orignal value
$user = $original_user;
drupal_save_session(TRUE);

```

---
Tags: views, emails, users
---


# Question
Title: How to update current url of view page so that it will filter correct result?
I have created view to search nodes of video from content type channel. I have set the URL as channel/%/search in view. when redirected to the page the the URL will be `channel/all/channel-search?title=test`. But I want to replace 'all' with 'nid' which I have got by php code. In short I want to replace `channel/all/channel-search?title=test` with `channel/*NID*/channel-search?title=test` (nid may be anything channel/26). I have written the code in views contextual filter but it is not working.

```
$path = $_SERVER['HTTP_REFERER'];
$filter = preg_replace('///','',parse_url($path,PHP_URL_PATH),1);
$path = drupal_lookup_path("source", $filter);
$node = menu_get_object("node", 1, $path);
$nid=$node->nid;
return $nid;

```

# Answer
Instead of doing your way, try out the following

Implement `hook_form_alter()` and modify the `#action` attribute of views exposed form.

```
function mymodule_form_alter(&$form, &$form_state, $form_id){
 if($form['#id']=='views-exposed-form-frontpage-page'){
  $node = menu_get_object("node", 1);
  if(!is_null($node)) {
     $form['#action']=$form['#action']."/".$node->nid;
  }
 }
}

```

And then in your view add a contextual filter `Content:nid` and provide default value as **Content ID from URL**

Note : The code I tested with frontpage view, so replace the `form id` with your own.
> 0 votes

# Answer
Add a new contextual filter, select 'Node: Nid', then check 'Provide default value' and in the select box choose 'Content ID from URL'
> 0 votes

---
Tags: views, uri
---


# Question
Title: How to create main links like home ,services programatically?
I am creating a new website in Drupal 7,but from my past efforts I tried adding main menu links(home,services,clients,blog etc)but all in vain!!

Can anyone tell me how to create main menu links programmatically or through admin interface?

# Answer
> 0 votes
```
// You can use the following code to create a menu.

// Path.
$path = 'admin/structure/menu/manage/';
// Title of your menu.
$menu['title'] = 'My Another Menu';
// Description.
$menu['description'] = 'My Another Menu';

// Manu name like navigation, management which we have in drupal.
$menu_name = 'custommenu';
$menu['menu_name'] = $menu_name;

// Link title.
$link['link_title'] = 'My Another Menu';
// Link path.
$link['link_path'] = $path . $menu_name;
// Router path.
$link['router_path'] = $path;
// Module name.
$link['module'] = 'menu';
$link['plid'] = 0;

// Saves a menu link.
menu_link_save($link);
// Saves a custom menu.
menu_save($menu);

// After creating main menu. You can create links under it.
// Use the below code to create custom links.

$item_link = array(
  'link_path' => '<front>',
  'link_title' => 'Test link',
  'menu_name' => 'custommenu',
  'weight' => 0,
  'expanded' => 1,
);
// Creates custom link under main menu.
menu_link_save($item_link);

```

---
Tags: routes
---


title: How to display a node as multi-step?

text:
# Question
Title: How to display a node as multi-step?
I have installed Multistep module and it worked well for forms (e.g. save node, edit node). But when I switched to "Manage Display" tab and add "Multistep Form" group, it didn't work. No multistep form block appeared in Structure-\>Block for displaying a node.

I have also tried "Div" for displaying field group, but it's just a collapsible box.

Is it possible to display node as multi-step?

# Answer
> 1 votes
It is possible to use node as multi step form with help of **page break field Module** . Enabled it and make it as one of the field where want in the node

---
Tags: forms
---


title: Add html to registration page

text:
# Question
Title: Add html to registration page
I have a registration form, and in the beginning of my registration page I want to show a title, subtitle and an image. A wireframe is like this:

As you can see there are checkboxes (select field) of my register form. But I would like to know how I can add the upper part to my page (Title, subtitle, logo).

What would be the best way to do this?

# Answer
You have to override the theme you are using in Drupal.

There is a good overview of this here.
> 2 votes

---
Tags: forms, users, theming
---


# Question
Title: Correct way for a db_query for nodes between two timestamps
I have a very simple db\_query. I want to look for any node created between two timestamps.

This query works fine in MySQL shell

```
SELECT nid as id,created as start,title FROM node WHERE created BETWEEN '1403564400' AND '1403650800';

```

This works fine in Drupal

```
$data = db_query("SELECT nid as id,created as start,title FROM node")->fetchAll();
echo json_encode($data);

```

As soon as I add in the BETWEEN conditions below I get an Internal Server Error.

```
$data = db_query("SELECT nid as id,created as start,title FROM node WHERE created BETWEEN '1403564400' AND '1403650800'")->fetchAll();

```

I am unsure what I am doing wrong here, perhaps someone can point me in the right direction please!

# Answer
> 6 votes
You can try using db\_select instead wich is a better way to create query with Drupal (assuming you are using Drupal 7).

```
$start_time = '1403564400';
$end_time = '1403650800';
$query = db_select('node', 'n')
  ->fields('n', array('nid', 'created', 'title'))
  ->condition('created', array($start_time, $end_time), 'BETWEEN');
$result = $query->execute();
$record = $result->fetchAll();

```

---
Tags: datetime, database
---


title: How do I index a custom added field?

text:
# Question
Title: How do I index a custom added field?
When I create a new content or update existing content gets index immediately on solr search api index. But I have added custom field to search index using entity\_info\_alter I have added custom field. The custom field gets updated on Solr only on cron job runs. I want it to update when I create/update any content.

How it can be achieved?

# Answer
I think this is the expected behavior: Content is marked to index when you update it, and the next cron run will reindex your items.

You need to enable the checkbox "Index items immediately" for this to be a immediate operation. Be aware this is a costly operation.

If your field type is custom, you might need to expose the value you want to entity API. Check out how to do this in Describe field properties to make custom fields work with Entity Metadata Wrappers.
> 1 votes

---
Tags: search
---


# Question
Title: profile2 - change default edit path to custom profile
I use profile2 module. After visiting user account, user is able to edit account by clicking on edit tab. It leads to Account secondary tab (user/x/edit). User is presented with empty passwords fields and other fields which can be sometimes confusing.

Question: Is it possible to change this default path to direct user to main profile created by profile2 module? (user/x/edit/main)

Thank you

# Answer
> 1 votes
Well actually you can, there is a submodule of the profile2 called "profile pages"

> With profile2 user account settings and user profiles are conceptually different things, e.g. with the "Profile pages" module enabled users get two separate menu links "My account" and "My profile".

Via the included "Profile pages" module profiles can be viewed and edited at their own page and get their own menu link, e.g. "My profile".

with the profile menu paths already setted up for your custom profile then you need to remove the edit tab that points to the default profile edit page of drupal. For delete this tab follow this tutorial http://www.zyxware.com/articles/4159/solved-drupal-how-to-hide-menu-tabs-and-menu-links-in-drupal-7

Then you can add your own edit tab that will link to your custom profile edit page https://www.drupal.org/node/1578582

---
Tags: 7, users
---


# Question
Title: Is Sweaver module compatible with Domain Access module?
I'm configuring a Domain Access website and having some issues on making Sweaver module working as it suppose to be. I see that Sweaver back end is configurable based on domain. What about the switch theme feature? Is there any known compatibility issue between these two modules?

# Answer
> 0 votes
It doesn't work because it saves all the data files in the same place and all the sites will have your same changes. The admin settings maybe able to be changed based on the domain but code that controls your CSS changes doesn't change based on the current domain.

This is with Drupal 6.

---
Tags: domain-access
---


# Question
Title: Get field value directly from inside views-view-list.tpl.php
Inside `views-view-list.tpl.php` there is a loop like this:

```
<?php foreach ($rows as $id => $row): ?>
  <li class="<?php print $classes_array[$id]; ?>"><?php print $row; ?></li>
<?php endforeach; ?>

```

I want to be able to access the actual values of the fields inside each item, rather than passing off the rendering of the html to `views-view-fields.tpl.php`.

In pseudocode, I would like to do this (THIS CODE DOES NOT WORK):

```
<?php foreach ($rows as $id => $row): ?>
  <?php print $row->$fields['field_my_field_name']; ?>
<?php endforeach; ?>

<?php foreach ($rows as $id => $row): ?>
  <?php print $row->$fields['field_my_second_field_name']; ?>
<?php endforeach; ?>

```

Would I actually use the `$row` object, or would I use something else?

# Answer
> 2 votes
> views-view-list.tpl.php file it's a view template to display a list of rows, not fields.

**Theming only fields:**

```
<?php foreach ($fields as $id => $field): ?>
    <li><?php print $field->content; ?></li>
<?php endforeach; ?>

```

** file: views-view-fields--\[view name\]--\[display\].tpl.php*

**Theming the whole output:**

```
<div class="<?php print $classes; ?>">
    <?php foreach ($view->style_plugin->rendered_fields as $delta => $item): ?>
        <li><?php print $item['field_my_field_name']; ?></li>
    <?php endforeach; ?>
</div>

```

** file: views-view--\[view name\]--\[display\].tpl.php*

# Answer
> 3 votes
took me a while to work this out so sharing the solution i used.

```
<?php foreach ($rows as $id => $row): ?>
    <?php print $view->render_field('field_my_field_name', $id);?>
<?php endforeach; ?>

<?php foreach ($rows as $id => $row): ?>
    <?php print $view->render_field('field_my_second_field_name', $id);?>
<?php endforeach; ?>

```

# Answer
> 1 votes
There is a `$view` variable inside most Views templates that contains the entire View Object. Inside of it, you can access the raw results via `$view->result` which is basically an array of the rows. Throwing in a `drupal_set_message('<pre>' . print_r($view->result, TRUE) . '</pre>')` or equivalent will give you an idea of what you have to work with.

# Answer
> 0 votes
The simplest way is : $fields\["field\_name"\]-\>content; Where field\_name -\> cck field name.

Hope that will help !!

Cheers ! Raj

---
Tags: views, entities, theming
---


# Question
Title: Can't place context-controlled block below user picture on user profile page
I have a views block of user content that I want to display on the user profile page below a custom generated block of user information created in code via a theme function (using the $build\['user\_picture'\] element in hook\_entity\_view\_alter(). If I place the block into the appropriate region using the blocks admin page and configure the block to only appear at user/\*, it works fine. However, if I place the block using Context module with the User Profile condition, it places the block above all other content, and there seems to be nothing I can do to drop the block below the user\_picture element. The weight for the user picture element is set to -10 by default, but even if I make it lower, nothing changes is.

Is there a way to control the placement of the block via Context so it is below the user\_picture element? I can see no way via the UI - either for Context or user profile configuration - or code. Do I have to override user-profile.tpl.php and manually split everything out? I need to use Context to be able to control which user profiles the block is on, so if I can't re-order, then I have to find another mechanism (probably Panels) to control this placement.

Thanks.

# Answer
Following the general rule (at least for me) that posting a question in a public forum somehow helps me find the answer, I figured this out as soon as I posted this. All I had to do was click on the "Show row weights" link, alter the weight, and that put it right where I wanted it.
> 0 votes

# Answer
> The weight for the user picture element is set to -10 by default, but even if I make it lower, nothing changes is.

The default weight for system content is 0, so display below that you would want a weight of 1 or more for your block in Context \> Reaction \> Block (if I'm understanding your issue correctly).
> 0 votes

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


# Question
Title: Add a prefix to a views field pre_render
Our Drupal distribution is to be used with different currencies defined by a custom variable...when we display nodes in a view with the price field we don't add the currency prefix...i want to add it through im guessing hook\_views\_pre\_render? How can i inject a prefix using my custom variable?

This is what i am thinking:

```
if (in_array($view->name, $views_with_prices)) {
//dsm($view->result);
foreach ($view->result as $activity) {
  //dsm($activity);
  $price = $activity->_field_data['nid']['entity']->field_average_price['und'][0]['value'];
  if ($price != 0) {
    $activity->_field_data['nid']['entity']->field_average_price['und'][0]['value'] = variable_get('my_currency') .  $activity->_field_data['nid']['entity']->field_average_price['und'][0]['value'];
  }
}
}

```

but ideally i'd like to use a specific prefix functionality that comes with cck fields if possible or views equivalent.

# Answer
> 1 votes
I would do it by creating a template file, like `views-view-field--fieldname.tpl.php`, for the field and add the currency prefix to it.

---
Tags: views
---


title: Hook Advance Search Form

text:
# Question
Title: Hook Advance Search Form
I want to hook the Drupal advance search form for add more filter criteria,

I want to add the below criteria
1) Search By Post Date
2) Search Between Post Date
3) Search by last day, last 7 days

I applied the hook Mymodule\_search\_form\_alter(&$form, $form\_state) {} to add the fields,

Please You suggest me Guys that how can i alter the search query, i am looking for this by last 2 days, but nothing found

This is the link that i got only

https://stackoverflow.com/questions/8575289/extending-drupal-7-search

But that not works,

Any suggestions Please...!!

# Answer
To alter the query itself, try hook\_search\_api\_query\_alter (for search api) or hook\_search\_execute for the core search
> 0 votes

---
Tags: hooks, search
---


title: When is hook_user_presave triggered?

text:
# Question
Title: When is hook_user_presave triggered?
I'm trying to create a little module that operates on similar principals as a shopping cart, but has nothing to do with e-commerce. I want to add paired values to `$user->data['cart']` on a very frequent basis. Everyone seems to agree that hook\_user\_presave is the way to do this. My question is this, when does hook\_user\_presave trigger? Can it be called from inside another fucntion or an .inc file, or does it happen on pageload? I am absolutely befuddled, since I thought hooks were basically event handlers for Drupal Core.

Can I, say, do the following?

```
test.module:
<?php
function mymodule_user_presave (&$edit, $account, $category) {
    $edit['data']['cart'] = $edit;
}
/* ... */

test.inc:
<?php
/* ... */
function mysavefunction () {
  $myvar = array('sweetdata' => 5);
  $account = user_load($user -> uid);
  mymodule_user_presave ($myvar, $account)
}
/* ... */

```

If you could even point me to some documentation other than this useless api page, I would be greatly in your debt.

# Answer
> 1 votes
`hook_user_presave` is an event listener that's called when a user account is saved.

It's invoked from `user_save` and shouldn't normally be called manually.

```
// Invoke hook_user_presave() for all modules.
user_module_invoke('presave', $edit, $account, $category);

```

If you want to save data on the user account, just use `user_save`

---
Tags: users
---


# Question
Title: How do I completely disable user profiles and the dedicated login page in Drupal 7?
I am building a site in which user accounts matter only to provide the `authenticated` / `not authenticated` information. I created a custom login block that is always displayed (in the header of the website). I want to reach the following two points:

* Since user profiles are not needed, I want to disable them for usability reasons. The users should, after login, be redirected to the landing page of my website.
* Also, I want to disable the dedicated login page that appears, i.e., upon entering the wrong password.

Is there any easy way to do these things?

# Answer
> 2 votes
Yes, you can change built in menu / page callbacks with `hook_menu_alter`

For example, alter `user_menu`

```
/**
 * Implements hook_menu_alter
 */
function MYMODULE_menu_alter(&$items){
  // Go to front page when visiting /user and /user/login
  $items['user']['page callback'] = 'drupal_goto';
}

```

---
Tags: 7, users
---


# Question
Title: How to make field names of a custom database table show up in the Views UI
I want to create a view using a table that is already present in the database, I used the hooks\_views\_data function to describe the tables and its fields. While creating a new view I can see my custom table listed in the view's selection option, but when I use the custom table I don't see the field name for my table instead I see " Array: Array (Array)" in the field selection option.

Database:

```
                                    Table "chado.biomaterial_value"
          Column        |  Type  |                               Modifiers
---------------------+--------+---------------------------------------------------               ---------------------
          name                | text   |
          cultivar            | text   |
          age                 | text   |
          tissue              | text   |
          treatment           | text   |
          phenotype           | text   |
          developmental_stage | text   |
          source              | text   |
          bio_val_id          | bigint | not null default nextval('biomaterial_value_bio_val_id_seq'::regclass)
     Indexes:
     "biomaterial_value_pkey" PRIMARY KEY, btree (bio_val_id)

```

Things that I have implemented: bioviews.info

```
name = Bio_Views
description = Custom module For learning views coding
core=7.x
version=VERSION
dependencies[] = views

```

bioviews.module

```
<?php
function bioviews_views_api() {
return array(
    'api' => '3.0-alpha1',
    'path' => drupal_get_path('module','bioviews'). '/views',
);
}

```

views/bioviews.views.inc:

```
 <?php

  /**
  * @file
  * Views integration for the mydons custom module
  */

 /**
  * Implements hook_views_data()
  *
  */
  function bioviews_views_data() {
     $data = array();

      // Table name is "biomaterial_value".
      $data['biomaterial_value']['table']['group'] = t('Biomaterial');

      $data['biomaterial_value']['table']['base'] = array(
           'field' => 'bio_val_id',  //Primary key
           'title' => 'biomaterial_value custom table',
           'help' => 'biomaterial_value custom database table'
         );

   // Description of name field

    $data['biomaterial_value']['name'] = array(
         'title' => t('NAME'),
         'help' => t('biomaterial_val name field'),
         'field' => array(
            'handler' => 'views_handler_field',
            'click sortable' => TRUE,
         ),
         'sort' => array(
             'handler' => 'views_handler_sort',
          ),
         'filter' => array(
              'handler' => 'views_handler_filter_string',
           ),
         'argument' => array(
              'handler' => 'views_handler_argument_string',
          ),
       );

  // Description of cultivar field

  $data['biomaterial_value']['cultivar'] = array(
      'title' => t('CULTIVAR'),
      'help' => t('biomaterial_val cultivar field'),
      'field' => array(
         'handler' => 'views_handler_field',
         'click sortable' => TRUE,
       ),
       'sort' => array(
       'handler' => 'views_handler_sort',
    ),
   'filter' => array(
       'handler' => 'views_handler_filter_string',
   ),
   'argument' => array(
       'handler' => 'views_handler_argument_string',
  ),
);

 // Description of the age field

  $data['biomaterial_value']['age'] = array(
      'title' => t('AGE'),
      'help' => t('biomaterial_val age field'),
      'field' => array(
          'handler' => 'views_handler_field',
          'click sortable' => TRUE,
        ),
       'sort' => array(
            'handler' => 'views_handler_sort',
        ),
        'filter' => array(
            'handler' => 'views_handler_filter_string',
         ),
        'argument' => array(
            'handler' => 'views_handler_argument_string',
         ),
      );

   //Description of the tissue field

   $data['biomaterial_value']['tissue'] = array(
       'title' => t('TISSUE'),
       'help' => t('biomaterial_val tissue field.'),
       'field' => array(
       'handler' => 'views_handler_field',
       'click sortable' => TRUE,
       ),
       'sort' => array(
         'handler' => 'views_handler_sort',
        ),
        'filter' => array(
          'handler' => 'views_handler_filter_string',
       ),
        'argument' => array(
            'handler' => 'views_handler_argument_string',
        ),
     );

    // Description of the treatment field

    $data['biomaterial_value']['treatment'] = array(
        'title' => t('TREATMENT'),
        'help' => t('biomaterial_val treatment field.'),
        'field' => array(
           'handler' => 'views_handler_field',
          'click sortable' => TRUE,
        ),
        'sort' => array(
           'handler' => 'views_handler_sort',
         ),
         'filter' => array(
            'handler' => 'views_handler_filter_string',
          ),
         'argument' => array(
            'handler' => 'views_handler_argument_string',
         ),
     );

    // Description of the phenotype field

    $data['biomaterial_value']['phenotype'] = array(
         'title' => t('PHENOTYPE'),
         'help' => t('phenotype field.'),
         'field' => array(
             'handler' => 'views_handler_field',
             'click sortable' => TRUE,
          ),
          'sort' => array(
              'handler' => 'views_handler_sort',
           ),
          'filter' => array(
              'handler' => 'views_handler_filter_string',
            ),
            'argument' => array(
                'handler' => 'views_handler_argument_string',
            ),
       );

      // Description of the developmental_stage

       $data['biomaterial_value']['developmental_stage'] = array(
            'title' => t('DEVELOPMENT STAGE'),
             'help' => t('phenotype field.'),
             'field' => array(
                'handler' => 'views_handler_field',
                'click sortable' => TRUE,
            ),
            'sort' => array(
              'handler' => 'views_handler_sort',
            ),
            'filter' => array(
              'handler' => 'views_handler_filter_string',
            ),
           'argument' => array(
              'handler' => 'views_handler_argument_string',
             ),
         );

     // Description of the source field

      $data['biomaterial_value']['source'] = array(
          'title' => t('SOURCE'),
          'help' => t('phenotype field.'),
          'field' => array(
            'handler' => 'views_handler_field',
            'click sortable' => TRUE,
          ),
          'sort' => array(
            'handler' => 'views_handler_sort',
          ),
          'filter' => array(
             'handler' => 'views_handler_filter_string',
           ),
           'argument' => array(
              'handler' => 'views_handler_argument_string',
           ),
      );

      // Description of bio_val_id.
       $data['biomaterial_value']['bio_val_id'] = array(
         'title' => t('ID'),
         'help' => t('biomaterial_value ID field'),
         // Is field sortable TRUE.
         'field' => array(
             'click sortable' => TRUE,
          ),
         // Filter handler for filtering records.
        'filter' => array(
           'handler' => 'views_handler_filter_numeric'
        ),
        'sort' => array(
          'handler' => 'views_handler_sort'
        )
    );

     return $data;

 }

```

# Answer
> 0 votes
Your nesting isn't quite right in `hook_views_data`. You have `'base'` incorrectly nested under `'group`'

Try something like:

```
/**
 * Implements hook_views_data()
 *
 */
function bioviews_views_data() {

  $data = array();

  // Assumes table name is "biomaterial_value".
  $data['biomaterial_value']['table']['group'] = t('Biomaterial');

  $data['biomaterial_value']['table']['base'] = array(
    'field' => 'bio_val_id',  //Primary key
    'title' => 'biomaterial_value custom table',
    'help' => 'biomaterial_value custom database table'
  );

  // Description of bio_val_id.
  $data['biomaterial_value']['bio_val_id'] = array(
    'title' => t('ID'),
    'help' => t('biomaterial_value ID field'),
    // Is field sortable TRUE.
    'field' => array(
      'click sortable' => TRUE,
    ),
    // Filter handler for filtering records.
    'filter' => array(
       'handler' => 'views_handler_filter_numeric'
    ),
    'sort' => array(
      'handler' => 'views_handler_sort'
    )
  );

  /* ... Add other fields ... */
  // $data['biomaterial_value']['field_name'] = array();

  return $data;

}

```

Also, as an aside, remove

```
files[] = bioviews.module
files[] = views/bioviews.views.inc

```

From `bioviews.info`. files\[\] is autoloading for OO classes.

---
Tags: views
---


# Question
Title: Inputs for "am" and "pm" get messed up on the arabic side when editing content
When creating/editing a node on the english side all works ok but when this is done on the arabic side it breaks up the am/pm form. The markup values also change unlike on the month or hour fields. I think this causes the content to become invalid and it prevents the node from being saved.

I'm guessing this happens with other languages that might use different characters.

Can this be corrected?

EN

```
<select class="date-ampm form-select" id="edit-field-date-und-0-value-ampm" name="field_date[und][0][value][ampm]">
   <option value=""></option>
   <option value="am" selected="selected">am</option>
   <option value="pm">pm</option>
</select>

```

AR

```
<select class="date-ampm form-select" id="edit-field-date-und-0-value-ampm" name="field_date[und][0][value][ampm]">
   <option value=""></option>
   <option value="arabic_word_for_AM" selected="selected">arabic_word_for_AM</option>
   <option value="arabic_word_for_PM">arabic_word_for_PM</option>
</select>

```

Also posted this on drupal.org that allowed the actual arabic text. https://www.drupal.org/node/2291987

Thanks in advance for any helpful clue!

# Answer
The translation interface was translating both the value and the text on the select list. Had to change it back to latin characters and leave it as pm and am.

Unfortunately I wont be able to translate this on the node edit form but at least not the inputs don't break the form and I can save the nodes.
> 0 votes

---
Tags: i18n-l10n
---


# Question
Title: How can I achieve this functionality to allow url prefixes without hacking the core?
Lets say I have a site example.com with the following urls:

```
example.com
example.com/page1
example.com/about

```

This is an American site, but I also want an Australian version.

The urls for the Australian site will be:

```
example.com/au
example.com/au/page1
example.com/au/about

```

The homepage and `page1` are identical on both sites so the same content is served. However there is an Australian specific version of `about` so different content is served.

How can I map all of the `/au` pages to the ones without `/au` and somehow pass the fact that it is an AU page so I can determine what content to serve?

---

**Update:**

To clarify I want every single page that exists to be accessible via it's normal path alias, or the normal path alias prefixed with "au/".

I have managed to achieve this by editing bootstrap.inc in the following way:

A. Alter `request_path()`. After the line:

```
$path = substr(urldecode($request_path), $base_path_len + 1);

```

I added:

```
if(substr($path, 0, 3) == 'au/') {
  $path = substr($path, 3);
  $_SESSION['au'] = TRUE;
} else {
  $_SESSION['au'] = FALSE;
}

```

B. Alter `drupal_settings_initialize()`. After the `$base_path` has been set add:

```
if(isset($_SESSION['au']) && $_SESSION['au']) {
  $base_path = '/au/';
}

```

This means both `/page` and `/au/page` are treated in exactly the same way and I can use `$_SESSION['au']` in a node preprocessor hook to determine which content to serve.

Now my question is how can I achieve this behaviour **without hacking the core?**

# Answer
> 1 votes
Use i18n. It does this for you.

You have the possibility to choose how the content is served (from the module configuration page), between a subdomain for ex. "au.mysite.com/post-name" and prefixes like "mysite.com/au/post-name".

You will have a language field for your content-type, and you can easily set different content for different languages.

---
Tags: uri
---


title: Difference between Hook and function

text:
# Question
Title: Difference between Hook and function
I have a confusion regarding the hook and a normal function, So can any one tell me what is the significant difference between a Drupal hook and a normal PHP function in Drupal.

# Answer
This is a good question. To clarify it first, Hook **is** a function. But **it is a function that is named in such a way, that other modules and themes can override it with their own versions**.

**For example:**

1. Your module '*custom\_node*' has a function that adds information to the custom node. That function is called '*custom\_node*\_add\_data()'.
2. Soon after you release the module, you realize, that other people liked it, and they are asking you to implement a way for them to add their custom data to a custom node, from their custom modules, so that they dont have to hack yours.
3. So what do you do? You make your '*custom\_node*\_add\_data()' a hook. You name it '*hook*\_add\_data()', and then you add your own overrides in '*custom\_node*\_add\_data()'.
4. Under the hood, Drupal finds the declared hooks, and searched for functions in all code base that serve the hook formula, where the 'hook' is replaced by the module name.

Thus, profit! Custom modules can now override your hook function with their own code. They 'hook in' to what your module does, because now their hook function will be called.

Hooks allow to replace initial module's functionality with your own functionality in procedural code. In OOP code, like in Drupal 8, hooks are being replaced by subclassing and implementation of interfaces. Some hooks fill still remain in theming.
> 2 votes

---
Tags: 7, hooks
---


# Question
Title: Preferred way of adding new setting to all fields in a View?
I'd like to add a new setting to all fields in Views. In other words, when you click on any given field in the "Fields" list, you get a popup with the selected field's configuration options. I would like to add a new settings element here.

If this was just about adding a new setting to a specific custom field handler, then I would just create a new field handler class and have it extend `views_handler_field`. Then, I'd make my setting available by first defining it in `option_definition()` followed by adding a new form element in `options_form()`. However, I'd like the new setting to appear for **all fields regardless of field handler**.

What I've done so far is to simply provide an implementation of `hook_form_views_ui_config_item_form_submit()` to add the new setting. I'm adding my custom form element here as well as my own submit handler. In the submit handler I make sure to save the setting in `$form_state['handler']->options` in my submit handler.

However, is that the right way to go about it? Is there another way which Views facilitates and which would let me do things a little more clean so that I do not have to "mess" with the options array in my own submit handler, but rather have Views to actually know about my added universal field setting?

# Answer
> 0 votes
I wrote the module Views Label Tooltips based on my technique to achieve this, and here's a post explaining it: http://thereisamoduleforthat.com/content/recipe-extending-views-handlers-without-subclassing

---
Tags: 7, views, hooks
---


# Question
Title: How to set the link in a view slideshow?
Currently, I'm creating a xyz resort website. In my home page, I implemented a slideshow by using views. I want the slideshow to be clickable: When I click on to the resort image in slideshow it should go the respective resort description page.

Can anyone guide me on how to set the link in the view slideshow?

# Answer
You just need to make a little change in the slideshow view: Just link the image field to the content and save. Go to *Configure Field \> Link Image to \> Select Content*.

>
> 0 votes

---
Tags: 7, navigation, views
---


# Question
Title: How to add dynamic fields with condition?
I have a website that is about automobiles, I want when a user choose a brand drupal shows some of its models:

This image show an example:

for example I want when a user selected **BMW** drupal shows BMW's models in other **select tag** dynamic. and for example selected **Lamborghini** drupal shows Lamborghini's models.

**I mean a tree stystem**

# Answer
I would recommend you to use any one of following modules.

Hierarchical Select

> This module defines the "hierarchical\_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.

Simple hierarchical select

> Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy.

Taxonomy Term Reference Tree Widget

> This module provides an expandable tree widget for the Taxonomy Term Reference field in Drupal 7. This widget is intended to serve as a replacement for Drupal's core Taxonomy Term Reference widget, which is a flat list of radio buttons or checkboxes and not necessarily fit for medium to large taxonomy trees.
> 2 votes

# Answer
You can check the conditionnal fields module which is based on the States API if you want to do this hardcoded.

An other way to do this is by using hierarchical taxonomy and a module like Hierarchical Select even though you might be limited.
> 1 votes

---
Tags: nodes
---


title: Custom field not showing on edit form

text:
# Question
Title: Custom field not showing on edit form
I'm fairly new to drupal development and still trying to wrap my brain around the API. I run an athletic based website and need to be able to store race times using a mm:ss.00 format. I haven't seen any contributed modules that can do this, so I decided to create my own. I basically used an example field as my model and have gone through creating the field. When I activated the code, I can add the field to the content type. The field shows as an option when managing the display. However, the field doesn't show up when I edit the content type. I've gone through the code and compared it to others and I just can't figure out why. Below is the code for my module. Any ideas?

```
    /**
     * Implementation of hook_field_info().
     */
     function racetime_field_info() {
        return array(
             'racetime' => array(
                 'label' => t('Time'),
                 'description' => t('Time in format mm:ss.00'),
                 'settings' => array(),
                 'instance_settings' => array('number_decimals'=>2),
                 'default_widget' => 'racetime_default_widget',
                 'default_formatter' => 'racetime_default_formatter'
             )
         );
     }

     /**
        * Implements hook_field_instance_settings_form()
        */
     function racetime_field_instance_settings_form($field,$instance) {
         return array(
             'number_decimals' => array(
                 '#type' => 'textfield',
                 '#size' => 4,
                 '#title' => t('Number of decimals'),
                 '#default_value' => $instance['settings']['number_decimals'],
                 '#description' => t('The number of decimal places to use'),
             )
         );
     }

     /**
        * Implements hook_field_widget_info()
        */
     function racetime_field_widget_info() {
            return array(
                 'racetime_default_widget' => array(
                        'label' => t('Time Field'),
                        'field types' => array('racetime')
                 ),
            );
     }

     /**
        * Implements hook_field_is_empty()
        */
     function racetime_field_is_empty($item,$field) {
            if($item['value'] === '') {
                    return TRUE;
            }
            return FALSE;
     }

     /**
        * Implements hook_field_widget_form()
        */
     function racetime_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
            $value = isset($items[$delta]['value']) ? $items[$delta]['value'] : '';
            $numDecimals = $instance['settings']['number_decimals'];
            $widget = $element;
            $widget['#delta'] = $delta;

            $widget += array(
                 '#type' => 'textfield',
                 '#default_value' => $value,
                 '#size' => 8,
                 '#maxlength' => 15,
                 '#number_decimals' => $numDecimals,
                 '#value_callback' => '_racetime_widget_process_callback',
            );
            if (!isset($widget['description']) || !strlen($widget['description'])) {
                $widget['#description'] = t('Add description here');
            }
            if (!isset($widget['#process'])) {
                $widget['#process'] = array();
            }
            if (!in_array('_racetime_widget_process_callback', $widget['#process'])) {
                $widget['#process'][] = '_racetime_widget_process_callback';
            }

        $element['value'] = $widget;
        echo "<!-- \$element = " . print_r($element,true) . "-->\n";
        return $element;
     }

     /**
        * Implementation of hook_field_formatter_info
        */
     function racetime_field_formatter_info() {
            return array(
                 'racetime_default_formatter' => array(
                        'label' => t('Time'),
                        'field types' => array('racetime'),
                        'settings' => array(),
                        ),
                 );
     }

     /**
        *
        */
        function racetime_field_formatter_settings_form($field, $instance, $view_mode,$form, &$form_state) {
            $display = $instance['display'][$view_mode];
            $settings = $display['settings'];

            $element = array();

            if($display['type'] == 'racetime_default_formatter') {
                $element['number_decimals'] = array(
                    '#type' => 'textfield',
                    '#title' => t('Number of decimals'),
                    '#size' => 4,
                    '#description' => t('The number of decimals to use'),
                    '#default_value' => $settings['number_decimals'],
                    '#required' => TRUE,
                    );
            }
            return $element;
        }
     /**
        * Implements hook_help
        */
        function racetime_help($path, $arg) {
            switch ($path) {
                case "admin/help#racetime":
                    return '<p>' . t("A field for recording a race time in the format m:ss.00") . '</p>';
                    break;
            }
        }

        /**
         * Implements hook_field_formatter_view()
         */
        function racetime_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
            $element = array();

            if($display['type'] == 'racetime_default_formatter') {
                foreach($items as $delta => $item) {
                    $element[$delta]['#theme'] = 'racetime';
                    $element[$delta]['#value'] = $item['value'];
                    $element[$delta]['#number_decimals'] = $display['settings']['number_decimals'];
                }
            }

            return $element;
        }

        /**
         * Implements hook_theme()
         */
        function racetime_theme($existing, $type, $theme, $path) {
            return array(
                'racetime' => array(
                        'variables' => array('value' => '', 'number_decimals' => 2)
                )
            );
        }

        /**
         * Theme racetime
         */
         function theme_racetime($variables) {

             $classes = array();
                $html = '<span class="' . implode(' ',$classes) . '">';
                $html .= _racetime_integer_to_formatted($variables['value'],$variables['number_decimals']);
                $html .= '</span>';
                return $html;
         }
        /**
         * Function to convert a string to integer
         */
        function _racetime_string_to_int($str, $numDecimals = 2) {
            //valid formats could be 16:47.17 (minutes:seconds.hundredths)
            //or 1:53:45.35 (hours:minutes:seconds.hundredths)
            //$numDecimals is the number of decimal places to carry after the seconds

            //split the string by colons, first.
            $parts = explode(":", $str);

            $numParts = count($parts);
            $hours = 0;
            $minuts = 0;
            $seconds = 0;
            if($numParts == 3) {
                $hours = $parts[0];
                $minutes = $parts[1];
                $seconds = $parts[2];
            }
            elseif($numParts == 2) {
                $minutes = $parts[0];
                $seconds = $parts[1];
            }
            else {
                $seconds = $parts[0];
            }
            //convert hours and minutes to seconds
            $sec_hours = $hours * 3600;
            $sec_minutes = $minutes * 60;
            //add all together to get the total number of seconds
            $seconds = $sec_hours + $sec_minutes + $seconds;

            /**
             * now convert the seconds to an integer value
             * here we multiple seconds by 10 to the power of number of decimals.
             * if the user wants one decimal, we'd be expecting a value like
             * 1:54.3, in which case we'd have a seconds value of 114.3.  10^1 is 10,
             * and we'd be left with an integer of 1143.  For the default of two,
             * we would expect a value of 1:54.34, which would give us 114.34 * 10^2 or
             * 114.34 * 100 = 11434.
             */
            $seconds_int = $seconds * (10^$numDecimals);

            return $seconds;
        }
        /**
         * function to convert an integer value to a time
         */
        function _racetime_integer_to_formatted($seconds, $numDecimals=2) {
            //first convert the integer value to seconds
            $sec = $seconds / (10^$numDecimals);
            if($sec < 60) {
                return number_format($sec,$numDecimals);
            }
            else {
                $hours_str = '';
                //get number of minutes
                $minutes = floor($sec / 60);
                $seconds_str = $sec - ($minutes * 60);
                //if seconds is less then 10, then add a leading 0
                if($seconds_str < 10) { $seconds_str = 0 . number_format($seconds_str,$numDecimals); }
                //if the number of minutes is greater than 60, then convert
                //minutes to hours and minutes
                if($minutes > 60) {
                    $hours = floor($minutes / 60);
                    $minutes_str = $minutes - ($hours * 60);
                    if($minutes_str < 10) {
                        $minutes_str = 0 . $minutes_str;
                    }
                    $hours_str = $hours . ':';
                }
                else {
                        $minutes_str = $minutes;
                }
                $time_string = $hours_str . $minutes_str . ":" . $seconds_str;

                return $time_string;
            }
        }
        /**
         * Widget helper to present seconds as readable formatte string
         */
        function _racetime_widget_process_callback($element, $form_state) {
            if(!isset($element['#value'])) {
                $element['#value'] = '';
            }
            $element['#value'] = _racetime_integer_to_formatted($element['#value'],$element['#number_decimals']);
        }

```

**EDIT** It appears to have something to do with this line

```
 if (!in_array('_racetime_widget_process_callback', $widget['#process'])) {
     $widget['#process'][] = '_racetime_widget_process_callback';
 }

```

as soon as I commented it out, the form appears, even though the data doesn't get saved correctly.

# Answer
try to use this in the `hook_field_widget_form()`

```
'#default_value' => isset($items[$delta]) ? $items[$delta] : '',

```
> 0 votes

---
Tags: entities
---


# Question
Title: Overriding the view_handler_field_node_link_edit
I have created a view using custom content type with edit link.I have to write some php code for edit link.Can i override views\_handler\_field\_node\_link\_edit extends in my custom module?

```

    /**
     * Renders the link.
     */
    class views_handler_field_node_link_edit extends views_handler_field_node_link {
        function render_link($node, $values) {
        // Ensure user has access to edit this node.
            if (!node_access('update', $node)) {
                return;
            }

            $this->options['alter']['make_link'] = TRUE;
            $this->options['alter']['path'] = "node/$node->nid/edit";
            $this->options['alter']['query'] = drupal_get_destination();

            $text = !empty($this->options['text']) ? $this->options['text'] : t('edit');
            return $text;
        }

    }

```

# Answer
Maybe this post will help you out http://thereisamoduleforthat.com/content/recipe-extending-views-handlers-without-subclassing
> 0 votes

---
Tags: views
---


title: What's going wrong in my template file?

text:
# Question
Title: What's going wrong in my template file?
I'm displaying a user's messages in a view (which contains the messages' mid) and created a flag 'Unread' for them. (New messages are automatically flagged with a rule.) I'd now like to give the flagged ones a different background colour and tried editing the view's template file like this:

```
<?php if (!empty($title)): ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <?php $message = message_load($view->result[$id]->mid); ?>
  <?php $flag = flag_get_flag('unread'); ?>
  <div <?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
   <a class="inbox-message<?php if ($flag->is_flagged($message->mid)) {print " inbox-new";} ?>"
    <?php print $row; ?>
   </a>
  </div>
<?php endforeach; ?>

```

This works: flagged messages get the `inbox-new` class and I can theme them accordingly. Unfortunately, I'm also getting the error

```
Notice: Trying to get property of non-object in include() (line 8 of C:\wamp\www\MYSITE\sites\all\themes\MYTHEME\templates\views-view-unformatted--message.tpl.php).

```

What did I do wrong?

---

**Edit:** I've executed

```
$message = message_load(9);
$flag = flag_get_flag('unread');
if ($flag->is_flagged($message->mid)) {print ", inbox-new";}

```

with Devel and that works perfectly. I can debug `$message` and `$flag` via the template and use it elsewhere without any problems, so the problem can't be caused by being undefined.

# Answer
> 0 votes
I've changed line 8 to

```
<a class="inbox-message<?php if (is_object($message)) {if ($flag->is_flagged($message->mid)) {print " inbox-new";}} ?>"

```

and the error message vanishes magically. I've got no idea what caused this problem and why I had to solve it in this ugly way, so edits or comments with an explanation for this are welcome. Perhaps this is a bug in the Message module and I should report it on the drupal.org website.

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


title: How to create an Achive with views

text:
# Question
Title: How to create an Achive with views
I want to create an archive from my news with views and filter it by post date. How can I do it? Thank you

# Answer
There's a default view that comes with the Views module that will provide the block, it's called Archive and that'd be your best start point, enable it in `admin/structure/views` and you'll get both the block with the items grouped by date and a page.

Find an advanced customization of this in http://www.webbykat.com/2012/02/creating-monthly-archive-block-drupal-7-views
> 1 votes

# Answer
YOu just need to add a filter of post date/created date

To filter the content accorrding to the post date just tick the **Expose this filter to visitor**. You can see it is added above the listing under your view page.

If you want to display this form in the front end then set "**Exposed form in block**" under Advanced tab to "**Yes**". Now go to block listing page then assign it in the desired region.
> 0 votes

---
Tags: views
---


# Question
Title: How to add an editable text box to a page
So i have created a page which uses an XML feed to generate some output. I want to be able to add a textarea from the FORM API so that i can allow user of my site to enter some details on to the form itself.

Similar functionality to how entityform works, seemed like a simple task, but not sure how to do it.

# Answer
OK thought i would answer my own question and show the method in which this is done. First declare a block, with a block view and then define a custom callback function that defines the textarea, are any output from Drupal's Form API.

```
function hook_block_info() {
  $blocks['box_question'] = array(
    'info' => t('Box question area'),
  );
  return $blocks;
}

function hook_block_view($delta = '') {
  $block['subject'] = t('TEST');
  $block['content'] .= drupal_render(drupal_get_form('custom_block_form'));
  return $block;
}

function custom_block_form($form, &$form_state) {
  $form['question'] = array(
    '#markup' => 'this is a block,
  );
  $form['answer'] = array(
    '#type' => 'textarea',
    '#resizable' => FALSE,
    '#default_value' => $default,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#name' => 'save',
    '#attributes' => array(
      'class' => array('save-button'),
    ),
  );
  return $form;
}

```

The custom\_block\_form is what defines the form blocks, call the submit functions to make your own callback on what to do when the form is saved.
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Views Sort Criteria: Sort by Taxonomy terms
I have a view that lists team members of a country that are referenced by an Entity reference field.

Now these team members can have different functions and job titles. I assign them through a taxonomy vocabular called "Functions" with the following terms: \- Office Head \- Partner \- Client Partner \- Consultant \- etc.

Usually team members only have one function but the Office Head always has two (Office Head and e.g. Partner).

When I now choose the above taxonomy field as a sort criteria, the office head always appears twice since it has two taxonomy terms assigned. But I only want the office head to show up only once.

Any suggestions how to do this would be greatly appreciated.

# Answer
Check out Views Distinct module. Once you enable this module, for every field there will be a setting **Views Distinct Settings** where you can choose to **filter repeats**.
> 1 votes

---
Tags: views
---


title: Drupal Views Sorting problem

text:
# Question
Title: Drupal Views Sorting problem
I have a question on views sorting.

I have two content type(TypeA TypeB) which has the same field.

And i use views to list all the content with the sort i want.

Right now my problem is i want to sort my content with A1 A2 B1 B2 B3 B4 A3 A4 B5 B6 B7 B8...

with ratio 2:4 and in each type with another sorting rule like post date or update date ...

How can i do that?

Could somebody give me a suggestion?

Thx a lot

# Answer
Try using the Views Natural Sort module, it is an add on to views and provides a better sorting option than the build in views sort.

> Provides a views filter that sorts node titles by a more natural manner by ignoring articles like "The" and "A."
> 0 votes

---
Tags: views
---