title: Checkbox near multifield value

text:
# Question
Title: Checkbox near multifield value
I want to make a new content type called **Event**, I have other fields in Event, but the field I am having trouble is *Keynote Speakers*.

**Speakers** are different content types and have their own fields like Name, Address.

In **Event content type** I have a *field entity reference* for this *speakers content type*, where Multiple Speakers could be added. I want to have a **Checkbox** near every speaker which would say Key Speaker as Title and could be checked to make the speakers as Key Speaker.

I tried this with *Field Collection Module*, where I made a collection type of Speakers and inserted the Entity Reference for Speaker as a field value. I created a new *Boolean* field with *checkbox*, but that went on to be

My quest is to make that **Keynote Speaker** as a separate title and have a checkboxes near every Speaker, if checked they'll be added as Keynote Speaker. Like:

How do I achieve this ?

# Answer
I would suggest using two entity reference fields rather than one. One for storing the speakers and another one for storing the keynote speaker.

The you could place these two fields side by side and then hide the label of the keynote speaker through css.

You could also achieve this in a module using the form alter function to alter the style of the form.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How to fix 'Cannot access empty property' when visiting admin/reports/databasereport?
> Fatal error: Cannot access empty property in /home/public\_html/sites/all/modules/dba/database/mysql.report.inc on line 44

I get the above fatal error on a WSD when clicking on */admin/reports/databasereport* (using Drupal version 7.22).

Any idea what it means and how to fix it?

# Answer
> 1 votes
I haven't used the Database Administration module before but when i looked on the line 44 of that module and I found that:

```
$value = new stdClass();
$query = db_query('SHOW GLOBAL STATUS');
foreach ($query as $row) {
  $column = $row->variable_name;
  $value->$column = $row->value;
}
return $value;

```

It means you can't fetch the data from 'SHOW GLOBAL STATUS' SQL statement. So i think maybe your current MYSQL account didn't have right to do that.

---
Tags: debugging
---


title: Google showing pages with ?page=2 urls

text:
# Question
Title: Google showing pages with ?page=2 urls
In one Drupal 6 based site there are product pages like : example.com/product1, example.com/product2 etc but in Google search engine result pages(SERP) it is instead taking us on clicking to url's to like : example.com/product1?page=2 or page=1 or other pages and so on.

This site has Nodewords installed and has meta-description defined for each page. But in case of url's like example.com/product1?page=2 meta-description isn't appearing.

The front-page seems to be set to "/node" so I can see in the bottom of the front-page as 1,2,3,4 ... links for pagination.

I simply want Google to index the page like example.com/product1 and not example.com/product1?page=2.

Why this could be happening and how can I resolve it?

# Answer
Those links appear in Google's index because they're linked to on your site (presumably the pager generates those links for you) and you allow Google to crawl and index them.

If you do not want those pages to be crawled and indexed by Google, then you can disallow it by adding the following to the `robots.txt` for your site (btw.: this has little to do with Drupal):

```
Disallow:*?page=*

```

This will stop *googlebot* (and *msnbot*) from crawling the pages that is linked to with a link that contains this pattern.

Note that wildcards are not part of the Robot Exclusion Standards (but are supported by *googlebot* and *msnbot*), so don't expect any rule with wildcards to be widely recognised by robots.
> 2 votes

# Answer
To add another side to what Gisle Hannemyr already wrote - once Google has your links indexed, it might be hard to get rid of them. But there is no need.

First, there is a Global Redirect module to seamlessly redirect you to the "main" version of your node, no matter what way user accessed it. So you usually don't need to get rid of all that power these links give you.

With pager it might be a bit hard. If there is a real pager, you don't want to disallow Google indexing. Instead, providing good link "go to first page" would be useful.

In your case it's a pager of paginated thing that's not really a content. So you cannot simply redirect. Canonical URL module or more recent **Nodewords module** allows Google to index all links, no matter to which page, but tells Search Engine that user should be directed to the canonical address, the one without `?page=1` part.

For Drupal 7, use Metatag module to provide canonical location.
> 1 votes

---
Tags: 6, navigation, meta-tags
---


# Question
Title: Open a view getting nid from previous view
I have two view. One is a Gallery view and the other is a view with exposed filter with which i choose field\_gallery\[nid\] to make operations into some editable fields.What i wish to Know is if i can add a link in the first view with which open second view calling the \[nid\] of the first. Do you think is possible?

# Answer
Yes it is possible.

You can do the following

1. In the first view add nid field
2. In the field settings go to rewrite result
3. In rewrite result give something like Link Text

\[nid\] will work as a place holder for the current content nid. You can see all the replacement patterns with in the view itself.
> 1 votes

# Answer
if you want the first view to display a link to the second view (with exposed filter) so that the nid from the first view passes to the second view for exposed filter to work,

extending Mohammed Shameem's answer which gives you the correct way to add the link, you also need to take care of the URL format.

Exposed filters usually have a identifier in the url of format:

```
www.abc.com/cde/?fgh=ijk

```

Here fgh is identifier and ijk is the value passed.

So you need to construct URL in that format.
> 0 votes

---
Tags: views
---


title: Form redirect (?)

text:
# Question
Title: Form redirect (?)
I' trying to build this kind of pages:

* one page for each taxonomy term with taxonomy info and all commerce products related to term

plus

* one 'products' page where users can click on a taxonomy image to view all the products in a box (loaded via ajax).

I have built taxonomy/term/\* pages and the products page and they work fine but when I tried to add a product to cart (from taxonomy/term AND products pages.. ) drupal add the product to cart but always redirect me in the taxonomy/term page.

So I tried to setup a different form #redirect in hook\_form\_alter() but it work in a strange way: when I call taxonomy/term page via ajax to include it in products page now drupal serve me the product page itself like there is a all times redirect from taxonomy/term page to products page.

```
$form['#redirect'] = drupal_goto('products');

```

If I write

```
$form['#redirect'] = 'products';

```

just do not redirect.

How can I achieve a right redirect?

I'm working in D7 with drupal commerce to manage e-commerce

# Answer
> 0 votes
I solved this problem with this code:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if( startsWith($form_id, 'commerce_cart_add_to_cart_form_') ){
    array_push($form['#submit'], '_mymodule_redirect_to_products_page');
  }
}

function  _mymodule_redirect_to_products_page(&$form, &$form_state){
  global $language ;
  $lang_name = $language->language ;

  $form_state['redirect'] = url('prodotti', array('language' => $language));
}

```

---
Tags: forms, redirection
---


title: Default tab by date or day

text:
# Question
Title: Default tab by date or day
I'm building a TV listing and I'm using quicktabs module with tabs:

* Monday
* Tuesday
* Wednesday
* Thursday
* Friday
* Saturday
* Sunday

Every tab shows a node that have a TV listing.

Is it possible these tabs to be shown by date/day?

Example: today is Monday, so when a user enters the page for TV schedule the active tab will be Monday.

I've inspected the tab links and I find out that every tab has additional link to the main URL.

Example: The first tab (in mine case - Monday) has /program?qt-quicktabs\_tv\_schedule=0#qt-quicktabs\_tv\_schedule

The second tab (in my case - Tuesday) has /program?qt-quicktabs\_tv\_schedule=1#qt-quicktabs\_tv\_schedule

etc.

EDIT:

I've tried this code:

```
(function($){

$(document).ready(function(){
var d = new Date();
var n = d.getDay();
$(".quicktabs-tabs li").removeClass('active');
$('#quicktabs-tab-quicktabs_tv_schedule-0' + n).parent().addClass('active');

});
})(jQuery);

```

The removing active class is working, but the days changing based on

```
var d = new Date();
var n = d.getDay();

```

it's not working. Maybe I'm missing something...

EDIT 2:

Here's what I've tried:

```
     (function($){

        $(document).ready(function(){
        var d = new Date();
        var n = d.getDay()-1;
        if ( n == -1) {
        n = 6;
        };

        $(".quicktabs-tabs li").removeClass('active');
        $('#quicktabs-tab-quicktabs_tv_schedule' + n).parent().addClass('active');
        $('.quicktabs-tabpage').addClass('quicktabs-hide');
        $('#quicktabs-tab-page-id-' + n).removeClass('quicktabs-hide');

        });

})(jQuery);

```

With this code it simply hides the default tab.

# Answer
> 2 votes
You can use javascript for this.

Each quicktab "A" tag has an ID something like quicktabs-tab-name-0 (replace name with the quicktab name you have given)

You can use some thing like the below code to get the current day of the week

```
var d = new Date();
var n = d.getDay();

```

this would return a number which would be something from 0 to 6 where 0 Represents Sunday and so on.

The active class is set to li tag with in which the a tag is placed.

So first we need to remove the active class from all the li with in quick tab this can be done with

```
$(".quicktabs-tabs li").removeClass('active');

```

Next we need to add the active class to the current day's tab for which you could do something like.

```
$('#quicktabs-tab-name-' + n).parent().addClass('active');
// n is the day number we got from the code above.

```

Next you need to enable the tab page for the corresponding tab for that you would do the following. The first one would add the hide class to all tab pages and the second code removes the hide class from the current div.

```
$('.quicktabs-tabpage').addClass('quicktabs-hide');
$('#quicktabs-tab-page-id-' + n).removeClass('quicktabs-hide');

```

That should do it.

Just make sure that the tabs are arranged form Sunday to Saturday. So that quicktab ids also get the same numbering. If you want a different order then you can offset the number accordingly by adding the offset value and then getting the reminder value of a division by 7.

So in effect the complete code would be

```
var d = new Date();
var n = d.getDay();
$(".quicktabs-tabs li").removeClass('active');
$('quicktabs-tab-name-' + n).parent().addClass('active');
$('.quicktabs-tabpage').addClass('quicktabs-hide');
$('#quicktabs-tab-page-id-' + n).removeClass('quicktabs-hide');

```

This would go inside the document ready function.

---
Tags: blocks
---


title: Reload Javascript after ajax event

text:
# Question
Title: Reload Javascript after ajax event
I have a module that uses a button to load an embed view everytime the button is clicked.

```
// function to print builder view
    function workout_builder_template() {
        $viewName = 'builder_view';
        print views_embed_view($viewName);
    }

workout_builder_template();

```

However after the button is pressed a new view is loaded and the view is no long ajaxified. For example, if I click the apply button after changing the exposed forms, the form submits to a new page. Before clicking the button that loads an embed view via ajax, the exposed form altered the view content via ajax.

Here is example html from the ajaxified view

```
<form accept-charset="UTF-8" id="views-exposed-form-builder-view-default" method="get" action="/drupal7/builder-view" class="ctools-auto-submit-full-form ctools-auto-submit-processed jquery-once-1-processed">

