# Question
Title: Allow user to filter View by Month only using a D/M/Y date field
I have a simple date (birthday) field in my View, and I have added that field as an exposed filter. I want to be able to filter by just the month, so that the View can return a list of users whose birthdays are in the month of July, for example. Currently, the exposed filter also requires that I choose a year, which makes the filter un-usable. How can I filer based on just the month and nothing else?

Thanks!

# Answer
I ended up discovering the Birthdays module (https://www.drupal.org/project/birthdays). It provides Views filters on the year, month, and day as separate filters. I simply had to export my existing date info as a CSV, parse the data out into separate columns to match the format of the birthdays database table, ad import that date into the birthdays database table.
> 0 votes

# Answer
You can use Computed field and create other field on your content type, there Month will stored (calculated as PHP code: `return date('m', {Date Field Value});`, so you can easily filter by months in Views by this field...
> 0 votes

# Answer
You can do this by following some steps

Add these steps to youe view-

Firstly add date field as an simple filter, then add same date field as an exposed filter, then add these lines to header of the view

```
<form method="get">
<select name="field_date_value">
<option value="01">Jan</option>
<option value="02">Feb</option>
<option value="03">March</option>
<option value="04">April</option>
<option value="05">May</option>
<option value="06">June</option>
<option value="07">July</option>
<option value="08">Aug</option>
<option value="09">Sep</option>
<option value="10">Oct</option>
<option value="11">Nov</option>
<option value="12">Dec</option>
</select>
<input type="submit" value="Apply">
</form>

```

After adding above steps save the view.

Now write below code to your activated theme template.php file

```
function hook_views_query_alter(&$view, &$query)
{
    if($view->name=='demo12') // in place of demo12 ,place your view name here
    {
        if(isset($_GET['field_date_value']))
        {
        $month=$_GET['field_date_value'];

        $query->where[1]['conditions'][2]['field']="DATE_FORMAT(ADDTIME(field_date_value
, SEC_TO_TIME(19800)),'%m') = :field_data_field_date_field_date_value";

        $query->where[1]['conditions'][2]['value'][':field_data_field_date_field_date_value']=$month;
        }
        else
        {
            $query->where[1]['conditions']=array();
            $query->where[1]['conditions'][0]['field']='node.status';
            $query->where[1]['conditions'][0]['value']='1';
            $query->where[1]['conditions'][0]['operator']='=';
            $query->where[1]['conditions'][1]['field']='node.type';
            $query->where[1]['conditions'][1]['value'][0]='demo';
            $query->where[1]['conditions'][1]['operator']='in';
        }
    }

}

```

like- my theme name is 'testing' so replace "hook\_views\_query\_alter(&$view, &$query)"

to "testing\_views\_query\_alter(&$view, &$query)" in template.php.

You have to change fields name in above code as 'field\_date\_value' in above code is my content type 'date field' machine name.so you have to change it. The above code is working in my view.

You can import the below given code of view to you site:-

======================================================================================

```
 $view = new view();
    $view-name = 'demo12';
    $view-description = '';
    $view-tag = 'default';
    $view-base_table = 'node';
    $view-human_name = 'demo12';
    $view-core = 7;
    $view-api_version = '3.0'

;
    $view-disabled = FALSE;  Edit this to true to make a default view disabled initially

 Display Master
$handler = $view-new_display('default', 'Master', 'default');
$handler-display-display_options['title'] = 'demo12';
$handler-display-display_options['use_more_always'] = FALSE;
$handler-display-display_options['access']['type'] = 'perm';
$handler-display-display_options['cache']['type'] = 'none';
$handler-display-display_options['query']['type'] = 'views_query';
$handler-display-display_options['exposed_form']['type'] = 'basic';
$handler-display-display_options['pager']['type'] = 'full';
$handler-display-display_options['pager']['options']['items_per_page'] = '10';
$handler-display-display_options['style_plugin'] = 'default';
$handler-display-display_options['row_plugin'] = 'fields';
 Header Global Text area
$handler-display-display_options['header']['area']['id'] = 'area';
$handler-display-display_options['header']['area']['table'] = 'views';
$handler-display-display_options['header']['area']['field'] = 'area';
$handler-display-display_options['header']['area']['empty'] = TRUE;
$handler-display-display_options['header']['area']['content'] = 'form method=get
select name=field_date_value
option value=01Janoption
option value=02Feboption
option value=03Marchoption
option value=04Apriloption
option value=05Mayoption
option value=06Juneoption
option value=07Julyoption
option value=08Augoption
option value=09Sepoption
option value=10Octoption
option value=11Novoption
option value=12Decoption
select
input type=submit value=Apply
form';
$handler-display-display_options['header']['area']['format'] = 'full_html';
 Field Content Title
$handler-display-display_options['fields']['title']['id'] = 'title';
$handler-display-display_options['fields']['title']['table'] = 'node';
$handler-display-display_options['fields']['title']['field'] = 'title';
$handler-display-display_options['fields']['title']['label'] = '';
$handler-display-display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler-display-display_options['fields']['title']['alter']['ellipsis'] = FALSE;
 Field Content Image
$handler-display-display_options['fields']['field_image']['id'] = 'field_image';
$handler-display-display_options['fields']['field_image']['table'] = 'field_data_field_image';
$handler-display-display_options['fields']['field_image']['field'] = 'field_image';
$handler-display-display_options['fields']['field_image']['click_sort_column'] = 'fid';
$handler-display-display_options['fields']['field_image']['settings'] = array(
  'image_style' = '',
  'image_link' = 'content',
);
 Field Global Custom text
$handler-display-display_options['fields']['nothing']['id'] = 'nothing';
$handler-display-display_options['fields']['nothing']['table'] = 'views';
$handler-display-display_options['fields']['nothing']['field'] = 'nothing';
$handler-display-display_options['fields']['nothing']['alter']['text'] = 'a class=colorbox-load href=httpwww.youtube.comwatchv=617ANIA5Rqs title= We Share Our Mother's HealthWatch Nowa';
 Field Content BirthDate
$handler-display-display_options['fields']['field_date']['id'] = 'field_date';
$handler-display-display_options['fields']['field_date']['table'] = 'field_data_field_date';
$handler-display-display_options['fields']['field_date']['field'] = 'field_date';
$handler-display-display_options['fields']['field_date']['settings'] = array(
  'format_type' = 'long',
  'fromto' = 'both',
  'multiple_number' = '',
  'multiple_from' = '',
  'multiple_to' = '',
);
 Sort criterion Content Post date
$handler-display-display_options['sorts']['created']['id'] = 'created';
$handler-display-display_options['sorts']['created']['table'] = 'node';
$handler-display-display_options['sorts']['created']['field'] = 'created';
$handler-display-display_options['sorts']['created']['order'] = 'DESC';
 Contextual filter Content BirthDate (field_date)
$handler-display-display_options['arguments']['field_date_value']['id'] = 'field_date_value';
$handler-display-display_options['arguments']['field_date_value']['table'] = 'field_data_field_date';
$handler-display-display_options['arguments']['field_date_value']['field'] = 'field_date_value';
$handler-display-display_options['arguments']['field_date_value']['default_argument_type'] = 'date';
$handler-display-display_options['arguments']['field_date_value']['summary']['number_of_records'] = '0';
$handler-display-display_options['arguments']['field_date_value']['summary']['format'] = 'default_summary';
$handler-display-display_options['arguments']['field_date_value']['summary_options']['items_per_page'] = '25';
 Filter criterion Content Published
$handler-display-display_options['filters']['status']['id'] = 'status';
$handler-display-display_options['filters']['status']['table'] = 'node';
$handler-display-display_options['filters']['status']['field'] = 'status';
$handler-display-display_options['filters']['status']['value'] = 1;
$handler-display-display_options['filters']['status']['group'] = 1;
$handler-display-display_options['filters']['status']['expose']['operator'] = FALSE;
 Filter criterion Content Type
$handler-display-display_options['filters']['type']['id'] = 'type';
$handler-display-display_options['filters']['type']['table'] = 'node';
$handler-display-display_options['filters']['type']['field'] = 'type';
$handler-display-display_options['filters']['type']['value'] = array(
  'demo' = 'demo',
);
 Filter criterion Content BirthDate (field_date)
$handler-display-display_options['filters']['field_date_value']['id'] = 'field_date_value';
$handler-display-display_options['filters']['field_date_value']['table'] = 'field_data_field_date';
$handler-display-display_options['filters']['field_date_value']['field'] = 'field_date_value';
$handler-display-display_options['filters']['field_date_value']['granularity'] = 'month';

 Display Page
$handler = $view-new_display('page', 'Page', 'page');
$handler-display-display_options['path'] = 'demo12';

```

===========================================================================================

You have to create content type with name 'demo' for it.Or have to change the name 'demo' with your content type name.

May this code will help you
> 0 votes

---
Tags: 7, views, datetime
---


# Question
Title: What is the proper way to drop database references for an uninstalled drupal module?
I've uninstalled the Commerce Coupon 7.x-2.0-beta3 through the admin ui and removed the corresponding folder from the sites/all/modules directory. Now when I install the previous version of Commerce Coupon 7.x-1.0-beta7 I get hit with the error.

```
DatabaseSchemaObjectExistsException:
 Table <em class="placeholder">commerce_coupon</em> already exists.

```

When I look at the Database in phpMyAdmin I see the the following references.

* commerce\_coupon
* commerce\_coupon\_type
* field\_data\_commerce\_coupon\_order\_reference
* field\_data\_commerce\_coupon\_reference
* field\_revision\_commerce\_coupon\_order\_reference
* field\_revision\_commerce\_coupon\_reference

I am not very familiar working with tables through SQL. Is there a basic procedure or query that is commonly used for deleting all references to a particular Drupal module?

# Answer
> 1 votes
There's no single procedure for manually removing a module, it kind of depends on what has been installed, where it's been installed and how it's been used.

For commerce coupon the basics are pretty simple:

* Remove `commerce_coupon` and `commerce_coupon_type`
* Remove the 4 field tables.
* `DELETE FROM field_config_instance WHERE field_name IN ('field_data_commerce_coupon_order_reference', 'field_data_commerce_coupon_reference')`
* `DELETE FROM field_config WHERE field_name IN ('field_data_commerce_coupon_order_reference', 'field_data_commerce_coupon_reference')`
* Flush the caches

From there it gets a bit trickier. Depending on how the module's been used you may have references to coupons in the `commerce_line_item` table, with relationships back to their order in `field_data_commerce_line_items` (and the corresponding revision table). Those should also be removed to prevent errors when line items are loaded.

As you mentioned in the comments there may also be related rules (and potentially views as well), hunting down and deleting those manually might be the easiest thing to do.

# Answer
> 1 votes
Using the help provided by @Clive this was the procedure that enabled me to install the Commerce Coupon modules that I wanted to use without error.

Clear all caches Run Cron

1. Select all cache tables in phpMyAdmin then go bottom of page and under "With selected" dropdown chose empty.
2. Use phpMyAdmin to search for "%commerce\_coupon%" then delete the found entries which in my case were:

* 1 match in commerce\_checkout\_pane
    * 1 match in commerce\_line\_item
    * 3 matches in field\_config
    * 14 matches in field\_config\_instance
    * 1 field\_data\_commerce\_coupon\_reference
    * 1 match in field\_data\_commerce\_order\_total
    * 1 match in field\_data\_commerce\_total
    * 1 match in field\_data\_commerce\_unit\_price
    * 1 match in field\_revision\_commerce\_coupon\_reference
    * 1 match in field\_revision\_commerce\_order\_total
    * 1 match in field\_revision\_commerce\_total
    * 1 match in field\_revision\_commerce\_unit\_price
    * 7 matches in system
    * 4 matches in variable
3. Drop the following tables if they exist

* commerce\_coupon
    * commerce\_coupon\_type
    * field\_data\_commerce\_coupon\_order\_reference
    * field\_data\_commerce\_coupon\_reference
    * field\_revision\_commerce\_coupon\_order\_reference
    * field\_revision\_commerce\_coupon\_reference
4. Install latest Commerce Coupon Dev version of 7.x-1 branch
5. Install Commerce Coupon Percentage
6. Install Commerce Coupon Fixed Amount

run update.php

---
Tags: 7, commerce, database, installation
---


# Question
Title: How to dislodge drupal from Apache and remove drupal
Excuse me please.. I am new to website development. I am using LAMP on fedora 20. I am also using bluefish to edit html/php.

As a shear experiment, I installed Commerce Kickstart on my system. I did some terrible mistakes and now I need to remove drupal completely from the system..

I was just thinking of deleting the files and dropping the database. but is it enough?

thanks in advance

# Answer
Yes, deleting the files and dropping the database should be enough.

If you made any changes to Apache (eg. creating a virtual host) and/or the operating system (eg. a line in the /etc/hosts file) you may want to revert that as well.

Don't worry about messing it up the first time, that's actually a great way to learn and get comfortable with any CMS (not just Drupal).
> 2 votes

---
Tags: installation
---


# Question
Title: Nest one content type in another to be able to add single fields
I would like to have one content type "Basic" and then another content type "Premium" that has a few extra fields than the basic one. The idea is that I want my users to pay for premium publications (using Commerce Node Checkout Module) if they want to use those extra fields. Basic content will always be free.

It is very likely that I will need to make changes to the basic content type fields that I want to also be reflected in the permium content type. Is there a way to kind of "subtheme" the content type so that it reflects the basic one whenever changes are made but still carries a few extra fields that are independend of these changes?

# Answer
That's quite a cool question...

I think If I were doing it, I would have the basic form available to all standard users of a standard permissions role...

Then when a customer has paid for the privilege to use more advanced fields, I set up a rule to promote their role to an advanced user role after checkout.

You can then use a module like Field Permissions to determine which fields your basic users can edit, and which fields your advanced users can edit.

And, you only need one content type.
> 2 votes

---
Tags: entities, commerce, nodes
---


# Question
Title: how to provide a content type variable to region--header.tpl.php
I want to hide some inline html from header for specific content type. How cud I provide a content type variable to region--header.tpl.php to put a php condition to hide the html?

# Answer
Try this... https://www.drupal.org/node/115419

```
<?php
  // Only show if $match is true
  $match = false;
  // Which node types
  $types = array('book', 'news', 'anothernodetype' );
  // Match current node type with array of types
  if (arg(0) == 'node' && is_numeric(arg(1))) {
    $nid = arg(1);
    $node = node_load(array('nid' => $nid));
    $type = $node->type;
    $match |= in_array($type, $types);
  }
  return $match;
?>

```
> 1 votes

---
Tags: theming
---


# Question
Title: Translating taxonomy list name for a custom link in rewrite result field
Very hard to describe this problem in a title. Let me explain:

I have a taxonomy list named 'Meubelen'. I translated the name to 'Meubles' for the French version of the website.

I created a view of the terms in this list (an overview of categories). An image of a representative node is shown for each term. I like te rewrite the output of this image to a link directing to the taxonomy page. I can do this for one language, like this:

```
 meubelen/[term-name]

```

But this should change to

```
 meubles/[term-name]

```

when visiting the French side of the website.

How can I achieve this? There's no translatable field for this view that I can add and use as variable.

# Answer
> 0 votes
> How can I achieve this? There's no translatable field for this view that I can add and use as variable.

Really?!? If you have a representative node of the category content (with the proper language set) you should be able to have a relationship to that nodes language settings, and also the url path to nodes' url path for say, French, in this case.

There's no token support to Rewrite the link in Views to the path with X language setting for the node? .... eg, under `Replacement Tokens` for the field there's no configurable token for like, `node:path:lang:YOUR-LANG` or something similar -- I typically dont do internation sites, but i'm 99% sure this type of flexability comes out of the box.

---
Tags: views, taxonomy-terms, i18n-l10n, uri
---


# Question
Title: How to redirect to another drupal site/alias after file upload
I use the drupal standard to upload files + File Entity. After uploading file eg this is the current URL: https://blabla.com/en/file/abc.pdf. I want to redirect the users to file/add.

Matroschker

# Answer
> 0 votes
You can add a custom submit handler onto your form and add a `$form['#redirect']` attribute to the target destination. There are many examples of form redirect questions on this site, and also examples for custom submit handlers for forms.

---
Tags: files
---


title: View per content type

text:
# Question
Title: View per content type
I'm using Drupal 7 and Views. I have 4 different content types and I want to be able to display each content type in separate view. What i did is I create a view and a page and i set the view Path to `node/%`

After that I'm using contextual filters to get specific node. It's working when I'm on view creator page and the preview.

I have 4 such views, each for particular content type.

When I save the view and I'm trying to load a page it takes wrong view and it gives no results found.

How to solve that issue and have multiple `node/%` pages? Is there something like views order or priority in loading? Shouldn't it have any filtration and pick the correct view based on content type?

Any tips will be appreciated:)

# Answer
> 1 votes
It won't work, if you give same path for different views/displays then it will load the view/display with the least id.

But why you want to give same path for all views?

# Answer
> 0 votes
You can use the Panels Module Once the module is installed you can override the Node View Page on `admin/structure/pages/edit/node_view`

You can create one variant for each of the content types and within that you can add the view that you are using.

# Answer
> 0 votes
I agree with @Gokul N K's answer. However if you are using blocks for the content on the pages and you need to change which blocks appear based on what type of content you are viewing, you can go into each block and under Visibility Settings \> Content Types select the content types that you want that particular block to show on. Or better yet look into using the Context Module

---
Tags: views, nodes
---


# Question
Title: Recommendation for hosting Git VCS from my drupal installation
Our community does a lot of coding work (lua, c#, php, etc) and we are looking to move away from the usual repo hosts (BitBucket/GitHub/Jenkins) and make our website more of an all-in-one experience. I've been trying to find guides for hosting a git repo and browser from a drupal installation, but all I can seem to find is installing/updating drupal with git. Are there any modules for hosting a personal git repo?

# Answer
> 1 votes
Look at Case Tracker for project SCM hosting from Drupal:

> Case Tracker enables teams to track outstanding cases which need resolution. This module was inspired by the issue handling in project module, but unlike Project module, which is specific to software development, Case Tracker was designed to be a generic issue tracker.
>
> Case Tracker is usable right out of the box as a basic ticketing system, it's default UI is minimal but feature complete. The module was designed to be extended by programmers and site builders to meet complex needs, and so tries to avoid making too many assumptions about all the ways it can be used.
>
> Drupal 7
>
> 7.x-2.x - it is an Entity based approach(#1653184: Case Tracker 7.x-2.x - a new approach, with entities) and is on heavy development. As it's based on Entity API, it has a deeper integration with Views, Rules, Message and a lot of other modules natively. 7.x-1.x - has the content types for Project and Cases working without problems. The Notifications, Actions and View integration that needs to be tested.

This module is D6 specific but look at Case Tracker Commits as well.

See also Project which powers Drupal.org itself, and the modules it uses such as Versioncontrol Project and its dependant modules.

---
Tags: 7, drush, version-control
---


# Question
Title: where to find default view code in user relationships module in drupal 7?
I have installed user relationship module. Which gives me default views to display the list of friends, received requests and sent requests. I want to show a message to the user about the number of requests he/she has received as we see in facebook. But I am not getting the view's machine name, display name to take a count of requests received as I am not getting which is the view for requests received. Where Can I find it?

# Answer
Under User Relationship module there will be a folder called `user_relationship_views` inside that you can find the default view `user_relationship_views.views-default.inc` file
> 0 votes

---
Tags: views, users
---


# Question
Title: How to show only the comment form, not the comments
Right now in Drupal, at the end of each article, there are the comments which users has put on that article and also the comment form. I just want to have the comment form at the end of each article, I do not want the comments be shown at the end of each article. Does any body know how can I do it?

# Answer
> 1 votes
Implement `hook_node_view()` and check for `$node->type == 'article'` and `$view_mode=='full'` then unset the comments as follows

```
unset($node->content['comments']['comments']);

```

---
Tags: comments
---


# Question
Title: How can I tell what is causing commerce to throw entity wrapper exception errors?
I'm attempting to repair and reconfigure a site that was created by another admin. I ran across some issues with commerce coupon that I've been able to get past with help I received here first then here (referenced for insight into the current error).

When I enter edit mode for the "Commerce Coupon Review Pane" view, I get the same ajax error message as before but now with currency\_code:

```
An AJAX HTTP error occurred.
HTTP Result Code: 500
Debugging information follows.
Path: /admin/structure/views/view/commerce_coupon_review_pane/preview/checkout/ajax
StatusText: Service unavailable (with message)
ResponseText: EntityMetadataWrapperException:
Unable to get the data property currency_code as the parent data structure is not set.
in EntityStructureWrapper->getPropertyValue()

```

I'm also redirected to an error page with same exception when I click on the checkout button.

I don't think its a bug due to the way that this issue cleared up in the previously referenced issues. It seems more likely something happened to the data. It would also seem that getting help from the issue queues would be unlikely because it would be impossible for me to come up with steps to reproduce the error. Unfortunately I don't know how to attack the problem. However, I suspect that when the page tries to load, somewhere along the way, it fails to find data it expects to find. If this is too general of a problem what steps can I take to find out more precisely what is happening?

===============

**Update:** Thank you for the responses @pcambra, @tenken and @Clive. It appears that there is a broken relationship. I am missing these settings in the Commerce Coupon Review Pane:

```
"FIELDS"

 (Commerce Order referencing Commerce Coupon) Commerce Order: Order ID

"CONTEXTUAL FILTERS"

 (Commerce Order referencing Commerce Coupon) Commerce Order: Order ID

"RELATIONSHIPS"

 Entity Reference: Referencing entity

```

When I try to add them into the view, there is no option to select them.

Also, when I try to load /admin/commerce/orders/carts/ I get the same error but it does not specify a field.

Where is this relationship made and how do I now fix the relationship so they show up in the configuration dialog?

===============

**Update:**

Following instruction I am now getting these errors. Although this is progress, I turned up nothing useful on restoring broken handlers that was not specific to a particular module.

```
//when I click on add under FIELDS in the view this error is produced
Notice: Undefined index: base in get_base_tables()
(line 717 of view.inc).

//otherwise these errors are produced each time I try to enter the view
Missing handler: commerce_coupon
reverse_commerce_coupon_order_reference_commerce_order relationship

Notice: Undefined property: views_handler_relationship_broken::$alias
in get_result_entities() (line 1604 of views_plugin_query_default.inc).

```

# Answer
sounds to me like the rules the old developer put in place are still firing for coupons and since you *tried* to downgrade from 2.x to 1.x they're firing and its killing your page ........ look for rules that might be lingering about??

More debugging can be found by installing devel, finding this path in the sourcecode of commerce\_coupon `/admin/structure/views/view/commerce_coupon_review_pane/preview/checkout/ajax` and using dd() on func\_get\_args() throughout that pages' page callback function to debug where php is trying to get `currency_code`.

In general installing and hitting the page with xdebug debugger, and stepping through the code, could be very helpful too -- learn how to set some breakpoints in the debugger.
> 1 votes

# Answer
An error 500 is logged by the webserver, so the first thing I'd do is to check the logs there to get more information about this. Another super useful module to try here is Commerce Devel, it raises the debug log for the annoying EntityMetadataWrapperException error. It will show you a trace of what's happening.

If this is happening at the views level, I'm guessing it should be one of the data additions that coupon does: http://cgit.drupalcode.org/commerce\_coupon/tree/includes/views/commerce\_coupon.views.inc most probably this one http://cgit.drupalcode.org/commerce\_coupon/tree/includes/views/handlers/commerce\_coupon\_handler\_field\_coupon\_granted\_amount.inc and related with the module you're using for your coupons, percentage, or fixed amount.
> 1 votes

---
Tags: database, commerce
---


# Question
Title: Programmatically remove exposed filter in a view
I would like to remove a certain exposed filter on the **taxonomy term** view when certain conditions in the URL are met.

For example, I want to remove the "**Color**" exposed filter when the user is seeing the **/color/red** taxonomy term page, leaving only the "**Shape**" filter available.

Or remove the "**Shape**" exposed filter on the **/shape/square** page, leaving only the "**Color**" one.

The only code I could come up with is this, which is ugly and doesn't even work.

```
function hook_views_pre_render(&$view){
      if( CONDITIONS_ARE_MET ) {
         unset($view->filter['field_color_tid']);
         unset($view->exposed_data['field_color_tid']);
         unset($view->exposed_raw_input['field_color_tid']);
      }
}

```

Any ideas?

---

**UPDATE**

This is the code in mmo\_views\_alters:

```
function mmo_views_alters_views_pre_build(&$view){
    //dpm($view);
    unset($view->filter['field_tipologia_tid']);
}

```

This is the exported view: http://pastebin.com/JrYDmtZQ

It has **4 filters, and 3 of them are exposed**. I'm using **BEF** for displaying them, which generated another warning (*undefined index filter-field\_tipologia\_tid*) that I solved by patching **better\_exposed\_filters\_exposed\_form\_plugin.inc**, line 896:

```
if( isset($form['#info']["filter-$label"]['value']) )
        $field_id = $form['#info']["filter-$label"]['value'];
else continue;

```

The warnings that I'm not able to solve are:

> Notice: Undefined index: field\_tipologia\_tid in views\_handler\_filter\_term\_node\_tid-\>exposed\_validate() (linea 258 di /var/www/drupal/sites/all/modules/views/modules/taxonomy/views\_handler\_filter\_term\_node\_tid.inc).
>
> Notice: Undefined index: field\_tipologia\_tid in views\_handler\_filter\_term\_node\_tid-\>exposed\_validate() (linea 259 di /var/www/drupal/sites/all/modules/views/modules/taxonomy/views\_handler\_filter\_term\_node\_tid.inc).

They appear even with BEF disabled.

# Answer
> 2 votes
Implement `hook_views_pre_build()` and unset using `unset($view->filter['field_color_tid']);`

Else, you can also try altering the exposed form in `hook_form_alter()` using the code `$form['field_tipologia_tid']['#access']=FALSE;`

---
Tags: views
---


# Question
Title: What hook to use changing image field description
I wonder how I can alter the description of the custom image field. I can't use hook\_form\_alter. I couldn't find the variable. Please advise. Thanks!

e.g

# Answer
> 6 votes
The alternate text field is added by image\_field\_widget\_process(), which is the process element function added by image\_field\_widget\_form() (an implementation of hook\_field\_widget\_form()). To alter it, you can add your element process function with hook\_field\_widget\_form\_alter().

```
function mymodule_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($context['field']['type'] == 'image' && $context['instance']['widget']['type'] == 'image_image' && !empty($context['instance']['settings']['alt_field'])) {
    foreach (element_children($element) as $delta) {
      $element[$delta]['#process'][] = 'mymodule_field_widget_process';
    }
  }
}

function mymodule_field_widget_process($element, &$form_state, $form) {
  // Verify the element is accessible to the currently logged-in user.
  // Differently, it will not be visible to the user, and it is useless to alter the description, or the title.
  if ($element['alt']['#access']) {
    // Use $element['alt']['#title'] for the title.
    // Use $element['alt']['#description'] for the description.
  }

  return $element;
}

```

The reason I would use `hook_field_widget_form_alter()` instead of `hook_form_alter()` is that the first has direct access to some information the latter doesn't get, such as the settings for the field instance, and the field settings. In this case, I can access `$context['instance']['settings']['alt_field']` to check if the field requires the alternate text field.

If you are going to use `hook_form_alter()`, remember that:

* A field could have more than one widget, if the user is allowed to enter multiple values.
* When its #access property is set to `FALSE`, a form element is not accessible to the currently logged-in user; in that case, it is useless to change any other properties for the form element, as it will not be shown to the user.

# Answer
> 3 votes
That text is added by

image\_field\_widget\_process

You can alter it using form\_alter to add your own process callback to the element.

See also

image\_field\_widget\_form for some additional info, e.g the process callback added by `$elements[$delta]['#process'][] = 'image_field_widget_process';`

Alternatively, a module solution is to use

stringoverrides

and translate the text via the admin user interface.

# Answer
> 0 votes
Although @kiamlaluno's answer comes close, it's returning a blank image field for me. Here's a modified solution that worked.

```
// Alter image field Alt Title & Description
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  // Replace field_MYFIELD with your field name
  if ($context['field']['field_name'] == 'field_MYFIELD') {
    // Loop through the element children
    foreach (element_children($element) as $key => $child) {
      // Add the new process function to the element
      $element[$key]['#process'][] = 'MYMODULE_image_field_widget_process';
    }
  }
}

function MYMODULE_image_field_widget_process($element, &$form_state, $form) {
  // Change the title field label and description
  $element['alt']['#title'] = 'Effect';
  $element['alt']['#description'] = '{effect options}';

  // Return the altered element
  return $element;
}

```

Answer is inspired by a duplicate question asked on StackOverflow.

---
Tags: theming
---


title: Drupal and event on bootstrap modal

text:
# Question
Title: Drupal and event on bootstrap modal
I have a following problem.

I have a bootstrap modal with a form which I submit using jQuery. Upon sussesful Ajax I hide the form in the modal and append a message.

Now, when I close the modal and open it again I would like to have an empty form. Instead obviously I see the message. So I thought that I will use the bootstrap 'hidden.bs.modal' event to trigger the reoval of the message, showing the form and resetting it. The problem is that the event listener is never attached to the modal:

```
  Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {
  //code starts
  $('#feedback-form').submit(function(e) {

    $('#feedback-form').hide().parent().append('<div id="loader" class="well well-lg" style="text-align:center"><h3 class="alert alert-info">Please wait ...</h3></div>');
    $.post("email_us.php",form.serialize(), function(data){
        $('#loader').replaceWith('<div id="loader1" class="well well-lg" style="text-align:center"><h3 class="alert alert-success">'+data+'</h3></div>');
        $('#feedbackModal').on('hidden.bs.modal', function (e) {
                        $('#loader1').remove();
                        $('#feedback-form').show().trigger('reset');
                    });
        });
    e.preventDefault();
    })
  }
}

```

I do not see any error in the console it simply seems that the 'hidden.bs.modal' event listener is not attached to the modal.

Interestingly. If I execute this part of th code in console:

```
$('#feedbackModal').on('hidden.bs.modal', function (e) {
                    $('#loader1').remove();
                    $('#feedback-form').show().trigger('reset');
});

```

and then

```
$('#feedbackModal').trigger('hidden.bs.modal')

```

the modal and form behave as intended.

Any has an idea how to solve this problem?

# Answer
This isn't exactly a Drupal question :)

Why not simply clear the form data as soon as you get to the AJAX success point?

```
Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {
    //code starts
    $('#feedback-form').submit(function(e) {
      $('#feedback-form').hide().parent().append('<div id="loader" class="well well-lg" style="text-align:center"><h3 class="alert alert-info">Please wait ...</h3></div>');
      $.post("email_us.php",form.serialize(), function(data){
        $('#loader').replaceWith('<div id="loader1" class="well well-lg" style="text-align:center"><h3 class="alert alert-success">'+data+'</h3></div>');
        $('#feedback-form').trigger('reset');
      });
      e.preventDefault();
  })
}

```

As far as I can see, if you modify the code like this, it will:

* hide the form in preparation to post (no change)
* post, and wait for success (no change)
* show the success message (no change)
* clear the form immediately (modified)

Does this solve the problem, or have I misinterpreted what you need in a big way?

---

To answer the specific question, it's not clear to me what the problem might be, but I'm suspicious that it's caused by the `on` event handler being attached inside the `$post` function's `success` function. Maybe try moving it outside as shown below:

```
Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {
    //code starts
    $('#feedbackModal').on('hidden.bs.modal', function (e) {
      $('#loader1').remove();
      $('#feedback-form').show().trigger('reset');
    });
    $('#feedback-form').submit(function(e) {
      $('#feedback-form').hide().parent().append('<div id="loader" class="well well-lg" style="text-align:center"><h3 class="alert alert-info">Please wait ...</h3></div>');
      $.post("email_us.php",form.serialize(), function(data){
        $('#loader').replaceWith('<div id="loader1" class="well well-lg" style="text-align:center"><h3 class="alert alert-success">'+data+'</h3></div>');
      });
      e.preventDefault();
    })
  }
}

```
> 3 votes

---
Tags: javascript, ajax
---


# Question
Title: Allow user to flag only those node that associated to a particular term of a vocabulary?
I have content type "product" term referenced by Taxonomy "Product category" having terms -Cook tops -Heaters -Chimneys

Now if i flagged nodes associated with term "Cook tops" , after that if i flag node associated with "Heater". I should get a error message.

Actually I am using this flag to show flagged item in BASKET(as done in many shopping site). But i do not want to put a "Cook tops" node with "Heater" nodes.

# Answer
Found these links which solved my question https://www.drupal.org/node/2235353 https://www.drupal.org/node/952114
> 0 votes

---
Tags: flags
---


title: Single Bulk Operation on several blocks

text:
# Question
Title: Single Bulk Operation on several blocks
I would like to display on a single page several blocks generated by views and associate the same bulk operation to all of them so that the user only needs to click execute once.

Where would you start to achieve this ?

All ideas welcome.

# Answer
If you have a specific list of blocks you want to alter, get their deltas and invoke hook\_block\_view\_alter in a custom module, as follows:

```
function YOURMODULE_block_view_alter(&$data, $block) {
  switch($block->delta) {
     case 'delta1':
     ...
     case 'deltaN':
       // alter the block in the required way by modifying the $data array
       break;
  }
 }

```

If you want to alter ALL blocks created by a particular module, say, views, do a switch on `$block->module`, instead, i.e.:

```
function YOURMODULE_block_view_alter(&$data, $block) {
      switch($block->module) {
         case 'views':
         case 'SomeOtherModule':
           // alter the block in the required way by modifying the $data array
           break;
      }
}

```

Bear in mind that hook\_block\_view\_alter is called for ALL blocks, so if your site has lots of blocks, this may be a performance hit.
> 0 votes

---
Tags: blocks, views
---


# Question
Title: Google map in jQuery UI tabs / Drupal behaviors.js
As you can see here the google map in the first jQuery ui tab loads correctly but the same map in second / third etc tabs does not load properly or loads off centre.

As mentioned here the problem is that "Any component that requires some dimensional computation for its initialization won't work in a hidden tab, because the tab panel itself is hidden via display: none so that any elements inside won't report their actual width and height (0 in most browsers)."

I have read for example here that the problem is that the map loads after the jQuery UI tabs and so I need a jQuery snippet in my (Drupal 7) theme's behaviors.js to to make the map load before the jQuery UI tabs.

(Please note that the alternative solution of applying CSS to .ui-tabs .ui-tabs-hide will not work for me because it causes problems elsewhere.)

Can anyone please tell me the code I need for my-theme.behaviors.js ?

my template.php =

```
<?php
function whitecross_160614_preprocess_html(&$variables){
// some comment here
    drupal_add_library('system', 'ui.tabs');
    drupal_add_js('jQuery(document).ready(function(){
                jQuery("#tabs-x, #tabs-y").tabs({event: "click"});
                jQuery("#tabs-x, #tabs-y").tabs().addClass("ui-tabs-vertical ui-helper-clearfix");
                jQuery("#tabs-x li, #tabs-y li").removeClass("ui-corner-top").addClass("ui-corner-left");
            });',
        'inline');
}

```

HTML =

```
<div id="jqueryui-tabs-wrapper">
<div id="tabs-x">
<div id="tab-list">
<ul>
<li><a href="#tabs-1">Map 1</a></li>
<li><a href="#tabs-2">Map 2</a></li>
<li><a href="#tabs-3">Map 3</a></li>
</ul>
</div>  <!--end tab list-->

<div id="tab-content">
<div id="tabs-1">
<iframe src="<a href="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d2483.645966939501!2d-0.14189000000000002!3d51.501364!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0xa26abf514d902a7!2sBuckingham+Palace!5e0!3m2!1sen!2suk!4v1403805298071"">https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d2483.645966939501!2...</a> width="800" height="600" frameborder="0" style="border:0"></iframe>
</div>  <!--end tab 1-->

<div id="tabs-2">
<iframe src="<a href="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d2483.645966939501!2d-0.14189000000000002!3d51.501364!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0xa26abf514d902a7!2sBuckingham+Palace!5e0!3m2!1sen!2suk!4v1403805298071"">https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d2483.645966939501!2...</a> width="800" height="600" frameborder="0" style="border:0"></iframe>
</div> <!--end tab 2-->

<div id="tabs-3">
<iframe src="<a href="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d2483.645966939501!2d-0.14189000000000002!3d51.501364!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0xa26abf514d902a7!2sBuckingham+Palace!5e0!3m2!1sen!2suk!4v1403805298071"">https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d2483.645966939501!2...</a> width="800" height="600" frameborder="0" style="border:0"></iframe>
</div> <!--end tab 3-->

</div> <!--end tab-content -->
</div> <!--end div tabs-x-->
</div> <!--end jqueryui-tabs-wrapper-->

```

# Answer
> 0 votes
Further to the comments, here is a jsfiddle of what I was talking about. This is a quick example, but should be easily adapted to your own code. I altered the dimensions on the maps to show the change

CSS:

```
#toolbar
{
    width:100%;
    height:20px;
    background:#000;
}

#toolbar li
{
    display:inline-block;
    min-width:100px;
    background:#fff;
    color:#000;
    border:1px solid #ffff00;
    cursor:pointer;
}

#maps
{
    position:relative;
    width:800px;
    height:600px;
    overflow:hidden;
}

#maps #tabs-1,
#maps #tabs-2,
#maps #tabs-3
{
    position:absolute;
    top:0;
    left:0;
    width:800px;
    height:600px;
}

#maps #tabs-2,
#maps #tabs-3
{
    opacity:0;
}

```

HTML:

```
    <div id="toolbar">
        <li id="toolbar_tabs1">Map 1</li>
        <li id="toolbar_tabs2">Map 2</li>
        <li id="toolbar_tabs3">Map 3</li>
    </div>

    <div id="maps">
        <div id="tabs-1">
<iframe src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d2483.645966939501!2d-0.14189000000000002!3d51.501364!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0xa26abf514d902a7!2sBuckingham+Palace!5e0!3m2!1sen!2suk!4v1403805298071" width="800" height="600" frameborder="0" style="border:0"></iframe>
</div>  <!--end tab 1-->

<div id="tabs-2">
<iframe src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d2483.645966939501!2d-0.14189000000000002!3d51.501364!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0xa26abf514d902a7!2sBuckingham+Palace!5e0!3m2!1sen!2suk!4v1403805298071" width="700" height="500" frameborder="0" style="border:0"></iframe>
</div> <!--end tab 2-->

<div id="tabs-3">
<iframe src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d2483.645966939501!2d-0.14189000000000002!3d51.501364!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0xa26abf514d902a7!2sBuckingham+Palace!5e0!3m2!1sen!2suk!4v1403805298071" width="600" height="400" frameborder="0" style="border:0"></iframe>
</div> <!--end tab 3-->

</div>

```

JS:

```
jQuery('#toolbar_tabs1').click(function(){
    jQuery('#tabs-1').animate({'opacity':1}, 200);
    jQuery('#tabs-2').animate({'opacity':0}, 200);
    jQuery('#tabs-3').animate({'opacity':0}, 200);
});

jQuery('#toolbar_tabs2').click(function(){
    jQuery('#tabs-1').animate({'opacity':0}, 200);
    jQuery('#tabs-2').animate({'opacity':1}, 200);
    jQuery('#tabs-3').animate({'opacity':0}, 200);
});

jQuery('#toolbar_tabs3').click(function(){
    jQuery('#tabs-1').animate({'opacity':0}, 200);
    jQuery('#tabs-2').animate({'opacity':0}, 200);
    jQuery('#tabs-3').animate({'opacity':1}, 200);
});

```

---
Tags: javascript
---


# Question
Title: Drupal Time field for hour:minute:second.tenth of a second
Is there a drupal field type to represent time for athletics sports events. e.g. for 100m sprint: 10.42 seconds but for 800m 1:40.89 (1 minute, 40.89 seconds) In the format : hour:minute:second.tenth of a second

# Answer
No time field will give you what you are looking for. They all work with Unix time, which is defined as 'the number of seconds since midnight, January 1, 1970'. The maximum granularity you will see is one second.

If you wish to record this information to one one-hundredth of a second, you will need to define the field and its formatting yourself.
> 1 votes

# Answer
Not sure if this module does what you need. But http://drupal.org/project/cck\_time may work if it allows you to create a format using PHP. There is also
> 0 votes

# Answer
Checkout this module HMS Field

> Displays a integer formatted as Hours, Minutes or Seconds. The field stores values as integer. Both input and output can be formatted as Hours, Minutes and/or Seconds. Alter functions provides developers a way to add their own format.
> -1 votes

# Answer
This is currently being developed too: https://www.drupal.org/project/timeperiod
> -1 votes

---
Tags: entities, datetime
---


# Question
Title: Grant permission to post a new node of content-type 2 if previous node of his content-type 1 has a state of approved
I'm using the Workflow module for an article submission contest website.

I have two roles:

1. Referee
2. Participant

The whole workflow is the following.

* Participant users log in, submit their summary article
* System sends a confirmation e-mail to the participant users
* Referee users log in, check the submission, and approve/deny the submission
* System sends another e-mail letting the participant know the result
* When approved, participant users may send their article
* Referee users check the new submission, approve/deny and publish
* System sends a congratulation e-mail

The part that got me hooked with the Rules module is implementing this point.

* When the referee users approve the *Summary Article* node via the Workflow module, it gives the participant permission to create a new *Full Article* node

I'd really appreciate any hint.

# Answer
> 1 votes
You can create two `Roles`.

1. Role 1 -\> has permission to create summary (content type 1)
2. Role 2 -\> has permission to create full article (content type 2)

you can assign `Role 1` to users by default.

Next you create a rule like

> Event : Summary gets approved
> Action : Add user role

The way you create the rule depends on whether you are using `Workflow Node` or `Workflow field`

If you are using **Workflow Node** then the rule will be

> Event : Workflow state has changed
> Condition : Check the state

If you are using **Workflow Field** then the rule will be

> Event : After updating existing node
> Condition : Do a data comparison for the workflow field with the state ID.

Action will be **Add user role**, that is **Role 2**

---
Tags: rules, workflows
---


# Question
Title: Voting Api + Vote Up / Down = Vote Power
I have installed VotingApi with Vote Up/Down, also have my own module which implements user exp and levels. I want the voted to be more powerful if the user has greater level. I search through Vote Up/Down files but didnt find a file inserting the vote to databse, so I could change it depending on my needs.

# Answer
> 0 votes
The vote will be casted by calling the **Voting api** function `votingapi_set_votes()`. But if you want to change the votes before sending it to `Voting api` there is hook for this called `hook_vud_votes(&$votes)` which you can use.

**Update:** The api file mentions a hook called `hook_vud_votes(&$votes)` to alter the vote but in their code they are invoking the hook using `drupal_alter()`, so the right hook to implement is `hook_vud_votes_alter(&$votes)`, I think it is mistake in their api doc.

---
Tags: rating
---


# Question
Title: Is there any way to create validation function in system_settings_form
Creating a form having two file type element, i want to check that if user uploaded file any file, then user must upload both file, so is there any way to add a validate function in system\_settings\_form.

# Answer
> 3 votes
The `system_settings_form` should be used to set simple variables for your module, see the approved answer and related comment here:

Is "system\_settings\_form" voodoo?

If you want to be sure both form fields are filled out during submission you don't need a validate function -- you can set both fields as being required when you create your form array:

```
$form['SOMETHING']['#required'] = TRUE;

```

where *something* is your form field key.

If you have complex logic and your form isn't simply setting a configuration variable you will call with `variable_get` or `variable_set` later -- then implement a custom `form_validate` and `form_submit` function for your form as your form is not simply a variable settings form.

See the Form API Handbook. Also of use is this drupal `$form` lifecycle or workflow illustration. Lastly form validation helpers and submit handlers are touched on briefly on this page of the handbook.

**EDIT:**

Just to complete my answer, hook\_form\_alter can change many aspects of a form used by drupal.

**EDIT 2:**

You can add a custom validator on the form you use to build `return system_settings_form($form);` for an example see the Commerce Admin include file here: http://cgit.drupalcode.org/commerce/tree/includes/commerce\_ui.admin.inc

They set:

```
$form['#validate'][] = 'commerce_currency_settings_form_validate';

```

in their form builder function then they provide a validation function:

```
/**
 * Form validate handler for the currency settings form.
 */
function commerce_currency_settings_form_validate($form, &$form_state) {
  // Ensure the default currency is always enabled.
  $default = $form_state['values']['commerce_default_currency'];
  $form_state['values']['commerce_enabled_currencies'][$default] = $default;
}

```

---
Tags: 7, forms
---


title: User tabs and actions

text:
# Question
Title: User tabs and actions
I have a custom module and in `hook_menu` have defined the items below.

I have created a new user tab below:

```
$items["user/%user/TAB"] = array(
    "title"             => t("TAB"),
    "page callback"     => "FUNCTION1",
    "page arguments"    => array(1),
    "type"              => MENU_LOCAL_TASK,
);

```

and several actions (showing 2 below):

```
$items["user/%user/TAB/ACTION"] = array(
    "title"             => t("ACTION"),
    "page callback"     => "FUNCTION1",
    "page arguments"    => array(1),
    "type"              => MENU_LOCAL_ACTION,
);

$items["user/%user/TAB/ACTION2"] = array(
    "title"             => t("ACTION2"),
    "page callback"     => "FUNCTION2",
    "page arguments"    => array(1),
    "type"              => MENU_LOCAL_ACTION,
);

```

New tab shows and when I click on it, I get my action links as expected. But when I click on an action, I lose the tabs! The breadcrumb is accurate but no tabs.

How do I keep the user tabs?

# Answer
I feel stupid that it took me so long to try this:

```
$items["user/%user/TAB/ACTION"] = array(
    "title"             => t("ACTION"),
    "page callback"     => "FUNCTION1",
    "page arguments"    => array(1),
    "type"              => MENU_DEFAULT_LOCAL_TASK,
);

$items["user/%user/TAB/ACTION2"] = array(
    "title"             => t("ACTION2"),
    "page callback"     => "FUNCTION2",
    "page arguments"    => array(1),
    "type"              => MENU_LOCAL_TASK,
);

```
> 0 votes

---
Tags: hooks, routes
---


# Question
Title: How to set the property $label_hidden to be true
In the `field.tpl.php` the following code:

```
<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>: </div>
  <?php endif; ?>

```

The code is printing the label of the field. I want to set, conditionally, `$label_hidden = false` from more general place other than the `field.tpl.php` itself.

I tried the following snippet from template.php:

```
function my_foundation_preprocess_field(&$variables){
  print_r($variables);
}

```

To get the value I mean but all I found is `[#label_display] => hidden` as an array element. In addition, the form I meant with is not found in that array, the search form.

So I need a way to set $label\_hidden = true to prevent the Search label of the search text box.

# Answer
Forms are handled differently than the variables, like node content, etc. You can find information on customising the Search form here. A common method for hiding the label is to use CSS and simply make it display:none. It's exact nomenclature will depend on how exactly you have implemented the search form.
> 0 votes

---
Tags: 7, theming, search
---


# Question
Title: Backup & Migrate not working because of perrmission settings? what should they be?
I'm unable to use the Backup & Migrate module because it's telling me the file permissions are not set correctly. i have tried various settings in the command line using chmod. i've removed rwx from users and group but it's still not working. can someone clue me in exactly how they should be set?

the folders used are files/private/backup\_migrate/scheduled and then same for manual too.

neither backup option is working. thanks in advance!

# Answer
> 1 votes
Well last time I had the same problem what I did is connect with fillezilla and right-click to the root folder of my site then change permissions to 777 filezilla will go through all your folders and sites and will change all the permissions automatically, it will take some minutes but then all your folders and files will have 777 permissions, try again to use your back-up and migrate, do not forget to clear chaches, after use backup and migrate change the permissions to your settings.php and your private folder in sites/default/private that forlder is where backpup and migrate saves the backups.

Also make sure the the database user you are using with your drupal has all the privileges.

---
Tags: backups
---


# Question
Title: Print views fields in a custom view page template
I am trying to create a custom view page template which will be made of custom fields, which i am trying to print. I created a view page and added all the needed fields to it.

Next, I created a views-view--my-page-name.tpl.php template, which get's recognised, however when i try to print the fields, i get the errors below:

Notice: Undefined variable: fields in include...

Notice: Trying to get property of non-object in include....

Below is the full code of my custom view page template which i copied from the default view page template and modified it. Im trying to print the field with this code:

```
<?php print $fields['views_field_field_name']->content; ?>

```

I tried all variables of field name as: field\_name, field\_field\_name, views\_field\_field\_name, but none of them work, as they all give same error.

```
<div class="<?php print $classes; ?>">
  <?php print render($title_prefix); ?>
  <?php if ($title): ?>
    <?php print $title; ?>
  <?php endif; ?>
  <?php print render($title_suffix); ?>

  <?php if ($exposed): ?>
    <div class="view-filters">
      <?php print $exposed; ?>
    </div>
  <?php endif; ?>

  <?php print $pager; ?>

  <?php if ($header): ?>
    <div class="view-header">
      <?php print $header; ?>
    </div>
  <?php endif; ?>

  <?php if ($attachment_before): ?>
    <div class="attachment attachment-before">
      <?php print $attachment_before; ?>
    </div>
  <?php endif; ?>

<?php print $fields['views_field_field_name']->content; ?>
<?php print $fields['views_field_field_age']->content; ?>
<?php print $fields['views_field_field_phone']->content; ?>

  <?php print $pager; ?>

  <?php if ($footer): ?>
    <div class="view-footer">
      <?php print $footer; ?>
    </div>
  <?php endif; ?>

  <?php if ($attachment_after): ?>
    <div class="attachment attachment-after">
      <?php print $attachment_after; ?>
    </div>
  <?php endif; ?>

  <?php if ($more): ?>
    <?php print $more; ?>
  <?php endif; ?>

  <?php if ($feed_icon): ?>
    <div class="feed-icon">
      <?php print $feed_icon; ?>
    </div>
  <?php endif; ?>

</div><?php /* class view */ ?>

```

# Answer
> 1 votes
You are using template for display, here you will do theming for overall display, the `$fields` variable is not available here.

If you want to change how fields are printed relative to each other, row style, then you should use `views-view-fields.tpl.php`, in your case the name will be like `views-view-fields--yourpagename.tpl.php`.

but if you want to theme individual fields then you have to use `views-view-field--yourfieldname.tpl.php`.

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


# Question
Title: Picking image from server: FileField_Sources not working
I currently have some nodes that use images. Problem is: every time I want to choose an image, I have to upload it again. It would be much better if I could just use a path picker, which could show which images are already uploaded.

This way I could upload the images through FTP and would make me able to give the authors only the rights to choose an already existing image, to be safe with author rights of the pictures.

I found that FileField\_Sources can give the file picker, yet still have the upload function as well, ok fair enough, it's just a matter of telling the authors not to use the upload function.

Problem is, it doesn't work.

I installed the following modules:

1. FileField Sources
2. IMCE
3. IMCE for FileField

However, my original file upload is still unchanged

And I also don't have any new options to choose from in my content types manage fields part.

PS: Yes I activated all the modules in the modules page.

PS2: I also tried to use imagepicker as a module, but this adds a picture in the body. This is NOT what I want, I need the image to come into an image field.

---

A secondary question as well: I want to put the copyights of the pictures on the site as well: preferably a bar coming over the bottom of the picture when you hover it, but a text below is also good enough. If anyone knows a module for this or anything like that, it would very much be appreciated. If not I will just add an extra text field "copyrights" that I will just show below the pictures.

# Answer
I just found the answer myself.

If anyone else would come into the need for something like this:

1. Download the 3 modules that I had typed in my question
2. Go to the Manage fields of your content type & click edit next to the Field
3. Scroll down and click Allow users to select files from IMCE File Browser for this field.

I forgot 2 & 3 :)

I do have to say that it's not 100% what I wanted, as I have different image fields in different nodes, and it only finds the image fields of the nodes that it's in. But I guess I should have used the references instead to make that work...

If anyone still has an answer for my secondary question, it would be much appreciated though, but I'll try to fix that myself tomorrow.
> 0 votes

---
Tags: files, media
---


# Question
Title: Can I download all data from drupal.org?
Does drupal.org make any data dumps available for the content it hosts? I would love a full dump of module / theme / distribution data, etc. without having to scrape the site.

# Answer
http://updates.drupal.org/release-history/project-list/all is a XML-document that lists all projects and their releases. It's a large file, but should provide all the info you need.
> 4 votes

# Answer
I think this is what you're looking for? ftp://ftp.drupal.org/

This dir seems to have all modules ftp://ftp.drupal.org/pub/drupal/files/projects/pub/drupal/files/projects/
> 1 votes

# Answer
Here you can find all downloadable files from drupal.org, but the page took about 5 minutes to load (I have a bad internet connection, but still, looks really long to load): http://ftp.drupal.org/files/projects/
> 1 votes

# Answer
Assuming you actually want to "know" the version information, well, then you have an API!

For drupal.org-hosted modules, the URL is: `http://updates.drupal.org/release-history`

If you want to check if a module is available, query in the following pattern:

```
http://updates.drupal.org/release-history/{project}/{major-version}/

```
* Views module example: `http://updates.drupal.org/release-history/views/8.x/`
* follow module (no 8.x): `http://updates.drupal.org/release-history/follow/8.x/`

Hope this helps.
> 1 votes

# Answer
You can obtain a list of **stable** releases in this file: https://drupal.org/files/releases.tsv (~4MB).

See my response here for details: Is there a drupal.org API for retrieving the list of available modules?
> 0 votes

---
Tags: community-official-site
---


# Question
Title: Is there a way to iterate on all Drupal modules on d.o?
I'd like to iterate on all contrib modules, pull their repos and extract information (such as drush commands, graph dependencies, etc.)

Is there a way to list all modules, other than scraping https://drupal.org/project/project\_module?

# Answer
> 1 votes
Here is a sandbox module (from a Drupal user I trust) that does it: https://drupal.org/sandbox/greggles/1481160

# Answer
> 0 votes
There's an old issue asking for a mechanism to pull entire codebase: Provide a way to download the entire git codebase for all projects. It includes several ways to get it, some of them don't work - I guess because the upgrade of drupal.org to Drupal 7.

---
Tags: version-control, community-official-site
---


# Question
Title: Does adding more processing power increases Drupal Page Load Speed
I have a site hosted on Acquia Cloud.all the unnecessary modules are uninstalled. The site has only couple of nodes (300 almost)and lot of imported registered accounts. Below optimizations are enabled already

http://www.goodykitchen.com

1. memcache
2. varnish
3. CDN - Cloudfront
4. Page Caching (Drupal's Default)
5. CSS / JS aggregation

RAM : 1.7GB CPU : 1 ECU

**Problem:**

My comparison site is bbcgoodfood.com in terms of page load. I have gone through some research and they are using most of above mentioned optimizations. Is there a way to find out why their page load is so smooth. OR should i just increase the Cloud size and see my site page load. (currently i do not have many users on the site)

any clues ? thanks

# Answer
> 0 votes
APC might be your answer

Best APC settings to reduce page execution time

There's a lot here on Drupal speed and performance generally ...

---
Tags: performance
---


# Question
Title: Automatically inheriting title for image
Is there a way to inherit the title or copyright field in the properties of a picture on your pc to the title or alt field of an image in drupal?

---

What I want to achieve is the following:

I want other people to be able to write things on my website, and include a picture to the text. However due to copyrights, I don't want them to be able to upload images. They can only use the images which I have paid for.

This works perfectly, I am using a combination of the following modules:

1. FileField Sources
2. IMCE
3. IMCE for FileField

---

So far so good, but I also want to be sure that the credits are given to the original authors of the images. I know for sure that people will forget to write that in their text, so I was wondering if it was possible to do this automatically.

If the copyright or title field of the image properties would automatically be added to the picture's title in drupal, I could disable the title field & the credits will always be correctly showed. That is, if I add them to the pictures before uploading :)

# Answer
This is probably what you are looking for although it uses Media rather than IMCE... http://webwash.net/tutorials/customize-media-module-image-display-drupal-7

Ok based on your comment I am assuming you have a directory on your computer called: 'images', that contains a bunch of files like 'image-001.jpg', 'image-002.jpg' and properties attached to these files ... on a Windows OS...

You can follow the instructions here: To export your 'images' directory and contents as a CSV (comma-seperated-values) file. This CSV-file can then be 'Read' by Drupal, and it will save you from having to re-enter properties attached to your images manually.

It's important to carefully format your CSV file in Excel or whatever Spreadsheet software you are using (google docs is good at importing and exporting CSVs) so that there is at least one column with unique elements in it, e.g. Column 'Title' - \> Image 001, Image 002, Image 003, etc... Other columns can have headers that match the image properties, such as 'date created', 'copyright' etc...

You can then use the 'feeds' module to import this CSV to Drupal. E.g. you can create a content-type 'Image' with fields that match your CSV's headers...like 'Date Created', 'Copyright' etc...

This question will probably help you in making the last stage happen... https://www.drupal.org/node/1851322
> 0 votes

---
Tags: media, files
---


# Question
Title: Webform confirmation message on same reloaded page
Webform has option to reload the page when submitting the form, but it just refresh the page and doesn't show any confirmation message that the message was sent etc. This might look misleading for simple home user when submitting the form.

Anyway to adding a confirm message on page refresh?

E.g. when submitting it as admin for more than once it actually reload the page and gives message that you already submitted this form. So basically I need the same when visitor submits the form and it would reload the page and show message like 'Thank you, your message was submitted'.

Cheers

# Answer
Once you've set up your webform you have the option to set up how the form responds after asubmission has been made. On the your Webform's Setting page...:

If you click the 'Customize Confirmation' checkbox you can - "Configure your website's actions when a user submits a response to this webform."

> Select from the following form submit options in the menu:
>
> * Show standard confirmation page - Displays a confirmation page that contains the information you enter in the Page body field.
> * Redirect to a different page - Redirects users to the page in the Path field. You can also display a confirmation message by selecting the Show a confirmation message check box, and then entering information in the Page body field.
> * Stay on the same page - Users stay on the webform page. You can also display a confirmation message by selecting the Show a confirmation message check box, and then entering information in the Page body field.

You probably want to select the third option...
> 2 votes

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


# Question
Title: Prepopulating county/state field (ajax driven field)
Before I describe my problem, just going to mention that I tried Commerce Addressbook and Commerce Extra (address populate) modules.

* The first one is not suitable in general for my project (because it's based on billing address when the mother address used in this project is always user's one entered on registration) and
* The latter is in alpha stage and has many issues (and still doesn't sort my problem)

The problem is that I cannot *prepopulate County/State field* on *commerce checkout billing address form*.

When using ***hook\_form\_alter***, I can successfully prepopulate all fields, except county. The reason for this is that county drop down is loaded with ajax and dependent on Country value. It's getting created when the form is built so before the hook\_alter\_form is applied.

So for **example** let's say my billing address defaults to Ireland (one can setup a default value under customer profile -\> billing information). A user registered using address in USA. When the user comes to billing form on checkout, gets all fields prepopulated with the address he/she registered with and country says United Stated, but county/state dropdown stays defaulted to Ireland (lists irish counties).

One needs to select other country than USA and then select USA again for ajax to load the proper county/states dropdown

I cannot seem to find a workaround for this. Any advice?

# Answer
> "So for example let's say my billing address defaults to Ireland (one can setup a default value under customer profile -\> billing information)."

If I understand you correctly perhaps **do not** set a default value for the country in your addressfield options. I.e. do not select a country in the options illustrated below... this way the state options are generated after the user has selected their country...

Incidentally, if you could post whatever your hook\_form\_alter code is and where you put it... I'd find it really useful as I am also working to pre-populate addressfields with user-account details.

Thanks!
> 1 votes

---
Tags: forms, commerce, ajax
---


# Question
Title: How to add custom stylesheet to print pdf output?
I have a view, displayed as table on single page.

HTML print view looks ok (I want border on every td), but it seems that I can't apply any styles to print pdf, I try to use HTML attributes and it seems, that only this is changing appearance of generated PDF.

Any chance to use CSS files to theme PDF output?

I am using Print module with additional PDF module (https://drupal.org/project/Print)

PDF library: tcpdf

**EDIT**

I just used old plain table attributes and it works inside PDF

# Answer
> 1 votes
One of the benefits mentioned on the PDF using mPDF project page is "Add custom Style Sheet to PDF". Here are some more quotes about this module (from the module's project page):

> ... used for Conversion of HTML pages to PDF documents using mPDF PHP Library. It allows you to generate a pdf document of any node.
>
> **Features**
>
> * PDF creation (www.example.com/node/nid/pdf) where nid is the node id of content to render.
> * PDF generation API is provided, the content developers can use this API to generate a PDF document.
> * By creating your own CSS file and/or the node.tpl.php template files, it is possible to change the look of the output page to suit your taste.
>
> **Benefits**
>
> * Document Properties
> * PDF Page settings
> * Watermark Image/Text
> * HTML Header & Footer
> * Password Protected PDF
> * Add custom Style Sheet to PDF
> * Enable/disable PDF generation for each Content type
> * Display/ hide any fields of Content type for PDF

# Answer
> 1 votes
You need to add a "print.css" file on your theme css folder. Print PDF will take it.

```
yourtheme/css/print.css

```

---
Tags: 7, files
---


title: Profile2 restrict main profile

text:
# Question
Title: Profile2 restrict main profile
I really don't know how to fix this so whats why im posting this over here.

Im using Profile2 for my profiles The Main profile is for authenicated users, lets can this User A.

I have also another profile type, with a seperate registration form, lets call this user B.

When user B wants to edit his profile, he can also choose to edit his main profile (profile for user A), i figured out that because user B is authenticaded he can automaticly edit his main profile, and his own profile (specially for user B's). How can i prevent user B for edit his main profile?

# Answer
One solution would be to create two roles, one for A and one for B - then you can restrict access to different profiles in permissions under admin/people/permissions .

You could use Rules to assign the appropriate role based on selections during registration, and use the 'After Saving a new user account' trigger.
> 0 votes

---
Tags: users
---


# Question
Title: Best Approach for View Caching using a Proximity Filter
I have a view that is time-based cached.

One of the options on the exposed form is a 'near me now', which sorts the results by distance and displays mileage.

The users location is provided by the IPM&V Module, and works fine with the view cache turned off.

The problem is that with cache-view turned on, sorting by near me now continues to display the results based on previous requests. The view is 'cached' and not using the current users location.

I could simply turn views caching off, but hate losing the extra speed.

Is there a way (a hook or function) that tells views to 'refresh/clear cache' if certain conditions are met? Ie, if user selects 'near me now' do not cache.

I looked at a combination of rules/cache action, but couldn't get it to work on a specific filter input.

Any ideas appreciated.

# Answer
> 0 votes
How about this module: https://www.drupal.org/files/images/Views\_content\_cache.png

Without testing it I cannot tell if it will expose the 'nearby' state as a filter for for the update cache function but looks like a good place to start:

---
Tags: 7, views
---


# Question
Title: Showing comment form under each paragraph
In node.tpl.php, I have done some changes, like creating an array of paragraphs:

```
    $paragraphs = explode("<p>",render($content));

```

So, I have a for loop for showing the paragraphs, like:

```
$number = count($paragraphs);
if($page){

 print render($paragraphs[0]);
  for ($i=1;$i<$number;$i++)
      {
         print render($paragraphs[$i]);

      <a href="#commenting">Put comment for Paragraph <?php echo $i?><br></a>
<?php  } ?>

   <a id="commenting"><?php print render($content['comments']); ?></a> <?php }?>

```

As you can see I want to create a hyperlink under each paragraph, so when user click on it, they can put comment on the paragraph, But right now, when they click on the hyperlink, it will jump to the end of the page, which has the comment form. If you check the CommentPress website, in the right column, you can see for example, it is said: 5 Comment on Paragraph 1, and when you click on it, it will show the comments and the comment form under that link, I want to have the same thing, I mean, when users click on the link under each paragraph, the comment form displays under that link instead of jumping to the end of the page.

# Answer
I think you will need to do a couple of things. First is to create a comment form under each paragraph:

Drupal 7:

```
$comment = new stdClass;
$comment->nid = $nid;
$form = drupal_get_form('comment_form', $comment);

print render($form);

```

Then I would suggest using some jQuery to hide the forms, showing it only when the user clicks on the link. You can assign a unique class to the $form (see form API reference for more info) so that only the comment form for the specific paragraph shows, instead of all of them when any given link is clicked.
> 0 votes

---
Tags: comments
---


title: ubercart role expiration

text:
# Question
Title: ubercart role expiration
I hope this question is neither a clone nor a stupid one, but I need to fix/understand this very quickly, I did some research though.

Coming to my problem: I am building a no-profit website and we do require a small fee for the participants. So I am using Ubercart to allow people to buy the "Participant" role.

I set everything up and also the payment system works properly. My problem is the expiration. In the product I set the expiration to 1 year, but when a user registers no expiration is set. When I go to **People -\> Role expiration**, the table is empty saying "No expirations set to occur".

I followed some tutorials on-line and I believe I did everything right, can you guys help me with this?

I also think I properly set the permission, even though I have some doubts about.

Thank you, guidout

# Answer
> 1 votes
Found the problem. The Role expiration entry is not created when a NEW user registers to the website buying the role. If an existing user buys the role, it shows up properly in Role Expiration.

If anybody knows how to go around this problem it would be great. Thanks for the help Aparna

# Answer
> 2 votes
```
Edit your product.
Go to features.
From the Add a new feature, Add both recurring fee and role assignment for your product.

```

Hope this helps.

---
Tags: ubercart
---


# Question
Title: How To add Comments to Profile 2 with five star rating on parent node
I need comments on profile2 but with option to vote on parent node / profile after posting a comment.

I've tried reply module but it doesnt support besides I'd have to theme it unlike the original comments in drupal. So I tried to implement below solution that was posted here in other question. Unfortunately don't fully understand and in the quotas you Can find two places that need claryfying. Still I'm not sure if this attached node to profile will work with fivestar?

> A nice workaround is to use Rules, Entity reference and Display Suite (or views). First, you create a new content type 'profile\_ref\_node\_type'. Add only comment fields and delete any unnesseccary fields.
>
> You can now create a new node of the type upon creation of the profile via rules. Add the 'entity has field' condition to be able to access.

Which field exactly?

> your field. As the action I've used my own PHP code, but you can probably use the standard rules as well. My PHP code for creation of the node and entity reference:
>
> $node = new stdClass; $node-\>type = 'profile\_ref\_node\_type'; $node-\>title = 'Profile - \[profile2:field-name\]'; $node-\>uid = 1; node\_object\_prepare($node); node\_save($node);
>
> $profile2-\>field\_node = array('und' =\> array(array('target\_id' =\> $node-\>nid))); profile2\_save($profile2); You then can use this entity reference with display suite to show only the comments on that node (make a new display type if you want to use multiple fields of your node).

I'm not sure what exactly should i do in the DS so it would work.

# Answer
Mentioned by Marcus,

> You should create an entityreference field from the profile2

Please let me add a picture to explain this sentence in detail,

**Using hook\_profile2\_presave instead of using Rules**

* Make a node with Fivestar
* Add Nid into profile 2

---

```
function mymodule_profile2_presave($profile) {
  // is_new is important becase we will add fivestar into mint profile2
  if ($profile->is_new && ($profile->type == 'main')) {
    global $user;
      // Make node for Fivestar and comments
      $node = new stdClass;
      $node->type = 'profile_rate';
      $node->title = 'Rating for the profile';
      node_object_prepare($node);
      $node->language = LANGUAGE_NONE;
      //TODO: Who should be the owner?
      $node->uid = $user->uid;
     // No promote to front
      // Published node
      $node->status = 1;
      $node->promote = 0;
      //  Comments open
      $node->comment = 2;
      // Try to save node
      $node = node_submit($node);
      node_save($node);
      // Save Fivestar NID into profile 2
      $profile->field_article_ref[LANGUAGE_NONE][0] = array('target_id' => $node->nid);
  }
}

```
> 2 votes

# Answer
You should create an entityreference field from the profile2 to the newly created node type. Then in rules, select that field for the 'entity has field' value.

My setup was not available to show the actual comments (only the score), see my comment for a quick workaround (via an embedded view).
> 0 votes

---
Tags: nodes
---


title: Cannot redeclare drupal_get_hash_salt()

text:
# Question
Title: Cannot redeclare drupal_get_hash_salt()
I had a site and it was running fine on the live server but when I moved it to my local server it gave me this error.

```
Fatal error: Cannot redeclare drupal_get_hash_salt() (previously declared in
D:\wamp\www\htdocs\projects\mysite\includes\bootstrap.inc:2248) in
D:\wamp\www\htdocs\projects\mysite\includes\common.inc on line 5045

```

I guess the problem occurred because of editing the variable

```
$drupal_hash_salt = 'zU4q79TqFe0thQO-xGQbfbrFfKloUk9OYXfQ70J1nw0';

```

manually in setting.php file.

Does anybody have any idea how can I solve this problem?

# Answer
You've got definitely a Drupal upgrade problem, drupal\_get\_hash\_salt used to be in common.inc and was moved to bootstrap.inc in Drupal 7.23 version as you can see in https://www.drupal.org/node/1739986.

Something went wrong with your core update, I'd suggest you to backup your data and upgrade your files to the latest version, then run update.php and check everything is OK.
> 2 votes

---
Tags: configuration
---


# Question
Title: Radio button & Option list values migrate successfully with Feeds Importer but disappear in node edit
I'm doing a couple data migration projects. I'm using Feeds Importer and for the most part, things are going well.

But when I migrate option list fields, I get this weird thing where the data is migrated OK (I see it when I view the node and I see it in the appropriate table in the database), but when I edit the node, the option list field is empty/not-selected.

On one of the projects, I was using the radio button widget and the work-around ended up being changing the field's widget from that to Select list.

But on my second project, I was already using the Select List widget, and I can't seem to work around the problem. Tried changing it to radio buttons (hey - I'm not picky), but it didn't help.

It's a really sinister problem because it means I migrate the client's data OK, but when they edit one of these nodes, they will essentially delete data because the radio button or select list widget is not displaying the data. Help?

# Answer
> 1 votes
I don't have enough reputation to comment, so I'm posting this as an answer.

I'd suggest that you install and enable the devel module to compare the data structure of the field in question in these three situations:

1. when the data is input manually
2. when the data is loaded via feeds
3. when the data loaded via feeds is later edited

If you haven't used it, with Devel installed, you can get the 'devel' view of the node.

# Answer
> 0 votes
Thanks, caelbtr! Good advice. I didn't actually use the devel module (though it is great for many things).

But I did set one of the fields manually and saved it so I could scrutinize it in the database. While doing that, I realized my mistake: I had a trailing space at the end of my key! So I had my Option list value settings like this:

```
Yes |Yes
No |No

```

Changing it to...

```
Yes|Yes
No|No

```

...makes the migration (using Feeds Importer) work correctly.

It's fascinating that a trailing space would cause this behavior - but there you go! ; )

---
Tags: feeds
---


# Question
Title: How to disable Ubercart order mail notification?
Everytime a customer places an order, the store owner gets an email with the order invoice. Where can I disable this? (the webshop is still in production)

Also, is it possible to set up a conditional to only send an e-mail when the customer has paid? (right now paypal payments works)

# Answer
> 1 votes
You can disable the Rule (Configuration -\> Workflow -\> Rule):
**E-mail admin checkout notification.**

About the second question, you can customize the Rule:
**E-mail an order update notification**
to email the store owner when the order changes status AND when the status is equal to "Payment received"

Hope this helps

---
Tags: ubercart, emails
---


# Question
Title: Facebook Comment Social Plugin - Get Comment Count on Nodes and Views
I used a module 'Facebook Comment Social Plugin' to display comments on nodes, which it successfully did, however i like to know, is there a way to display **comment count** for the comments coming from the facebook plugin in nodes and views.

# Answer
This might be late to answer, but do checkout Social Stats module.

> This is a statistics module. It provides data from various social media sites. The data which is saved per node. It includes data from:
>
> 1. Facebook : likes count, shares count, comments count & total count.
> 2. Twitter : tweets count.
> 3. LinkedIn : share count.
> 4. Google Plus : plus one count, share count & total count
> 5. Total Share Count : total across all available social networks

It has an view integration. So, it would serve your purpose exactly.

P.S - I am the author and maintainer of the module. If you find any issues please feel free to report using the issue queue, and I'll be glad to help.
> 1 votes

# Answer
To get this value, you are going to have to go outside of the module and write some code yourself to interact with the graph.

This blog post may be slightly out of date but most of the core concepts should be there: https://developers.facebook.com/blog/post/490/

You are going to have to query the graph and parse the response. Afterwards you can take the value you want and use it as you see fit. In this case: "count".

This may be worth adding a feature request to the module's page to ask them if they would be willing to implement this feature as a block. http://drupal.org/node/add/project-issue/facebook\_comments

Hope that helps.
> 0 votes

# Answer
Use the following function on the **template.php** and call the function on the tpl files

```
function yourmodule_fb_comment_count() {

  $fb_comments_count =  '<fb:comments-count href= '.$base_root .$_SERVER["REQUEST_URI"]. '/></fb:comments-count>';
  return $fb_comments_count;

}

```
> 0 votes

---
Tags: nodes, comments, social-network
---


title: Hide/Show a DIV

text:
# Question
Title: Hide/Show a DIV
In node.tpl.php, I have:

```
          <a href="#" id="hideshow">Show </a>
       <div id="comments" style="width: 300px; border" 1px solid #777; padding:10px;>

              Some text in here

       </div>

       <script type="text/javascript" src="js/comments.js"></script>

```

And as you know node.tpl.php is in template folder.

I also have a comments.js file:

```
                 $('#hideshow'). toggle
                  (
                    function()
                     {
                  $('#hideshow') . text('Hide');
                     },
                 function()
                  {
                $('#hideshow'). text('Show');
                  }
                  );

```

the comments.js file is in a folder called, js, and it is in the template folder, so actually this is the path for comments.js file:

template/js/comments.js

So according to my program, when I click on the word Show, it should change to Hide, but when I click on it, nothing happens. Does anybody knows, what is the problem?

# Answer
Change your $ to JQuery, or have below code wrapper around

```
(function ($, Drupal, window, document, undefined) {

})(jQuery, Drupal, this, this.document);

```

In this case you can use $ .

Normally I put js file inside of my subtheme, unless it is module relate.
> 3 votes

# Answer
Assuming you have confirmed your javascript file is actually being included in the page, your problem is likely that the javascript is running before the elements have been rendered on the page.

To avoid this you need to make sure that any custom js you have is inside a drupal behavior (or $(document).ready() at the very least).

It will be like this:

```
(function ($) {
  Drupal.behaviors.yourBehaviorName = {
    attach: function (context, settings) {
      // Your code goes here.
    }
  };
})(jQuery);

```

For more info see https://drupal.org/node/756722#behaviors (the whole page is useful info).

As for adding the js, I recommend you use drupal\_add\_js() in your node template preprocessor, which would look something like this:

```
/**
 * Variable preprocessor for the node template.
 */
function THEMENAME_preprocess_node(&$variables) {
  // Add the javascript for the comments on node pages.
  drupal_add_js(drupal_get_path('theme', 'THEMENAME') . '/js/comments.js');
}

```

That code would go in your theme's template.php file. Remember to change THEMENAME to the name of your theme.
Also, as you can see from that code I recommend you move the js file to the js folder of your theme, not put it in the templates directory.
> 1 votes

# Answer
1) unless you specifically allow for it, change the $ to jQuery. To avoid JS library conflict, Drupal by default turns this jQuery shortcut off.

2) your source path is wrong. It would be relative to the root, not the node. For example, if your node.tpl.php is in /sites/all/themes/THEMENAME/template/, and your comments.js is in /sites/all/themes/THEMENAME/template/js/ your include source path should be:

```
<script type="text/javascript" src="/sites/all/themes/THEMENAME/template/js/comments.js"></script>

```

where you have it relative to node.tpl.php. Most things run relative to the root (or $base\_url) not the position of the file.
> 0 votes

# Answer
The code is correct. Make sure the js file is included with the correct path followed from the base url.

If it is then try this to replace the selector `$` with `jQuery`

```
jQuery('#hideshow').toggle(function() {
  jQuery('#hideshow') . text('Hide');
},
function() {
  jQuery('#hideshow'). text('Show');
});

```

I hope It works.
> 0 votes

---
Tags: javascript
---


title: Webform (*) instead of required word

text:
# Question
Title: Webform (*) instead of required word
I have a situation I want to put (\*) instead of "required" word inside the place holder of a webform field is it possible from webform admin.

# Answer
> 0 votes
You can add this (\*) in field label with field name or can use with style also.

# Answer
> 0 votes
You can always write a hook\_preprocees\_HOOK in your theme's template.php, in this case it would be

```
<?php
function THEME_preprocess_field(&$variables) {
   if ($element['#field_name'] == 'field_YOURFIELD' && $element['#bundle'] == 'webform' && $element['#view_mode'] == 'full') {
    $variables['theme_hook_suggestions'][] = 'field__field_WEBFORM_MY_TPL';
    $variables['ANOTHER VARIABLE_TO_OUTPUT'] = 'preprocessed';
  }
}

```

where you can manipulate the vars for this field, or even set your own template by copying the field tpl to your needs

---
Tags: 7, webforms
---


# Question
Title: Add state for Germany and drop-down menu
How do you change the default fields in the addressfield Module for a given country?

For Germany you have , while for USA you get , including a nice drop down menu with all 51 states.

I want to change the Germany default to have

* only one address field (only Address 1)
* a field with a drop down menu, showing the states of Germany.

I read on drupal.stackexchange that it should be possible with hook\_form\_alter or with ctools module, but within 4 hours of browsing and trying, I could not figure out how?

I'm using drupal for 5 months, so I would appreciate a detailed answer, but also any short link, that helps me to solve that issue, is highly appreciated.

# Answer
> 2 votes
Address Field module uses a plugin system for building the address fields. You should create an address field plugin in your custom module.

`hook_form_alter()` wouldn't help much in this case.

To create a plugin for Address Field, you should first implement `hook_ctools_plugin_directory()` in your module to tell you have an addressfield plugin and where they live:

```
function YOURMODULE_ctools_plugin_directory($module, $plugin) {
  if ($module == 'addressfield' && $plugin == 'format') {
    return 'plugins/format';
  }
}

```

Then, create the folders `plugins/format` in your module. The folder names are up to you. Under this folder create an `.inc` file, and give it a relating name, like `german-states.inc`.

In this file, you should define a `$plugin` array, which holds the information about your plugin, including the callback function name. Then define a function which can add new form elements, edit existing form elements etc.

```
$plugin = array(
  'title' => t('German States'),
  'format callback' => 'YOURMODULE_format_german_states_generate',
  'type' => 'name',
  'weight' => 0,
);

function YOURMODULE_format_german_states_generate(&$format, $address) {
  // Add new form element for German states
  if ($address['country'] == 'DE') {
    $format['locality_block']['administrative_area'] = array(
      '#title' => t('State'),
      '#required' => TRUE, // Set this FALSE if you don't want it to be required.
      '#attributes' => array(
        'class' => array('state'),
        'x-autocompletetype' => 'region',
        'autocomplete' => 'region',
      ),
      '#options' => array(
        '' => t('--'),
        'BW' => t('Baden-Württemberg'),
        'BY' => t('Bavaria'),
        'BE' => t('Berlin'),
        'BB' => t('Brandenburg'),
        'HB' => t('Bremen'),
        'HH' => t('Hamburg'),
        'HE' => t('Hesse'),
        'NI' => t('Lower Saxony'),
        'MV' => t('Mecklenburg-Vorpommern'),
        'NRW' => t('North Rhine-Westphalia'),
        'RP' => t('Rhineland-Palantine'),
        'SL' => t('Saarland'),
        'SN' => t('Saxony'),
        'ST' => t('Saxony-Anhalt'),
        'SH' => t('Schleswig-Holstein'),
        'TH' => t('Thuringia'),
      ),
    );
  }
}

```

# Answer
> 0 votes
I just make a commit to a sandbox on drupal https://www.drupal.org/sandbox/mordonez/1508242

This module works fine for me (France), but should work too in your case. Locality textfield is converted into a select list, dynamically populated (using geonames) after a postal code input.

---
Tags: entities
---


# Question
Title: How can I change _XTRAS_LIST and keep it from being overridden?
I'm running BOA on Linode Server and here is the last line of my barracuda\_log.txt file:

```
Sun Jun 22 10:39:16 EDT 2014 / Ubuntu.lucid x86_64 XEN / Aegir BOA-2.2.6 / Barracuda BOA-2.2.6 / Nginx 1.7.2 / PHP 5.3 5.2 / FPM 5.3 / CLI 5.3 / MariaDB-5.5.38 FQDN / Wildcard NO

```

I want to add the Compass Tools and FFmpeg support, so in my .barracuda.cnf I changed `_XTRAS_LIST="CSF CHV FTP"` to

```
_XTRAS_LIST="CSF CHV FTP CSS FMG"

```

However, upon running barracuda up-stable it returns to

```
_XTRAS_LIST="CSF CHV FTP"

```

I tried adding `_EASY_PUBLIC=NO` to the end of the .barracuda.cnf, but that didn't help.

What am I doing wrong?

Thanks for your help in advance.

Steve

# Answer
> 1 votes
It is a known bug affecting Ubuntu instances.

---
Tags: aegir
---


# Question
Title: How to create Taxonomy Term using Services?
I've a vocabulary called `Tags`. I need to create `Taxonomy terms` under this vocabulary using REST service.

So What is the JSON format to create `taxonomy term`. Similarly what is the JSON format to update `taxonomy term`?

# Answer
> 1 votes
I'm using POSTER plugin (for Firefox) to post data.

Here are the parameters.

**URL:** \[your path\]/\[end-point\]/taxonomy\_term.json

**Content Type:** application/json

**Actions:** POST

Here are the JSON formats.

To create *Taxonomy Term*

```
{
    "vid": "1",
    "name": "My First Tag",
    "description": "Term description",
    "vocabulary_machine_name": "tags"
}

```

To update *Taxonomy Term*

```
{
    "tid": "14",
    "vid": "1",
    "name": "My First Tag Edit",
    "description": "Term description changed"
}

```

Here `tid` is taxonomy id and `vid` is vocabulary id of the Taxonomy.

Hope it helps someone.

# Answer
> 0 votes
First of all tid will not be remain. It's always be incremental. You got the name, vid and description :).

You just have to use taxonomy\_term\_save. For more reference see this comment.

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


# Question
Title: Caching $_SESSION data for anonymous users
I recently inherited a Drupal 6 website that is using $\_SESSION to store a lot of anonymous user data. Currently none of this $\_SESSION data can be accessed while caching is enabled.

I have considered using cookies to work around this limitation but would like a fallback for users without javascript enabled.

Is there a way to do this in D6, D7 or the upcoming D8?

# Answer
I think your best option is to use 2 cookies. Set one cookie that checks to see if the browser has JavaScript enabled. If JavaScript cookie is not there, the user gets an uncached page. If JavaScript does exist then drop a cookie containing the session data. Do the uncached page check in your settings.php file.

If you have something like Varnish or Nginx on your web stack, checkout ESI as it can work how you want it if the browser doesn't support JavaScript.

Also checkout http://drupal.org/project/authcache as it might be what you're looking for (minus the JS part...)
> 1 votes

# Answer
If you are having issues with creating the session for **anonymous user**, then it can be the issue with missing the user whose user ID is zero (anonymous user) from the *users* table.

You can restore it by running this SQL query from PHPMyAdmin.

```
insert into users (name, pass, mail, theme, signature, language, init, timezone) values ('', '', '', '', '', '', '', '');
update users set uid = 0 where name = '';

```

Drupal 7 always need a user with that user ID to create a session for it.
> -2 votes

---
Tags: 6, users, caching, sessions
---


# Question
Title: Provide a default image for image field programmatically at theme level
I have an image field on a node, which will not always be populated. In the case where the field is empty (no image), I want to alter the markup to display a random image which always exists in a specified directory of the files dir. The second part isn't a problem, but I am struggling with the alter part. I am trying to find the correct hook or theme function to test if the image field is empty and then render some markup in it's place. I am lead towards a theme function. Any ideas?

Thanks

# Answer
> 0 votes
use hook\_node\_view\_alter. Check over there that if images is empty then fetch image from your whatever custom directory and print it. For printing an image use theme\_image.

# Answer
> 0 votes
I have achieved this by providing a default image for the field, and then using theme\_preprocess\_field to alter the uri. I'm not currently sure what adverse effects this may have.

```
function mytheme_preprocess_field(&$variables) {
  if($variables['element']['#field_name'] == 'field_myfield_image') {
    $variables['items'][0]['#item']['uri'] = 'public://path_to_img/my_new_image.jpg';
  }
}

```

---
Tags: nodes, theming
---