```

Here is example html from the ajax less view

```
  <form accept-charset="UTF-8" id="views-exposed-form-builder-view-default" method="get" action="/drupal7/builder-view" class="ctools-auto-submit-full-form">

```

In the example the ajax less view does not have processed classes added to it. From this I suspect that the new view does not get javascript attached to it after the first ajax event. I have been researching drupal.behaviors and thought about printing

```
$vars['scripts'] = drupal_get_js();
print $vars['scripts'];

```

in the workout\_builder\_template() function displayed above, but I am not sure how this is done

# Answer
> 2 votes
I could be wrong here but am going to assume that the fetching of the embedded view and HTML refresh on the client-side has been done using custom Javascript code.

Once new HTML has been added to the DOM in a custom way, then to attach all Drupal behaviors defined by active modules, from within the `success` callback of your XHR client (say `jQuery.ajax()`) you might have to manually call:

```
// $wrapper here is the jQuery object identifying the wrapper element to
// which your new HTML has been injected to. Eg. $wrapper = $('.my-view-wrapper')
Drupal.attachBehaviors($wrapper, Drupal.settings);

```

My recommendation would be to try and possibly switch to the Drupal AJAX API (Documentation) as it lets you keep this *refresh* logic on the server-side (one place). The other, obvious benefit is that `Drupal.attachBehaviors()` is called for you automatically.

---
Tags: 7, views, forms, javascript, ajax
---


title: Best practice for writing PDO Query?

text:
# Question
Title: Best practice for writing PDO Query?
I have noticed one thing in all core files: all DB related operations are not in try-catch block.

So please suggest me whether it's good practice to put SELECT, UPDATE, INSERT query in try catch block.

# Answer
> 2 votes
It's good practice to put *any* code that could potentially throw an exception in a `try...catch` (not just in Drupal-related code, and not just in PHP).

So yes, it's good practice to put your database queries in a `try...catch`.

---
Tags: 7
---


# Question
Title: How to sort drush status messages in test scripts?
I'm using drush to run test scripts agains my drupal 7 installation. Simply calling:

```
$ drush scr path/to/myScript.php

```

My script is using `drupal_set_message()` to output status of my test scripts.

My problem is the output is sorted by importance, like that:

```
Test 1339 failed.                [error]
Test 1338 failed.                [error]
Something strange happened!      [warning]
Test 1337 successful.            [status]
Script starting.                 [notice]
Script finished after 1234ms.    [notice]

```

Is there any way to sort the output of the messages by the time they get called in my script, it would look much more logical like that:

```
Script starting.                 [notice]
Test 1337 successful.            [status]
Test 1338 failed.                [error]
Something strange happened!      [warning]
Test 1339 failed.                [error]
Script finished after 1234ms.    [notice]

```

Is that possible somehow? Is `drupal_set_message()` the wrong approach? Any suggestions?

# Answer
> 1 votes
You can log your debugging messages in database using watchdog and you will find the logged message in order at "admin/reports/dtblog"

**Updated:** Check the document page, as for \[status\] , watchdog has $severity parameter to set the status for your message.Following values can be set as status for the logged message.

```
WATCHDOG_EMERGENCY: Emergency, system is unusable.
WATCHDOG_ALERT: Alert, action must be taken immediately.
WATCHDOG_CRITICAL: Critical conditions.
WATCHDOG_ERROR: Error conditions.
WATCHDOG_WARNING: Warning conditions.
WATCHDOG_NOTICE: (default) Normal but significant conditions.
WATCHDOG_INFO: Informational messages.
WATCHDOG_DEBUG: Debug-level messages.

```

As a simple example, check this

```
 watchdog('your_script_name', '!message', array('!message' => "something_happened"), WATCHDOG_ERROR);

```

the above will log message when called keeping severity as "error".

---
Tags: testing, drush
---


# Question
Title: theme_preprocess_views_view_fields() function in drupal7 does not accept static variable as index
This is my code

```
function THEME_preprocess_views_view_fields(&$variables)
{
    static $i = 0;
    $variables['address'] = t($variables['view']->result[$i]->field_address[0]['raw']['uri']);
    $variables['address1'] = t($variables['view']->result[0]->field_address[0]['raw']['uri']);
    $i++;
}

```

I wrote the following code in *views-view-fields-VIEWNAME--page.tpl.php* :

```
<?php print $address; ?>
<?php print $address1; ?>

```

the second `print` successfully printed its relevant value but the first one displayed nothing.

I tried to use this trick but i failed :

```
<?php
if($i==0)
    $variables['address'] = t($variables['view']->result[0]->field_address[0]['raw']['uri'];
if($i==1)
    $variables['address'] = t($variables['view']->result[1]->field_address[0]['raw']['uri'];
.
.
.

?>

```

why can't I use static variable as index?

---

**UPDATE**

after useful comment of Clive and arpitr I modified my code and I created two `THEME_preprocess_views_view_fields` functions separately as follow:

```
function THEME_preprocess_views_view_fields(&$variables)
{
    static $i = 0;
    $view = $variables['view'];
    if($view->name == "MY_VIEW_NAME")
    {
    $variables['address'] = t($variables['view']->result[$i]->field_address[0]['raw']['uri']);
    $i++;
     }
}

```

and this one

```
function THEME_preprocess_views_view_fields(&$variables)
{
    static $i = 0;
    $view = $variables['view'];
    if($view->name == "MY_VIEW_NAME")
    {
    $variables['address'] = t($variables['view']->result[$i]->field_address[0]['raw']['uri']);
     }
}

```

for the upper one it was the result

```
Array

```

and the second one (without `$i++`) successfully printed the right value.

# Answer
Static vars aren't special beyond persisting inside the scope of the function they were created, for the duration of a single page build. You categorically **can** use a static var as an array index.

Take the following code:

```
function some_test(&$variables) {
  static $i = 0;
  print $variables[$i];
  $i++;
}

$variables = array(
  0 => 'test1',
  1 => 'test2',
);

some_test($variables);
some_test($variables);

```

Which outputs the following:

```
test1
test2

```

Proving that `$variables[$i]` is accessed as expected.

The problem with you code must be somewhere else, as it's not being caused by a language issue as you suggest.

At a wild guess, `$variables['view']->result` isn't keyed in the same way you expect it to be (possibly keyed by the result's base table ID instead of a zero-based list). Dumping out `$variables['view']->result` should tell you pretty quickly what's happening.
> 1 votes

---
Tags: theming
---


# Question
Title: Use dropdown in views exposed filter on text fields with entity not node?
A very kind soul posted some code here for a small module that allows drop down fields in views for text fields on nodes

I was wondering how I can alter this so it works on an entity I created?

This is the particular field name on this example `field_exact_location`

My entity type is called "site\_object"

```
function dd_city_form_views_exposed_form_alter(&$form, &$form_state) {
$field_id = 'field_exact_location';

// Only alter forms with the necessary field
if (isset($form[$field_id .'_value'])) {
// Build a query to get all node ids having the specified field
$query = new EntityFieldQuery();
$results = $query->entityCondition('entity_type', 'node')
                  ->fieldCondition($field_id, 'value', 'NULL', '!=')
                  ->fieldOrderBy($field_id, 'value', 'ASC')
                  ->execute();

// Attach the field values to the nodes
$nodes = $results['node'];
field_attach_load('node', $nodes, FIELD_LOAD_CURRENT, array('field_id' => $field_id));

// Add a default so the filter is optional
$options = array('' => '<select>');

// Buld the options array based on the query results, overwriting duplicate entries
foreach($nodes as $nid => $node) {
  $value = $node->field_exact_location['und'][0]['value'];
  $options[$value] = $value;
}

// Alter the field
$form[$field_id .'_value']['#type'] = 'select';
$form[$field_id .'_value']['#options'] = $options;
$form[$field_id .'_value']['#size'] = 1;
}
}

```

# Answer
> 1 votes
Think I found a solution at last. It works in my local test environment for the exposed filters in views:

```
function dd_city_form_views_exposed_form_alter(&$form, &$form_state) {
  $field_id = 'field_selected_field';

  // Only alter forms with the necessary field
  if (isset($form[$field_id .'_value'])) {
    // Build a query to get all node ids having the specified field
    $query = new EntityFieldQuery();
    $results = $query->entityCondition('entity_type', 'model')
                      ->fieldCondition($field_id, 'value', 'NULL', '!=')
                      ->fieldOrderBy($field_id, 'value', 'ASC')
                      ->execute();

    // Attach the field values to the nodes
    $entities = $results['model'];
    field_attach_load('model', $entities, FIELD_LOAD_CURRENT, array('field_id' => $field_id));

    // Add a default so the filter is optional
    $options = array('' => '<select>');

    // Buld the options array based on the query results, overwriting duplicate entries
    foreach($entities as $id => $entity) {
      $value = $entity->{$field_id}['und'][0]['value'];
      $options[$value] = $value;
   }

    // Alter the field
    $form[$field_id .'_value']['#type'] = 'select';
    $form[$field_id .'_value']['#options'] = $options;
    $form[$field_id .'_value']['#size'] = 1;
  }
}

```

I only had to change a tiny bit more, than I posted before. Summary for the above code:

1. Rename 'field\_selected\_field' to your field. Example: If it is called 'city', then rename it to 'field\_city'.
2. Change 'model' to the name of your entity. In your case 'site\_object' These are the places:
    * $results = $query-\>entityCondition('entity\_type', 'model')
    * $entities = $results\['model'\];
    * field\_attach\_load('model', $entities, FIELD\_LOAD\_CURRENT, array('field\_id' =\> $field\_id));
3. Save the file to your module, upload it and enable it in Drupal.

A few screenshots of my test environment:

Here my example configuration for a view with an entity named 'model' with the field 'selected\_field'.

If you go to the respective view (in my case /modeltestview), you get the following (the screenshot is only part of the screen). The left part is the starting part,you get the right part if you click on the dropdown list. To show there actually is something in the dropdown list.

---
Tags: entities, views
---


title: Taxonomy panel page visibility problem

text:
# Question
Title: Taxonomy panel page visibility problem
I have a visibility problem.
I have a taxonomy/term page managed with panels. There are 2 panel pane who display 2 views. The problem is that I \[the admin..\] can see the page correctly but all the other users see nothing except a block I putted on top of panel pane for test.

I read the markup and I can see the panel but not the panel panes. This panel panes have no visibility rule and the views inside it have the default Access rule.

How can I find where is the issue?
Why only the user 'admin' can see this pages?

# Answer
> 2 votes
For sure this is related to permission:

A few pointers to help you debug:

1. Please check the permission of the components components you are trying to display through views. For example, a field is related to displaying an uploaded video. Anonymous users might ot be having permission to view it, though have the permission to view, but still they will not be able to access the stuff. So try to figure out what modules are responsible for the field you display through view, and then check the permissions coming from that module.

Actually this will be the only one that looks most probable to me. hope this helps.

---
Tags: views, panels
---


# Question
Title: How to fix Drupal commons 7.x-3 OgException
Problem is fixed in new version commons 7.x-3.3-rc4 https://drupal.org/node/2067473

**Modules:**

1. Organic groups 7.x.2.3
2. Organic groups access control 7.x.2.3

**The content access permissions have been rebuilt.**

In OG field settings (as default) User-User entity Group visibility Determine access to the group Group Determine if this should be a group

I created a Private group with "Joining requires an invitation" trying to add a post to the group I get following exception:

> OgException: Cannot set visibility of node ID 13 as the group node of type "user" does not have the "Group visibility" field attached to it. in \_og\_access\_verify\_access\_field\_existence() (line 250 of srv/www/htdocs/commons7x33rc2/profiles/commons/modules/contrib/og/og\_access/og\_access.module).

The same happens with a Public group with "Any site member can contribute"

What is wrong and how do I fix this?

# Answer
A bit too late maybe but...

...check answer #8 at Organic Groups issues place: https://drupal.org/node/2063479#comment-7882345

I've followed it and solved (at least apparently) the issue.

Hope it helps. Have a nice day! hip
> 1 votes

---
Tags: organic-groups, 7
---


# Question
Title: Commerce: query products and product variations
I have a view with a custom template and I need to query my products using some conditions. I'm running a videogame store, so I have a Content Type and Production Variation called "Games", and those games have a plataform assigned (Content Type field). So now I'm creating a custom PS3 categorie view and I need to query only PS3 games.

This is what I have currently:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'commerce_product')
    ->propertyCondition('status', 1)
    ->propertyCondition('type', 'games')
    ->fieldOrderBy('commerce_price', 'amount', 'ASC');
$result = $query->execute();

```

That query returns a list of "games", but I need to filter them by plataform.

PS: I don't know if any one can share information about querying products in Commerce. I have to say that Commerce API is very poorly explained.

# Answer
Commerce Products are entities, so you can query them exactly like any other entity (like you're already doing). You may consider the commerce API docs for entities to be poor, but that's simply because there *aren't* any - you can apply standard Drupal entity logic.

It seems the only thing you're missing is the platform filter that you mention; that's just a matter of adding a field condition to the `EntityFieldQuery`:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'commerce_product')
  ->propertyCondition('status', 1)
  ->propertyCondition('type', 'games')
  ->fieldCondition('field_platform', 'value', 'PS3')
  ->fieldOrderBy('commerce_price', 'amount', 'ASC');
$result = $query->execute();

```

Your mileage may vary if `field_platform` isn't a text field. For example, if it's a taxonomy term reference, you'll need to find the ID of the taxonomy term and use something like

```
  ->fieldCondition('field_platform', 'tid', 123)

```

Or if it's an entity reference field you'll need the entity ID and to use something like this

```
  ->fieldCondition('field_platform', 'target_id', 123)

```
> 2 votes

---
Tags: commerce, database
---


title: Cannot target #id as menu link?

text:
# Question
Title: Cannot target #id as menu link?
Drupal 6

How can i allow drupal to accept #idname as link? When I put # I cannot submit the form. Is there a way to do this?

# Answer
> 2 votes
You have five options.

1. Use the https://drupal.org/project/special\_menu\_items module
2. Do something like node/16#gohere (I'm not sure if you have a static page this is for)
3. Create a module to either edit a menu item or add one
4. Backport the https://drupal.org/project/void\_menu module
5. Make your own module to do this :)

Sadly there is no way to do this by default.

---
Tags: routes
---


# Question
Title: How to use Form API #attached and module's own scripts with jQuery Multi module?
I was using jQuery Update module, but it conflicts with Views and feature requests for library version per page or per theme are consistently killed. On the other side, Views maintainers seems to assume that if UI works with distribution's jQuery, it isn't broken. Long story short, I was forced to forget about jQuery Update the way we know it.

Solution I found is jQuery Multi module, as it allows load updated jQuery only, if there is a library that requires it in use on the page. And for things like Chosen (when jQuery Update is hacked out of requirements) it works great. Now, I have problem with javascripts directly attached to forms:

```
$form['#attached']['js'] = array(
  drupal_get_path('module', 'aat_pc_product') . '/js/tag.js',
  drupal_get_path('module', 'aat_pc_product') . '/js/tabs.js',
  drupal_get_path('module', 'aat_pc_product') . '/js/categories.js',
);

```

jQuery Multi claims it can be used on any js file, but it's documentation says:

> C) Put the JS anywhere else, like in a custom module, and use hook\_jqmulti\_files() to load it. No need to use the alias. 38
>
> D) Put the JS anywhere, use the provided alias, and don't use the jqmulti hooks or UI. Simply load with drupal\_add\_js() or something similar. If you're only using this method, make sure to select the 'Load Always' checkbox in the jQuery Multi config.

Now, I can't do C) as I'm using Form API and I can't do D) as it breaks Views.

Form API for `#attached` says:

> Description: Allows loading of CSS, Javascript, libraries,

Converting my scripts to a libraries would help, as A) and B) options for jQuery Multi are for libraries, but only examples provided by Form API are for JS and CSS files.

There is one use-case for libraries provided:

```
$form['#attached']['library'][] = array('system', 'jquery.cookie');

```

but it's there without description.

I can make my scripts library:

```
function amymodule_library() {
  $module_path = drupal_get_path('module', 'mymodule');
  $items = array();
  $items['mymodule_form'] = array(
    'title' => t('My Module Form'),
    'version' => '1.0.0',
    'js' => array(
        $module_path . '/js/tag.js' => array(),
        $module_path . '/js/tabs.js' => array(),
        $module_path . '/js/categories.js' => array(),
    ),
    'css' => array(
      $module_path . '/css/mymodule_form.css' => array(),
    ),
  );
  // dpr($items);
  // die();
  return $items;
}

```

And attach it as a library to a form:

```
$form['#attached']['library'] = array(
  array('mymodule', 'mymodule_form'),
);

```

Sadly this does not make it appear on the configuration screen:

I know it's due to the first 2 methods described in documentation:

> A) Put the JS in sites/all/libraries/ and use the UI at admin/config/system/jqmulti to select your library. All the library's JS files will be loaded with the jqmulti jQuery version. There is no need to use the alias in this case. This is ideal if you're using a prepackaged jQuery library or plugin.
>
> B) Put the JS in sites/all/libraries/ and use hook\_jqmulti\_libraries() to include the library. No need to use the alias. This is ideal if you're using a prepackaged jQuery library or plugin, and is equivalent to method A.

Of course I cannot put my scripts there, they are built in part of my module.

Now, I'm perfectly open to module hacking, if that's what needed, but if there is a way to "pretend" that my module's library is in the folder jQuery Multi wants it to be, I would be grateful to know it.

# Answer
> 1 votes
## Solution seems to be to hack jQuery Multi module.

First, we want to add module-provided libraries to the list in configuration options. Function responsible for it is `jqmulti_get_available_libraries()`:

```
/**
 * Returns available libraries to be used in the admin form.
 */
function jqmulti_get_available_libraries() {
  $libs = libraries_get_libraries();

  unset($libs['jquery']);
  foreach ($libs as $key => $value) {
    $libs[$key] = $key;
  }
  return $libs;
}

```

To display module-provided libraries, we need to add following line:

```
$libs += module_invoke_all('library');

```

Of course now it looks ugly:

List is long and hard to understand, because these are machine names only. Red colour used to distinguish element I added by hand after taking screenshot, it's all black folks.

Form element is defined in `jqmulti.admin.inc`, but it's the only place that ever uses `jqmulti_get_available_libraries()`, so we may stay inside it instead, to limit changes to narrow area. If we change this:

```
  foreach ($libs as $key => $value) {
    $libs[$key] = $key;
  }

```

to this:

```
foreach ($libs as $key => $value) {
  if(isset($value['title'])) {
    $libs[$key] = '<strong>' . $value['title'] . '</strong> ' . @$value[version] . ' (' . $key . ')';
  } else {
    $libs[$key] = '<strong>' . $key . '</strong> (' . $value . ')';
  }
}

```

output will get a lot more readable:

Again, blanked a project-related row but it is there all right.

But now the fun part begins. I can save, but logic is all wrong:

> * Warning: scandir(sites/all/libraries/product\_form): failed to open dir: No such file or directory in jqmulti\_find\_all\_js\_files() (line 180 of /var/www/sites/all/modules/jqmulti/jqmulti.module).
> * Warning: scandir(): (errno 0): Success in jqmulti\_find\_all\_js\_files() (line 180 of /var/www/sites/all/modules/jqmulti/jqmulti.module).
> * Warning: Invalid argument supplied for foreach() in jqmulti\_find\_all\_js\_files() (line 181 of /var/www/sites/all/modules/jqmulti/jqmulti.module).

Error is located in `function jqmulti_find_all_js_files($dir)` function. Obviously module still tries to use old way of scanning `/sites/all/libraries` even when I clicked a library that is not there. Function is called from `jqmulti_get_library_files($library, $reset = FALSE)` that blindly assume all files are in `'sites/all/libraries'`. First, it's a bug in it's own right, second it's not sufficient. We need to change:

```
$base_path = 'sites/all/libraries';

```

to something smarter. For example:

```
if(isset($libraries_libraries[$library])) { // Give precedent to old way
  $path = $libraries_libraries[$library];
} elseif(isset($module_libraries[$library])) {
  $path = NULL;
  $files = array_keys($module_libraries[$library]['js']);
} else { // Fallback to the old way, for what it's worth
   $path = $base_path . '/' . $library;
}

```

As you can see, if module gave us files already, there is no need to play with `$path`, we may use it directly. So code below needs to be wrapped in `if`.

**That's all**, now it works. Without conflict with Views, but with all jQuery Multi's own issues, some especially urgent for me.

---
Tags: 7, forms, javascript
---


# Question
Title: How to create pages with images in the content?
I'm trying to create a page with content that looks like this:

I'm using CKEditor to edit the content, and it allows me to add images to the article. However, the images need to be already present at some URL.

Is there a way I can upload an image (the image of the doctor with a pad) to my drupal site separately, and then use its URL to insert the image in my article?

In other words, how do I upload just an image to my drupal site so that it can be used elsewhere?

# Answer
> 0 votes
You should do something like this.

Have two regions, one with the content (ie the left blurry blob). And one called sidebar. The sidebar region would have a block that you would add the right image. And a block (which I assume would be something like a view or maybe it's manually added) to do the Related Links.

Then you could have a content header region for the top part.

So you would end up with

```
|  Content Header  |
| Content | Sidebar|

```

Or at least that is how I would do it.

# Answer
> 0 votes
You could just install the IMCE module, which will allow you to upload images and insert them into CKEditor/WYSIWYG fields. You can use the IMCE module regardless of whether you want to insert the image into your content node directly or make a separate block.

---
Tags: media, nodes
---


# Question
Title: How can I output a text string when my dynamically built form is empty?
I have a form that is dynamically built. It renders a list of check boxes, but sometimes there are none to render - it is empty. In this circumstance, instead of the forms `#titles` with nothing below them being rendered, I'd like to output `t('None')`. For the type `#tableselect` the option seems to exist: `#empty`, but not for checkboxes or any other type. How can I acheive this? Thanks.

Code added:

```
    // Form defintion.
    $form['posts'] = array(
        '#type' => 'checkboxes',
        '#title' => t('Member responses to:'),
        '#options' => $options['post'],
    );
    $form['terms'] = array(
        '#type' => 'checkboxes',
        '#title' => t('Posts tagged with:'),
        '#options' => $options['term'],
    );
    $form['groups'] = array(
        '#type' => 'checkboxes',
        '#title' => t('Group posts for:'),
        '#options' => $options['group'],
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Remove'),
    );
    return $form;

```

I tried at the bottom:

```
if(empty($options)) {
  return t('None');
} else {
  return $form
}

```

...but this threw an error.

# Answer
Your function should return a form element (if you are using `drupal_get_form`). What you could do is return a `markup` element within the form.

```
if(empty($options)) {
    $form['empty'] = array(
        '#type' => 'markup',
        '#markup' => t('None'),
    );
} else {
    $form['posts'] = array(
        '#type' => 'checkboxes',
        '#title' => t('Member responses to:'),
        '#options' => $options['post'],
    );
    $form['terms'] = array(
        '#type' => 'checkboxes',
        '#title' => t('Posts tagged with:'),
        '#options' => $options['term'],
    );
    $form['groups'] = array(
        '#type' => 'checkboxes',
        '#title' => t('Group posts for:'),
        '#options' => $options['group'],
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Remove'),
    );
}

return $form

```
> 0 votes

# Answer
I don't know what's the code before/after and exact context in which you are using it., but this could work for you:

```
if(empty($options)) {
  $form['empty']['#markup'] = t('None');
}
else {
  // Form defintion.
  $form['posts'] = array(
      '#type' => 'checkboxes',
      '#title' => t('Member responses to:'),
      '#options' => $options['post'],
  );
  $form['terms'] = array(
      '#type' => 'checkboxes',
      '#title' => t('Posts tagged with:'),
      '#options' => $options['term'],
  );
  $form['groups'] = array(
      '#type' => 'checkboxes',
      '#title' => t('Group posts for:'),
      '#options' => $options['group'],
  );
  $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Remove'),
  );
}
return $form;

```
> 0 votes

---
Tags: forms
---


title: Webform as homepage

text:
# Question
Title: Webform as homepage
Im using the webform module to create some reports.

I have only 2 pages available to users : submit a report and view existing reports.

Is there any way of making the "submit a report" page the default homepage ? ( right now it's a navigation item and i have the "add new content" link in the homepage)

I use a custom content-type for the form. Not sure if this is relevant or not.

# Answer
> 1 votes
Of course you can - just enter the path alias in `admin/config/system/site-information` or enter `node/[your webform node ID]` instead.

---
Tags: 7, webforms
---


# Question
Title: which hook is effective for setting custom breadcrumbs?
I have a theme which sets breadcrumbs like this:

```
function mytheme_process_node(&$variables) {
    (....)
    drupal_set_breadcrumb($my_breadcrumbs_array);
}

```

This gets overwritten later by something else. I need a specific taxonomy value of the displayed node to set the breadcrumb, that's why I am using this hook. How to do it effectively? Perhaps there is a hook which is performed later and still has access to the node object?

# Answer
I normally stick that logic in `hook_preprocess_page()`, it runs late enough in the page build to not be overwritten by anything else.

You can still get access to the node object by using the `menu_get_object()` function:

```
function MYTHEME_preprocess_page(&$vars) {
  if ($node = menu_get_object()) {
    // We're on a node page...
    drupal_set_breadcrumb($my_breadcrumbs_array);
  }
}

```
> 7 votes

# Answer
There is also hook\_menu\_breadcrumb\_alter()

Besides, you can use one of the plenty of breadcrumb-customizing modules and *might* get what you want without custom code.
> 3 votes

---
Tags: 7, theming, breadcrumbs
---


# Question
Title: How can I get file field url in drupal 7 from views of its content type?
It has been a few days I'm trying to get the uploaded file urls in drupal7 (using default file filed in drupal content type) from a view. I must get this url in page which a view is embedded inside it, this view shows 10 items of its content type per page, how can I get the url of filefield?

should I use preprocess function or any thing else?

I have tried many ways suggested in many websites but I have failed. is there any straight forward solution?

# Answer
> 0 votes
change the Formatter of file to `URL to file` in views administrative menu and then by this code `strip_tags($fields['field_file']->content);` you will get the url

# Answer
> 6 votes
It's not really clear what you mean by 'access' in this context, but if you're looking to get the details for a file uploaded through a file field:

```
$node = node_load(1);
if ( ($field_items = field_get_items('node', $node, 'field_file')) ) {
  $file = file_load($field_items[0]['fid']);

  $uri = $file->uri;
  $external_url = file_create_url($uri);
}

```

Or to grab the external URL directly with an `EntityMetadataWrapper`:

```
$node = node_load(1);
$wrapper = entity_metadata_wrapper('node', $node);
$external_url = $wrapper->field_files[0]->file->url->value();

```

---
Tags: 7, theming, files
---


# Question
Title: Looking for exposed filter for private file name
We have a view for a type of node that includes a Private File.

We cannot see a way to add an exposed filter, such as "Contains any word", and have it filter based on the file's name.

Are we missing something obvious?

# Answer
Here's how to set that up:

1. Make sure you are not displaying teaser/full nodes. This works only for fields.
2. Under `Relationships` add your file field. You should select `Content: [field name] (field_field_name:fid)`.
3. Create new `Filter Criteria` and choose `File: Name`.
4. Choose appropriate operator and optionally expose it to the visitors.

Hope this helps.
> 5 votes

# Answer
you can take a look to https://drupal.org/project/file\_entity module: "This allows for additional information to be stored along with a media file such as Title, Description, Taxonomy References, Node References, Location, Date created, License information etc."

If you are not able to find a solution in this way, you can create your own filter views handler. In this case, it would be a filter handler.

https://api.drupal.org/api/views/handlers!views\_handler\_filter.inc/group/views\_filter\_handlers/7

https://drupal.org/node/1239866

Extending views functionallity to provide an approach to your problem (How to provide a custom option for an exposed filter in Views?)

Your "custom filter views handler" could get the fid of your file for each node from "field\_data\_field\_yourfieldname.field\_yourfieldname\_fid" and make a join with "file\_managed.fid".

In this way you can match the text introduced by the user with "file\_managed.filename" database field.

Hope this helps.
> 0 votes

---
Tags: views
---


title: Get gid of group node

text:
# Question
Title: Get gid of group node
How do I get (in PHP) the gid of a node that is a group?

The group\_audience field is present but empty, and I can't seem to populate it; presumably it is because that node is the only group, and it cannot itself be a member of the group it defines. (Why not is another issue that won't matter if I can just get the gid.)

# Answer
Note that the entity id is the gid in the current OG 2.x version(s) (there is some confusion around the change from earlier OG versions where GIDs were NOT entity ids)

From

> ... the group ID is the identifier of the entity. if i have a group which is a node the group ID will the be node ID. If i create a group which is a user the group ID will be the user ID and if i have a group which is a taxonomy term the group ID will the term ID.

Use og\_is\_group to determine if the node in question is acting as a group.
> 1 votes

---
Tags: organic-groups
---


# Question
Title: append values to drupal7 cck link field entry
I've got a question about the CCK link field.

I'm using the link field as a way to get a youtube video embedded onto a page and displayed through colorbox, but in order to make it work I have to include all the embed video information like size and iframe acceptance.

i.e. ?width=560&height=315&iframe=true

Ideally I'd love my users to just have to put the video link in and not worry about including the size specs.

is there any way i can append this kind of information to this field?

I'm using: D 7.23 CCK link mod 7.x-1.1

Thanks!

# Answer
> 1 votes
You can use the Media: Youtube module.

You would then create a file field with a Media file selector widget. Make sure you configure the field to use the Youtube URI schema.

You can configure the size of the video through the field display settings.

When you create a new node, you will need the share url, like http://youtu.be/n1yxNjU7u\_8 to embed it.

---
Tags: 7, entities, navigation
---


# Question
Title: how to retrieve password from within hook_user_presave()
I am trying to catch the inputed password on the user registration page from within the hook\_user\_presave(). I want to send this password out to an external database for storage. However, when I analyzed the $edit variable, I found that the password field was returning an encrypted password.

Is there any way for me to retrieve the actual password?

# Answer
> It us not advised not to use the user's password as a raw value, however if you still want to access the password field value in unencrypted form than try the following:

```
<?php
/**
 * Implements hook_form_alter().
 * Alters user_register_form.
 */
function MyModule_form_alter(&$form, $form_state, $form_id) {
  // Add the additional validation callback for the user registration form.
  if ($form_id == 'user_register_form') {
    $form['#validate'][] = 'MyModule_user_register_form_validate';
  }
}

// Callback function for Validation handler of user_register_form.
function MyModule_user_register_form_validate($form, &$form_state) {
  if (isset($form_state['values']['pass'])) {
    // Here you will get the value of password.
    $password = $form_state['values']['pass'];
  }
}
?>

```
> 4 votes

# Answer
You would need to modify the form and add another submit handler then use that. Once it's in Drupal it's 100% encrypted.

**BUT... you SHOULD NOT be sending peoples passwords to an external database in raw form. You should send the encrypted password if anything.**
> 2 votes

---
Tags: hooks, users
---


title: Grouping Content by Date in Views

text:
# Question
Title: Grouping Content by Date in Views
I'm trying to group content by date in views but instead of utilizing 'Fields' to stylize it, I'm trying to style using 'Content'

Here is an example of what I see right now:

```
Note Post Title

  This is a test comment 1
  John Doe
  Posted Date October 7, 2013 - 11:15 AM

  This is a test comment 2
  John Appleseed
  Posted Date October 7, 2013 - 11:20 AM

```

Here is what I'm trying to achieve:

```
October 7, 2013

   Note Post Title 1
     This is a test comment 1
     John Doe
     11:15 AM

     This is a test comment 2
     John Appleseed
     11:20 AM

```

# Answer
> 0 votes
For grouping the content by date field, you may try the following:

* Add one extra date field in the fields section. (This field will be used for grouping)
* In `Format` -\> `settings`, select that date field for grouping

---
Tags: views, nodes, datetime
---


# Question
Title: Mailchimp Newsletter block position in registration page in Drupal
I am just pulling my hair out for the last two days trying to figure this out but as a new user of Drupal I cannot find the option where to change it. I have installed Mailchimp module in my drupal website and I want to display the newsletter option in the user registration page. It display fine but not in the right position. For some reason the block appears between the firstname and lastname field. I want to place this under email address field above the captcha. Can anyone please help me. I have tried to many things and cleared the cache but no luck.

# Answer
> 1 votes
Ok, you'll need to do this with a custom module and use hook\_form\_alter and set the weight of the mailchimp list properly.

```
function MODULE_form_alter(&$form, &$form_state, $form_id)
{
    if ($form_id == "user_register_form")
    {
        //print_r($form);
        //first name field - use proper name
        $form["first_name"]["#weight"]      = 1;
        //last name field - use proper name
        $form["last_name"]["#weight"]       = 2;
        //email field - use proper name
        $form["email"]["#weight"]           = 3;

        $form["mailchimp_lists"]["#weight"] = 4;
    }
}

```

You should use `print_r($form);` or `drupal_set_message(print_r($form,true));` to inspect the structure of your `$form` array and get out the proper names of your fields to use in the hook.

---
Tags: 7, users, emails
---


# Question
Title: How to copy data from Profile2 form to a new node using Rules.
I'll try to explain what I need to achieve:

1. User submits profile data during the registration proces (using Profile2 module).
2. Rules trigger event "After saving a new user account" that creates a new node, and then copies Profile 2 data fields to a new node.

Any ideas how can I get this working? Guess I need to use Action "Create a new entity" but not sure how can I pull data from Profile 2 and then save it to a new node?

Thanks a bunch!

# Answer
Why do you want this through Rules?..according to me a simple submit handler, grabbing the data on submit and creating a node programatically will be a much better approach. I can provide you direction on this if you let me know you want to go with this approach.

Update:

Here is my suggested workflow:

1. Use hook\_user\_save() to grab the submitted profile field values. All the profiles2 field you add, will be available in the user object.
2. Next in the content type you want to save the values, create proper fields so that you can map and store data.
3. you can look up in google to see how you can progmatically create a node. So you can grab the required values, and map them to appropriate fields you added to the node and then save the node.

Just a thought, I am really curious why are you trying to do this?
> 0 votes

---
Tags: nodes, rules, users
---


# Question
Title: how to get weight or delta of current field collection item that is being computed
Is it possible to get weight(order index) of multi field "field collection".This weight is needed inside computed field which is inside field collection.I tried the following but it returns empty

```
$wrapper = entity_metadata_wrapper('field_collection_item', $entity);
$instance = field_read_instance('field_collection_item',$wrapper, 'bundle_name');
dpm($instance['widget']['weight']);

```

Here is the structure

**main\_content**-contains field collection (multi value)
------**field collection(s)**-contains 1 text field and 1 computed field
------|----item 0
------|-------|-------computed\_field \<---here how to get weight of field collection item ie 0
------|----item 1
------|-------|-------computed\_field \<---here how to get weight of field collection item ie 1
------|----item 2
------|-------|-------computed\_field
------|----item n
------|-------|-------computed\_field

# Answer
I was searching in wrong path :( this is found at

http://drupalcontrib.org/api/drupal/contributions!field\_collection!field\_collection.module/class/FieldCollectionItemEntity/7

code for getting delta is

```
$wrapper = entity_metadata_wrapper('field_collection_item', $entity);
$cur_delta=$wrapper->delta();

```
> 3 votes

---
Tags: entities
---


title: User can add field value

text:
# Question
Title: User can add field value
Can anyone give me some advice/tips on how to get this working? I have a content type called "reviews", and in that i have two fields, called "pros" and "cons". Both fields have values defined in the Drupal admin interface.

In the front-end of the site, users can add new reviews and select values from the field list, until here no problem, everything work, but now i need to allow users (the registered users) to add new values to the fields (pros & cons).

Beside that, the values submitted by the users that don't exists yet in the database, must be approved by the admin before shows on the front-end.

Any suggestions for resolving this 2 questions?

Thanks in advance for your help.

# Answer
I will try and provide you a general direction which I think might serve you well:

1. Create a text field, with label something like this "Please add tags of your choice if you dont find adequate options".(purpose is explanatory from the label)
2. Create a content type, "Proposed Taxonomy Terms". Let it have only title and body field.
3. Now on saving a node of the content type in which we had the suggestion field, grab the value of the proposed taxonomy terms from it, create a node of type "Proposed taxonomy term" and clear the value of the field in the first content type.
4. Now the nodes in the content type "Proposed taxonomy Term" will be your basis which you need to set up such moderation. it will initially remain unpublished. Upon validation, write custom code, to grab the title on its save and create a taxonomy term in the vocabulary(which was used as term referance field in the first content type), and delete the node (or you may choose to keep it).

So next time when user tries to create the node of the first content type, they will have it as an option. this is a complex workflow. The logic parts you can do custom code better, employing drupal hooks or you may choose to use rules module (not sure it will serve the purpose exactly though).

Hope this long answer did not confuse you.
> 1 votes

---
Tags: entities, nodes, users
---


# Question
Title: Different placement/alignment for image (field) in teaser and Full content view
1. i have created a content type 'Article' which has a image field.
2. Both the teaser and Full view use the image field.(Default Drupal views for content)
3. Now the problem is this image field has the same CSS class.
4. So both the teaser view and full view get the same properties.
5. But i want the image in teaser view to align/float to left of teaser content, but to show in the top center region in the full view.
6. Since the CSS class is same for both view i can not achieve my goal ( **point 5**)

So please suggest me a way to achieve **point 5** without creating a new home page view in 'Views'

# Answer
> 1 votes
Just pick the field with right parent

on node teaser view - you will find class as "node-teaser"

and on full node view - you will find class as "node-full"

so its just matter of picking field with parent while applying the css. OR also you can have a separate template for your node-teaser view, check this link

---
Tags: media, nodes
---


# Question
Title: Show a view of Related Terms to a given Taxonomy term
How can I create a view and show only taxonomy terms related to the term you are currently viewing (term id in URL)? I have tried a handful of relationship and argument configurations, but can't seem to simply list the related terms to the term being viewed.

Edit: I have related the terms through the core taxonomy interface.

# Answer
I have done the same thing through Panels. I was stuck with views for a long time. All you have to do is to override the "Taxonomy Term Template" in panels. Add a new Variant with settings of your choice (default ones would be fine too). Go to 'content' section and add new one. Choose 'list of related terms' and inside it you would find the related terms you need. Make sure you give it a valid path and there you have it!

I don't know how this could be done in views but for me this is more than fine.. :)
> 1 votes

# Answer
I assume by related that you want parent, sibling and child relationships.

**Parent:** A view to identify a parent can be provided by a view page defined with a path such as category/% where the % wildcard is a term's name. A relationship should be defined for the taxonomy term:parent. The view should expose whatever fields you want such as the term name, but leave the relationship dropdown box set to 'Do not use a relationship'. Set a contextual relationship for the term name and set the relationship dropdown as 'Parent'. (You must also set validation to a taxonomy term name so that the URL wildcard name will be interpreted correctly.

**Children:** I answered this pretty thoroughly in this post.

**Siblings:** I worked at this one for a while before finding this post which suggests that it is not possible without the aid of Page manager. Sorry, but I was not able to find a way to do it with views alone.

My post uses D7 a V3 so there will be some differences in the UI to execute this, but I believe that the settings and basic configuration are the same with the exception that conceptual filters = arguments.
> 1 votes

# Answer
I know this question is older but I needed to be able to search for content via Views that showed results including Term Parents, Children & Siblings (All optionally depending on the view). I have created a module that adds some Views Filters for Term Families and also for restricting Search options to Terms on content (optionally allows adding related terms to the options):

http://drupal.org/sandbox/jpstrikesback/1844058

I'm not sure if you need to exclude the searched term or not, so just so you aware that is not in the feature set.
> 1 votes

# Answer
I think this can be done with 'entity references' (D7).

My goal was to relate a term ('steps') to another term ('goals'), and to have the 'steps' appear on the 'goal' page in a block.

* Download entity reference module
* Add an 'entity reference' field to the term (in my case, I added a entity reference field for 'goals')
* Add a 'taxonomy term' type view
* Add a relationship for 'entity reference' and the taxonomy field you would like to match
* Add a contextual filter 'taxonomy term: term id', add the previously created relationship, and make the default action to take term id from url.
> 0 votes

---
Tags: views, 6, taxonomy-terms
---


# Question
Title: How do I remove the colon from a form element's title - D7?
I've hunted high and low for what generates this colon. I've looked in the`theme_form_element_label` function and at the `#title_display` attribute in the form api, but I cannot see how to override it. It must come from somewhere? Thanks.

# Answer
> 1 votes
Well easiest solution is to use this module . But I am not sure you would be interested to install a module for this small task.

If not you need to do the following steps:

1. You need to copy the field.tpl.php to your theme folder.
2. Now in the template file you can find the code that outputs the colon.
3. Please remember to clear the cache.

---
Tags: forms
---


# Question
Title: Automatically load the URL from link field into a script
I have a content type "Team" to add team members. In this content type I have a link field (called "LinkedIn") which holds the URL to the team member's LinkedIn page. What I want is to use the URL from the link field and use it with a script (provided by LinkedIn). The script looks like this:

```
<script src="http://platform.linkedin.com/in.js" type="text/javascript"></script>
<script type="IN/MemberProfile" data-id="linkedin-profile-link.com" data-format="hover"></script>

```

I have created a simple text field for the content type "Team" and in a team member node of that content type I copied above code into it and inserted the URL from the "LinkedIn" link field. This works but I would have to edit more 100 team member pages.

How could I automatically load the URL from the "LinkedIn" link field into this script (it needs to be added into data-id="link comes here") and display on every team member page? Can this be done with Display Suite? Or do I need to write a module?

# Answer
You could use a field template in your theme.

Call it something like `field--field-linkedin-url.tpl.php` (whatever you have called your field. I'm assuming `field_linkedin_url` for my example. Notice the \_'s are converted to -'s in the file name.

In the template put the following html:

```
<script src="http://platform.linkedin.com/in.js" type="text/javascript"></script>
<script type="IN/MemberProfile" data-id="<?php print render($items); ?>" data-format="hover"></script>

```

It shows something like this:
> 2 votes

---
Tags: entities, display-suite
---


# Question
Title: Not showing clickable links in search results
I'm fairly new to Drupal but have gotten a hang of installing modules and setting up there configuration pages. The company site i'm working on is running on Drupal 7.1.4 and is using Node Search to look through books that they have created for documentation of their products. The problem with the node search was the lack of proper phrase search and partial words not being found. I have Search API, Search Facets, Search Pages and Fuzzy Search modules installed and it appears to be working but not as expected.

Unfortunately the results come back as unclickable links, with some results coming back as text only excerpts of certain books and most results coming back as what appears to be just the author name with a time stamp of the books that are available.

I'm having a bit of trouble finding a way to display these search results as proper links and text excerpts with highlighted search terms.

Was hoping someone here would be able to assist.

# Answer
> 0 votes
A couple of possibilities. Is the site using Search API views? If so perhaps there is a search results view that you can adjust.

Another idea might be that someone has customized the search results templates in the theme to be unlinked or otherwise weird. Check in your theme folder for any search related templates.

---
Tags: search
---


# Question
Title: how to display all content for the people table
How does one display all the data in the people table in a SQL or other statement? I would like to get a complete listing of the table(s).

# Answer
There is no table `{people}` in the database. However, the way I understand this question, you want to display everything that is recorded about all user entities (i.e. you want the list of user entities that is shown under *People* in the admin interface expanded to include *all* the fields attached to such entities).

In that case, you can install the Views project and enable the **Views** and **Views UI** modules (both part of the Views project). The recipe below assumes you're using Views 3 on Drupal 7. Older versions are different.

Navigate to *Home » Administration » Structure » Views* and click *Add a new view*. Give the view the name "Users", and select "Users" from the *Show* pull down menu. Click *Save & Exit*. This will give you a page view showing all users, but no fields.

Now, return to *Home » Administration » Structure » Views*, locate the view named "Users", and click *Edit*.

Next, locate the "Fields" widget, and click *Add*. Filter on "User". This will show *all* fields defined for the user entity (except `pass`), with a checkbox for each. Check all boxes and click *Apply (all displays)*. Now you've get to configure how to show each of the fields. You can of course do a lot of fine tuning here, but I find it better to do that later, after the view is fully populated with fields. So just click *Apply (all displays)* to each of these. AFAIK, this gives you access to *all* the fields in the user entity except `pass` (which holds the user's hashed password, and is excluded for security purposes).

After you've added all, there will be a preview at the bottom of the page. At this stage, the listing will not be pretty, but you can fine-tune how this appears later, by editing the format of the view.

When done editing, remember to click *Save* (near top of screen) to save the view.

If your objective is to export this data, there are deveral modules let you export lists produced by Views. One of these is Views Data Export.
> 1 votes

---
Tags: users
---


# Question
Title: Is it possible to make a particular column in a tablefield readonly?
Since in my case I have three columns A, B and C. A and B holds a data and C stores the summation of those data. I wrote a custom javascript to do that and also tried to make column C readonly through javascript but the problem is while in a table rebuild the data in column C clears out but if I didn't apply readonly on column C then data remains. Any suggestions in this case will be highly appreciated.

# Answer
How are you applying the readonly to the fields?

You need to use the FAPI '#attributes' property to set readonly like this:

```
'#attributes' => array(
    'readonly'=>'readonly',
);

```

You need to alter the form through hook\_form\_alter and addd the above property to the textfield you want readonly.
> 0 votes

---
Tags: entities
---


# Question
Title: How to convert an HTML website with stylesheets to Drupal 7 nodes?
I have a question. How can I convert a site with a few stylesheets.css file for the layout into Drupal 7. I'm not so worried about the content of the site, that is not so much. But I would like the layout to be converted to a drupal 7 theme. How can I do that whitout making a hole new theme my shelf. I'm just a beginner with Drupal and want a quick resulte.

Thank you for your help.

# Answer
> 1 votes
What you are looking for to avoid creating a whole theme from scratch is known as a starter theme. Starter themes are special themes designed to *not* work as themes by themselves, only to be used as foundations for a theme you build on top of them (the latter is known in Drupal-speak as a sub-theme). I.e. starter themes are theme framworks that "reset" the CSS, so that you can rebuild the CSS without having to think about inherited styling.

Pick the starter theme that looks like it best suites your needs, and build on that.

As for stater themes: Zen is the one that most people use. The other one I will recommend is Basic. It is a stripped down fork of Zen. As a bonus, both are responsive by default.

# Answer
> 0 votes
Hi Welcome to Drupal stackexchange

If you want to get started on theming.

You should Go after some of the famous base themes like Fusion, Zen, Omega

I see fusion as very easy.

Fusion handbook

> Installing Fusion
>
> If you've ever installed a Drupal theme before, you'll find that installing Fusion is just as easy. And if you haven't, don't worry: You'll still be fine! There are five simple steps:
>
> Download the Skinr module (the 1.x branch, as of March 2010), which gives you access to many of Fusion's unique features Download Fusion Enable the Skinr module Enable and set a Fusion subtheme (such as Acquia Prosper or the included Fusion Starter) as your site's default theme Give yourself permission to access Skinr's controls If you’re not the site's "super user" (that is, the person holding the first account created when you installed Drupal), you (or someone with sufficient permissions) need to explicitly allow you to use Skinr's features. Go to the user permissions page (e.g. http://www.example.com/admin/user/permissions), scroll down to the "skinr module" section, and check all boxes under your user role.

Here is a how to in creating a Fusion Sub theme

---
Tags: theming
---


title: Edit the default front page

text:
# Question
Title: Edit the default front page
One of my colleagues setup a Drupal front page for a website. He has left now. I was given access but I am not able to edit the front page. I can edit every other page, but not the front page.

I don't want to replace the front page with another page. I know how to do that by promoting the page. I want to edit the content of the front page I already have. It has some RSS feeds coming in, a presentation like thing and some pictures. I would like to edit those.

I googled but I cannot find anything substantial. Can anyone please help? I am a noob when it comes to Drupal, so apologies in advance!

# Answer
Even if it is the front page is located at the default `mysite.com/node`, there are dozen's of way of populating it in Drupal with stuff that aren't nodes.

Have you looked if blocks are used to populate the front page? To check, navigate to *Home » Administration » Structure » Blocks*, and examine the configuration of the blocks that are enabled. The RSS feed, for instance, is probably a block. You can edit the content of blocks, or moving them to region `- None -` to disable.

One problem here is that we don't know whether you predecessor has done this the right way or his *own* way. For all we know, he may have hacked the core or theme template directly. Things also depends on version and theme. You haven't told us what version of Drupal you're running or what theme the site uses. To answer this question with more accuracy than this general answer, all this must be known by the person writing the answer.

Three things to try:

1. If you're using Drupal 6, navigate to *Home › Administer › Site configuration › Site information*. See if there is any contents on that page that account for material on the front page. If so, you may now edit it.
2. Change the site's theme. In particular, get rid of any sub-themes and revert to the default theme for the Drupal version you're running (depends on version). If you're already running the default, install the admin theme as default (depends on version). If the content on the front page disappear, it's in the theme templates. Update your question with this information, and ask how to fix it. I (and others) will then update our answers.
3. Back up your configuration (Important!) Upgrade Drupal to the newest major version of the branch you're at (depends on version). If it is already the latest major version, upgrade anyway. If the content on the front page disappear, your predecessor has hacked the core. Restore from backup, and hire a consultant.
> 2 votes

# Answer
Drupal comes with a default front page at /node that shows a list of the most recent content. There are a bunch of different ways this could have been overridden.

One place to look is whether there is a view set up to override the default list.

Another idea might be that the page has been created using some custom template in your theme. Look for a file called page-front.tpl.php in your theme folder.
> 0 votes

---
Tags: nodes
---


title: Hide the Password tips

text:
# Question
Title: Hide the Password tips
How can I hide those password tips??? You know,when the enduser tries toregister and as soon as he clicks on the password field the following messages appear:

> ```
> To make your password stronger:
> •Make it at least 6 characters
> •Add lowercase letters
> •Add uppercase letters
> •Add numbers
> •Add punctuation
>
> ```

Simple CSS "display:none" won't do the trick here.

I still want to keep the password strength meter.Just need to get rid of the Password tips messages.

# Answer
You can do it via CSS, just add the `!important`:

```
.password-suggestions {
  display: none!important;
}

```

Another option is to copy the `modules/user/user.js` file to your theme, add it to `.info` file and edit it the way you want.
> 6 votes

---
Tags: users
---


# Question
Title: Subtract UserPoints from all taxonomy terms upon purchase?
OK So i was wondering if someone could point me in the right direction. Currently I'm running User Points Module with UberCart in order to purchase items with currency or use points for purchases. Now i've managed to get the transaction to work as needed except for one small thing. The Ubercart API only allows me to subtract the purchase points from a single category like "General". Id like to subtract the points used to buy the product from ALL the categories the use has points in. Does anybody know a way this can be done?

# Answer
> 1 votes
You have few options that depend on the number of userpoints categories and the way you want to do it (w or w/o code):

**Option 1:** Create separate actions for each userpoint category within Ubercart.

**Option 2:** Enter custom PHP code and do the following:

* Load userpoints dictionary - `userpoints_get_vid()`
* Loop through all terms in it and subtract the points.

Sample code:

```
$userpoints_vid = userpoints_get_vid();
$userpoints_terms = taxonomy_get_tree($userpoints_vid);
foreach ($userpoints_terms as $term) {
  // Build the params for this transaction.
  $params = array(
    'points' => -100,
    'moderate' => FALSE,
    'term_id' => $term->tid,
    'entity_id' => $order->order_id,
    'entity_type' => 'order',
  );
  // Subtract the points. This will call automatically all UP hooks.
  userpoints_userpointsapi($params);
}

```

**Option 3:** You could also create a Rules action from the code above that will accept `$order` as an argument. This will take slightly more time, but is the right way to do things.

---
Tags: 7, ubercart, userpoints
---


# Question
Title: How to obtain a list of JS files from enabled modules, or expose such list from a theme as library?
I'm in the process of extending jQuery Multi module. Libraries API libraries was built in, I have already added support for JavaScript libraries provided by modules, so with minimal cooperation on the side of modules' authors I have that part covered. Now time to add **themes** to the list - and I'm stuck.

I found no way to make a theme use `hook_library()` and by the API docs it's a module hook, so I can't use method I used for modules.

I can use `list_themes()` to list themes, but how to see a JS files?

# Answer
`list_themes()` returns an array of objects:

> The keys are the themes' machine names and the values are objects having the following properties:
>
> * **scripts**: An associative array of JavaScripts, using the filename as key and the complete filepath as value. Not set if no scripts are defined in the .info file.
> 0 votes

---
Tags: javascript, theming
---


# Question
Title: Can we create a feature for the changes in webform by using feature module?
I am unable to create a feature for the changes in webform on development site to be used on production site by using feature module.Is it possible ?

# Answer
Features does not give you the power to import/export the webform created.

You could use the Webform Share module.

For more details you could read the README.txt file of this module.
> 2 votes

---
Tags: webforms, features
---


# Question
Title: How to access remote index in search_api?
I have two drupal installations, one instance contains **data** like entities. The other one access this entities with service-calls and display the website.

I would like to make the entities searchable for users with search\_api(\_solr) and created an index in the **data** server which contains the entities.

Now.. How can I access this index from the other drupal installation? I found the services\_search\_api module, but there is only a DEV Version :-(

Thank you in advance for your help.

# Answer
Using the services\_search\_api Module is the right way, but you have to apply patches from the following Issues:

* Support keys: provide Key Field for searching Solr Indexes. See Comment #1
* Undefined functions: add required functions from previous Services Module. See Comment #4
> 1 votes

---
Tags: search
---


# Question
Title: Is there a Drupal module that implements a (+/-) button with a counter textbox at the side?
Can you implement a (+/-) button with a counter textbox at the side with Drupal like a shown below?

A very simple way of implementing this, like using an existing module, is much welcome. I am also open for answers implementating this using hard coded scripts.

# Answer
> 3 votes
There is already a module that gives you a vote up/down button, just like the one we have here on SE: https://drupal.org/project/vote\_up\_down.

> Allows votes on some drupal entities and provides the base for implementing votes on other entities.

It is still under dev for Drupal 7, but IMHO quite usable. If you find any problems, it will probably be less work to help the developers fix those, compared to reinventing the wheel.

# Answer
> 2 votes
In your existing form(or if one does not exist, you need to create it), add a textfield like this, with some associated markup:

```
$form['counter'] = array(
  '#type' => 'textfield',
  '#title' => t('Counter value'),
  '#default_value' => YOUR DEFAULT VALUE CALCULATED BY REQUIRED LOGIC GOES HERE, MAKE SURE ITS INTEGER,
  '#size' => 30,
  '#maxlength' => 128,
  '#attributes' => array('class' => 'counter-textfield'),
  '#suffix' => '<div class="counter-wrapper"><div class="vote-up"></div><div class="vote-down"></div></div>',
);

```

Now in JS file, apply this code:

```
Drupal.behaviors.updown = { attach: function (context, settings) {
      $('.vote-up').click(function() {
        var existing = $('.counter-textfield input').val();
        var new_count = parseInt(existing) + parseInt(1);
        if(new_count < 0) {
          new_count = 0;
        }
        $('.counter-textfield input').val(new_count);
      });

      $('.vote-down').click(function() {
        var existing = $('.counter-textfield input').val();
        var new_count = parseInt(existing) - parseInt(1);
        if(new_count < 0) {
          new_count = 0;
        }
        $('.counter-textfield input').val(new_count);
      });
    }
};

```

---
Tags: forms
---


# Question
Title: Will assigning a name string to user #0 do any harm?
By default, the `{users}.name` set for the Anonymous "user" (i.e. `uid=0`) is `""` (empty) in Drupal 7.

This design choice is inconvenient for me in a module I'm maintaining (see issue #2099123 for background).

For instance, I need "Anonymous" to be available when there is an autocomplete form field that accepts a user name. Also, when I print out lists of users stored as serialized data in blobs, I want "Anonymous" to appear if there is a `uid=0` somewhere in the list.

I've tried to use `hook_username_alter()`, but it has no impact on autocomplete widgets or serialized data.

I've looked for an API function to change the `{users}.name` field, and not found it. I know there is a Drupal rule of thumb that say that updating another module's tables directly (i.e. without going through that module's API) is *bad*.

However, the solution I currently favour is to add a form to the admin interface that when clicked, does the following if the `name` field for `uid=0` is `""`. (It does nothing if this field is not empty.)

```
$query = db_update('users')
  ->fields(array(
    'name' => 'Anonymous',
  ))
  ->condition('uid', 0)
  ->execute();

```

I've tested this solution, and it solves the problem.

I've verified that leaving the author field empty to assign node ownership to user #0 (as suggested by the the hint "*Leave blank for Anonymous.*") still works after this database update.

I understand that the value of `{variable}.anonymous` may not be "Anonymous", but believe I can live with that.

Question 1: Will assigning a string value to this particular field if it is empty have potential to break something on a site that installs my module?

Question 2: Is there a more Drupalishly *right* way to do this? (I.e. a way where I do not have to interfere with a piece of data that rightfully belongs to the **user** module.)

# Answer
For the record: I've done it. One issue immediately popped up during testing: If a user named "Anonymous" already existed, creation would fail (obviously). After modifying the routine to check for existing users before updating, it worked.

Been running on several production sites for a week, and no problems so far. I'll report here if any problems occur.
> 1 votes

---
Tags: users, database
---


# Question
Title: "The website encountered an unexpected error" right after login in
So I recently bought a very cheap host just to run a not-important website on it. but when I login to admin, it shows

> The website encountered an unexpected error, Please try again later.

message, since its a shared host I checked into my cpanel for error logs, there were just two errors regarding my `.htaccess` files (in root and also sites/default/files) regarding `FollowSymLinks` not being available here, so I commented out those lines and all error logs now are gone. but still I get the error message after I try to login.

I contacted the webmaster regarding `FollowSymLinks` and he said we are using `SymLinksIfOwnerMatch` .

however with or withought FollowSymLinks I still get the error message while my error logs in cpanel is empty.

Any Ideas or hints?

# Answer
> 1 votes
If you are not able to login then you can try checking the logged error directly looking into your database watchdog table.

In your case:As per our chat you were missing watchdog table so importing the database back helped you.

---
Tags: 7
---


title: Context Filter with Path Alias in URL

text:
# Question
Title: Context Filter with Path Alias in URL
Quick Summary: how do I pass a alias in a URL to a view's context filter, when that view is located somewhere in the site.

I've read dozens of similar articles, but nothing that directly makes this clear for me, so if someone has some insight, I'd be grateful.

I have a Content Type: "Artists" with an pathauto alias as so: artists/picasso I have a Content Type: Artwork with an entity reference to artists. A given Artwork might have an alias as such: artwork/minotaur (which is a work referencing picasso)

What I want to do is create a view, have it live here: (artwork/artists/picasso) that shows all Artwork by Picasso.

My trouble is: I can get the view set up, but it only displays correctly if I have the NiD in the URL path. For example: /artwork/artists/1 (with 1 being the Nid for the Picasso node)

How can I get the view to accept "picasso" as an argument to use in the location I want (artwork/artists/) for instance.

I have no trouble if I attach a view to the artists/picasso page as a block. I can show all works by him there, but I want to show works by him in another location.

It seems like this should be obvious, but I cannot find a clear answer as to how to implement. Your help is greatly appreciated."

# Answer
A more robust solution that avoids needing to ensure unique node titles would be to write a custom Views Plugin Argument Validator that converts a contextual filter to node ID.

In your case in which you want to validate node path aliases, you would want to extend the class `views_plugin_argument_validate_node` in views/modules/node/views\_plugin\_argument\_validate\_node.inc to overwrite `options_form()` to provide your own option. You probably want something like this:

```
function options_form(&$form, &$form_state) {
  parent::options_form(&$form, &$form_state);
  $form['type'] = array(
    '#type' => 'select',
    '#title' => t('Filter value type'),
    '#options' => array(
      'convert_path_alias' => t('Node path alias converted to Node ID'),
    ),
    '#default_value' => $this->options['type'],
  );
}

```

You would also need to overwrite `validate_argument()` to convert the argument (path alias) passed into the function into a node nid, set `$this->argument->argument` to the converted node nid, and return TRUE if the path alias was successfully converted.
> 1 votes

# Answer
This can be done with hook\_views\_query\_alter(). The contextual filters are nothing but where conditions (technically in MySql Slang). So you can implement the mentioned hook and alter the where condition.

But How to get the nid from alias?

Use node\_get\_object() inside the hook\_views\_query\_alter, you will get the nid. This can be set as the where condition.

Hope this helps you out.
> 1 votes

---
Tags: views, entities, path-aliases
---


# Question
Title: How to use $form['#action'] in Views PHP field
I print the comment form for each node in my view with the Views PHP module. The URL of the view is user/%/selection, and the code I am using is the following one.

```
$comment = new stdClass;
$comment->nid = $row->nid;
$form = drupal_get_form('comment_node_MYCONTENTTYPE_form', $comment);
$form['#action'] = url('user/'.$row->uid.'/selection');
print render($form);

```

When the form is submitted, I get /node/nid#comment-17 as URL.

Could you explain why `$form['#action']` doesn't work?

# Answer
Instead of this method, why cannot a new submit handler be written? so that you can use drupal\_goto there and redirect.
> 0 votes

---
Tags: views, forms, comments
---


# Question
Title: Jquery version issues: Flexslider doesn't works only with 1.5 and bootstrap needs 1.8+
This is my site: investassure and I tried incorporating the code for '`button dropdown`' from bootstrap. This works only with jquery-1.8+ but the flexslider I used works ONLY with 1.5. As a result, I'm getting this error:

```
 Uncaught TypeError: Object [object Object] has no method 'on'

```

I tried using jquery\_update, didn't work. There is only one version added on the page right now, which is 1.5. I didn't find a version of flexslider which works with version 1.7+. What else can I do?

# Answer
I recommend the jQuery Multi module.

It allows you to use the default drupal jQuery version for most of you site, and use newer versions of jQuery just for plugins that require it.

It gives an administration page where you can choose which libraries to load using the newer jQuery.

It also has hooks you can use to tell it to load your libraries using different jQuery versions.

If you are writing custom js it also namespaces the jquery versions so you can do something like:

```
(function ($) {
  // All your code here
})(jq172);

```

That is how the module would namespace jQuery 1.7.2 and you can load your scripts like that to use the newer versions.

One thing to note is that if your plugins with new jQuery require things like jquery UI, jquery.once etc., that drupal core uses already, you have to make sure they are added a second time, so they are added to the normal drupal jquery and the newer one.
> 1 votes

---
Tags: javascript
---


# Question
Title: How can I add a link to show/hide threaded comments?
I've enabled threaded comments in the comment settings on my Drupal 7 site. Now, on every comment that has threaded comments beneath it, I'd like to add a link (in the same place as the reply/edit/delete links) that enables users to toggle the display of the threaded comments beneath it -- a show/hide replies link.

# Answer
You can do something like this:

In your theme's template.php file:

```
/**
 * Override or insert variables into the comment wrapper templates.
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("comment" in this case.)
 */
function THEMENAME_preprocess_comment_wrapper(&$variables, $hook) {
  // Add jQuery UI accordian to hide the comments in.
  // It is already added in preprocess node but it is safer to also have it here
  // and doens't add much overhead as drupal will only add it once.
  drupal_add_library('system', 'ui.accordion');
  // Add some custom js to collapse comments.
  drupal_add_js(path_to_theme() . '/js/collapsi-comments.js');
}

```

In collapsi-comments.js (in this case it is in a folder called "js" in your theme.

```
(function($){
  Drupal.behaviors.collapsiComments = {
    attach: function(context, settings) {
      $('.comment-form-wrapper.accordion').accordion({
        collapsible: true,
        autoHeight: false,
        active: false,
        header: 'h2.title.comment-form'
      });
    }
  };
}(jQuery));

```

In your comment-wrapper.tpl.php in your theme wrap the comment form in a wrapper div like this (if your theme doesn't have one and you have a base theme that does, copy it from the base theme and modify it, otherwise copy from the comment module and modify it):

```
<?php if ($comment_form): ?>
  <div class="comment-form-wrapper accordion">
    <h2 class="title comment-form"><?php print t('Add new comment'); ?></h2>
    <?php print $comment_form; ?>
  </div>
<?php endif; ?>

```
> 1 votes

---
Tags: 7, theming, comments
---


# Question
Title: why &drupal_static is getting used with refernce?
I am going through different modules and I found this &drupal\_static function but exactly dont know why is getting used can any one please explain what is the purpose ?

# Answer
> 2 votes
## function drupal\_static

> Provides central static variable storage.
>
> All functions requiring a static variable to persist or cache data within a single page request are encouraged to use this function unless it is absolutely certain that the static variable will not need to be reset during the page request. By centralizing static variable storage through this function, other functions can rely on a consistent API for resetting any other function's static variables.

More with examples: https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/drupal\_static/7

---
Tags: 7
---


title: block user by sql query

text:
# Question
Title: block user by sql query
I wanted to block a bulk amount of users of my site. I was thinking to do it by firing a sql query and turning off the status field of users directory.

So is it safe to fire such sql or is there any otherfunction which does that?

My site is still in drupal 6.

Tks Vil

# Answer
If not Views Bulk Operations as mentioned in the comment above by arpitr there seems to be one function from the core users module which appears to be of the purpose for the same. The User module's `hook_user_operations` for block operation namely `user_user_operations_block` would be it to answer your query and should provide you a drupal code way of doing it.

```
function user_user_operations_block($accounts) {
  foreach ($accounts as $uid) {
    $account = user_load(array('uid' => (int) $uid));
    // Skip blocking user if they are already blocked.
    if ($account !== FALSE && $account->status == 1) {
      user_save($account, array('status' => 0));
    }
  }
}

```

Essentially it loads the user account and makes call to `user_save` with the status as 0. If your implementation is to block users with custom code based on a specific logic, you could do the same or perhaps consider invoking the user module's hook\_user\_operations for block operation with the desired input though I haven't done something similar. Doing so would prevent you writing your own update query. Hope that helps.
> 0 votes

---
Tags: 6, users
---


title: get path of an uploaded file

text:
# Question
Title: get path of an uploaded file
This is my form to upload a photo

```
 $form['Background_image'] = array(
 '#type' => 'managed_file',
 '#title' => t('Choose a background image'),
 '#description' => t('Click "Browse..." to select an image to upload.'),
 '#required' => TRUE,
 '#upload_validators' => array('file_validate_extensions' => array('jpeg jpg png gif')),
'#upload_location' => 'public://backgroundimage/',
 '#default_value' => $this->options['Background_image'],

);

```

I tried this function that get the current uploaded image and return its path, but still not working: what is missing:

```
function image_path()
  {
   $f = file_load($this->options['Background_image']);
  //this too is not working:
  //$f = file_load($form_state['values']['Background_image']);
   $url_image = file_create_url($f->uri);
   print_r($url_image);
   return ($url_image);
  }

```

# Answer
> 0 votes
$this is surprising in your form! I am not sure but do not consider $this as reference of current uploaded file,if the code you have shared is complete code then if you try to look inside dpm($this) , you will get your answer why file is not loading. check this link, it explains how to create custom upload form.

the use of `file_create_url()` is appropriate to get file url from uri,so I am sharing the submit handler changed codes from reference link the submit handler showing use of

```
function import_form_submit(&$form, &$form_state) {
  // Load the file.
  $file = file_load($form_state['values']['file_fid']);
  // Change status to permanent.
  $file->status = FILE_STATUS_PERMANENT;
  // Save.
  $uploaded = file_save($file);
  if ($uploaded == TRUE) {
    drupal_set_message(t('The file has been uploaded.'));
    dpm(file_create_url($file->uri));
  }
  else {
    drupal_set_message(t('The file could not be uploaded. Please contact the site administrator.'), 'error');
  }

}

```

# Answer
> 0 votes
In your submit handler of your form, you should be able to retrieve the `fid` of the uploaded file / image. By using this `fid`, you can load the file and work with that object.

```
function YOUR_MODULE_FORM_NAME_submit($form, &$form_state)
{
    $fid = $form_state['values']['Background_image'];

    if ($fid !== 0) {
        // Retrieve image URL
        $image_url = YOUR_MODULE_get_file_url(file_load($fid));
    }
}

function YOUR_MODULE_get_file_url($file)
{
    if (!$file) {
        // File not found
        return false;
    }

    // Return URL from a give file URI
    return file_create_url($file->uri);
}

```

---
Tags: forms, files
---


# Question
Title: Colorbox trigger builds clunky html instead of array
There is this view of which I configured the fields as follows:

**Gallery images:** exclude from display \- *Background: in cck, this is a separate image field with multiple values called 'Gallery images'*

**Title:** default

**Custom text:**
\- Exclude from display \- No results behavior: Hide if empty `checked` \+ Hide rewriting if empty `checked`

**Colorbox trigger:** \- trigger field: custom text \- popup: `[field_project_gallery_images]` \- No results behavior: Hide if empty `checked` \+ Hide rewriting if empty `checked`

This works nicely in itself, colorbox shows a nice slideshow after clicking on the custom text. The problem is that the colorbox trigger should only be output if there are actually images uploaded to the gallery images field. I other words, *Hide rewriting if empty* checked leaves me with no success.

Which isn't a surprise when `dpm($fields)`. It shows the gallery images field as one chunk of HTML entirely instead of an array. `dpm($fields)` output comes down to the following if that makes sense:

```
    <?php

$fields['colorobox']['content']['<span class="field-content"><a href="/en?width=100%25&height=100%25&inline=true#colorbox-inline-3" class="colorbox-inline" rel="">Meer foto's</a><div style="display: none;"><div id="colorbox-inline-3"><div id="field-slideshow-3-wrapper" class="field-slideshow-wrapper"> <div class="field-slideshow field-slideshow-3 effect-fade timeout-0 with-pager with-controls" style="width:680px; height:380px"> <div class="field-slideshow-slide field-slideshow-slide-1 even first"> <img class="field-slideshow-image field-slideshow-image-1" typeof="foaf:Image" src="http://multitech.id2r.net/sites/default/files/styles/colorbox_trigger/public/sd14-la-001_0.jpg?itok=8h7_PaP3" width="680" height="380" alt="" /> </div> <div class="field-slideshow-slide field-slideshow-slide-2 odd" style="display:none;"> <img class="field-slideshow-image field-slideshow-image-2" typeof="foaf:Image" src="http://multitech.id2r.net/sites/default/files/styles/colorbox_trigger/public/sd14-la-002_0.jpg?itok=as53SCju" width="680" height="380" alt="" /> </div> <div class="field-slideshow-slide field-slideshow-slide-3 even last" style="display:none;"> <img class="field-slideshow-image field-slideshow-image-3" typeof="foaf:Image" src="http://multitech.id2r.net/sites/default/files/styles/colorbox_trigger/public/sd14-la-003.jpg?itok=PtCO9nvK" width="680" height="380" alt="" /> </div> </div> <div id="field-slideshow-3-controls" class="field-slideshow-controls"> <a href="#" class="prev">Prev</a> <a href="#" class="next">Next</a> </div> </div> </div></div></span>']

?>

```

No wonder there is no `0` to interpret as an empty field. This way, I can't loop through it and hide if count `0`. To count the characters of the HTML would be way too dirty. But then, what *can* I do?

# Answer
> 0 votes
This is unfortunately just the way the colorbox module works.

Because it is possible to put any content in a views colorbox it is set up to handle anything in a very generic way, which means it doesn't handle single images in the most effective way and the trigger field way of configuring things is more complex than is needed in some cases.

I opened a similar issue about resizing the colorbox based on images, which you also cannot currently do because of the same issue of the way it has been implemented.

It is something I believe the module maintainer could fix though. I would recommend opening a feature request issue on drupal.org at https://drupal.org/project/issues/colorbox?categories=All

---
Tags: views, javascript
---


title: Views multiple Exposed Filters

text:
# Question
Title: Views multiple Exposed Filters
I have a view with three exposed filters like age, gender and city. Is it possible that, if I select for example "city = NY" and there are no "ages = 14-16" that this filter option will not be shown? I guess I want my exposed filters to narrow down each other (to work as a facet search). Is this possible?

# Answer
> 1 votes
Try the views hacks module (really not the best name for a module).

Specifically see the part on the project page at https://drupal.org/project/views\_hacks#views\_filters\_selective

---
Tags: views, search
---