# Question
Title: manipulate form variables before render()
I have the following line of code in a user-profile-form.tpl.php which Drupal uses to render an input field in the user's edit profile page.

```
print render($form['field_machine_name']);
// this field can be found in the database table field_data_field_machine_name

```

The issue is that I want to run the value field\_machine\_name through a function like `$form['field_machine_name'] = make_seo_url($form['field_machine_name'])` before I run the `render()` function. But this totally breaks the form because `$form['field_machine_name']` is some very large array and `render()` output html input tag instead of the actual field\_machine\_name itself.

How does one actually go about massaging values in the `$form` variable before outputting it as an html field in `render()`?

Additionally, i want to make sure anytime field\_machine\_name is printed anywhere on the drupal site, i want it to run through the `make_seo_url()` function. Is there a global place i can do this?

# Answer
> 1 votes
The Form API has #pre\_render per element. You can use hook\_form\_alter to add your pre-render function to the list of functions that need to be called to show the value.

> **#pre\_render**
>
> **Used by:** All elements and forms.
>
> **Description:** Function(s) to call before rendering in drupal\_render() has occured. The function(s) provided in #pre\_render receive the element as an argument and must return the altered element.
>
> **Values:** An array of function names to call.
>
> **Note:** If you are altering an existing form via hook\_form\_alter() or a similar means, be careful with this property! As demonstrated here, you will probably want to add to the existing array rather than writing over it.

I recommend being careful of when your module runs when trying to interact with Forms, Ajax, etc (your modules' weight). If needed I also recommend seeing hook\_module\_implements\_alter if you want to adjust when your hook is called, without affecting your modules' weight.

# Answer
> 0 votes
You need to hook into the form before processing the $form array not in a template file. See hook\_form\_alter. Also if you are wanting to make a field output a certain way when that field is rendered you need to look into changing the field template.

What you are doing is trying to render a form field inside a template which does not work.

# Answer
> 0 votes
You can do it in template\_preprocess\_field()

```
function mytheme_preprocess_field(&$variables, $hook) {
  $element = $variables['element'];
  if (isset($element['#field_name'])) {
    if ($element['#field_name'] == 'field_machine_name') {
          //do your changes
    }
  }
}

```

# Answer
> 0 votes
In the template.php of the appropriate theme, run code similar to the snippet i am giving:

```
function themename_form_user_profile_form_alter(&$form, &$form_state) {
  // dpm($form);
  // Use dpm to see the actual values that you are getting. Based on that change the lines below. Since $form is passed by refernce to this funciton, whatever change you make to the values, will be updated on the tpl file also.
  $old_value = $form['#user']->field_field_name['und'][0]['value'];
  $messaged_value = make_seo_url($old_value);
  $form['#user']->field_field_name['und'][0]['value'] = $messaged_value;
}

```

I think this should help. It uses `hook_form_FORM_ID_alter()`. To use `dpm()`, the Devel module needs to be enabled and the logged-in user needs to have the proper permissions to see the debug information.

---
Tags: forms, theming, views
---


# Question
Title: Modifying callback for Image Upload button
I am trying to access the upload button of an Image field. The field itself is in a field collection. Using dpm, I can access the field collection, and the image field.

What I want is to create a callback for the upload button such that once the upload is complete, the callback is triggered (ultimately to call a js function). I have found a few articles on how to do this for custom made, from scratch forms, but very little, and nothing yet that seems to work for me on existing, core forms.

I have been racking my brain for a couple of hours looking through elements via dpm, and researching, but I haven't found any fruitful examples related to this particular use-case.

I also tried tinkering with hook\_field\_widget\_form\_alter, which triggers for each element on every load, including initial load. I haven't been able to narrow it down to just the one event yet.

I went a completely different way as well, trying to intercept the click on the input via jQuery, which would then use a timer to check for the uploaded file in the new DOM output, and continue if found, but I cant get the click to work - I don't know if the built in ajax is over-ruling my code, or just a big conflict is causing it to fail for my own code.

Does anyone have any suggestions or direction on where I should look next?

# Answer
You can try hook\_file\_presave() or hook\_file\_insert() or hook\_file\_update()
> 0 votes

---
Tags: media
---


# Question
Title: Module Background Image (bg_image) installed, image not showing
Installed the Background Images module with path of image, but nothing is showing. I am using 'node/\*' to apply image to all pages

Did I miss something?

# Answer
When they say "You need to specify a css selector..." that is an existing selector; the module is not creating a new selector. Say, if you are giving the image to #Container, that is the selector you are asked for. See https://drupal.org/node/2043709 might be helpful.
> 0 votes

# Answer
Did you configure the base bg\_image settings? You need to specify a css selector to apply the background image to.
> 0 votes

---
Tags: theming
---


# Question
Title: Put off loading my theme banners to speed up Drupal
I'm currently using the Marinelli theme for a project. It loads ALL the top banner pictures before showing the page. Very slow. Results in a big download size for the home page. Is there a way to get Drupal or the theme to put off loading all but the first banner pics when it displays the page. See my screen capture of pingdom.com

Dave

# Answer
I think you're looking for a technique called "lazy-loading" to implement on your pages. Lazy loading means that the images are only loaded upon viewing them.

You can use the Lazyloader module as a start to implement it, however how it will exactly work for your site is completely dependent on your Drupal theme and module(s) configuration. One useful example (and starting point) is this blogpost, which explains how to implement the layloader module in combination with a slideshow.
> 1 votes

---
Tags: media
---


title: How to edit the user created date?

text:
# Question
Title: How to edit the user created date?
For node, we can change the created date easily, what about user ? Is there any easy way or module that can expose this field for editing instead via database ? I have many old users to be keyed in again manually into drupal, so I need to change this date of creation at the time of creating the user.

# Answer
> 1 votes
I haven't done this before, but if you have a module that loaded a user account, perhaps using `user_load()`, you can manually re-set the $account-\>created. Clues given in the user\_save() function. Let me know how you get on...

code will look something like this:

```
$account = user_load($users_uid_here);
$account->created = $date_timestamp_here; // eg. REQUEST_TIME
user_save($account);

```

---
Tags: users
---


# Question
Title: Improving Site Speed and Cache for Authenticated Users
I am building an intranet site. I have the site set up with single sign on via the server authentication module meaning there are no anonymous users. This means large parts of the cache are worthless.

The site is now set up how I want, however it's running extremely slowly for the first couple of page loads if the site hasn't been visited in a couple of hours. The speed picks backup once you've looked at a couple of pages.

We now have cron set up running every two hours with a scheduled task, so I now know cron isn't slowing the site down. I have the Devel module enabled, and some of the queries are clearly slowing things down and a lot of these seem to be cache related.

Below are all of the queries ran that took over 100ms when I visited the site's home page first thing this morning. (Speed in ms followed by task)

```
421.91 system_list
890.69 DrupalDatabaseCache::set
171.89 DrupalDatabaseCache::getMultiple
125.01 DrupalDatabaseCache::getMultiple
125.01 PagerDefault::execute
125.01 DrupalDatabaseCache::getMultiple
109.38 comment_num_new
390.65 DrupalDatabaseCache::getMultiple
140.64 ctools_export_load_object
187.51 DrupalDatabaseCache::set
328.15 DrupalDatabaseCache::getMultiple
421.91 admin_menu_tree_dynamic
390.65 admin_menu_tree_dynamic
1000.07 DrupalDatabaseCache::getMultiple
421.91 DrupalDatabaseCache::getMultiple
578.17 DrupalDatabaseCache::set
281.27 menu_get_item
343.77 statistics_exit
140.64 _drupal_session_write

```

Clearly there's enough here to slow the site down. However truth be told I don't have much of a clue how to a) decode what all the above really mean and b) what to do about any of it.

I would be grateful for any advice or pointing in the right direction anyone can give me.

# Answer
> 4 votes
I created a presentation that covers some of the basics of of performance https://docs.google.com/presentation/d/1AgnurTWsWdMAFjfFmSU7mk2zfJu8jG\_KmVdZ7-o6Pok/edit#slide=id. In your case I would make sure poormans cron in core is disabled, use an IP for your database connection (very important on IIS), make sure you have some sort of op code caching enabled, and follow this guide (linked in the presentation under Basic database tuning) to fix database issues at the drupal level, and be sure to adjust some MySQL defaults as well.

# Answer
> 0 votes
Also check out mySQL optimisation. Here's a couple links to get you started.

---
Tags: 7, caching, cron, debugging
---


title: Drupal services add location

text:
# Question
Title: Drupal services add location
I am trying to add a location to a node using Drupal services.

This is the JSON sent to the service

```
{
   "node":{
      "type":"restaurant",
      "title":"Restaurant from JSON API",
      "field_restaurant_location ":{
         "und":{
            "locpick":{
               "user_latitude":"22.38131",
               "user_longitude":"114.168639"
            }
         }
      }
   }
}

```

I can not get it to save the location to the node. Any ideas ?

# Answer
> 2 votes
Should anyone else have this problem, the correct answer is:

```
{
    "node": {
        "field_restaurant_location": {
            "und": [
                {
                    "country": "us",
                    "latitude": "-26.2041",
                    "locpick": {
                        "user_latitude": "-26.2041",
                        "user_longitude": "28.0473"
                    },
                    "longitude": "28.0473"
                }
            ]
        },
        "title": "Restaurant from JSON API",
        "type": "restaurant"
    }
}

```

# Answer
> 0 votes
Try this once, I hope would work for you. Sometime "Access denied for user anonymous" error also comes, if this issue is coming then it is coming due to different reason. If it doesn't work then share the error with us.

```
{
    "node": {
        "type": "restaurant",
        "title": "Restaurant from JSON API",
        "field_restaurant_location ": {
            "und": [
                {
                    "locpick": {
                        "user_latitude": "22.38131",
                        "user_longitude": "114.168639"
                    }
                }
            ]
        }
    }
}

```

---
Tags: 7, services, location
---


# Question
Title: How to save and append comment form without refresh the page in drupal 7
I have a form with comments but this page have counter to cout views of this page.

but every time when comment added on this page that page loaded and my counts increasing after comment added.

but i want to count views when page load first time not by comments module in drupal 7.

# Answer
> 1 votes
One option would be to use the AJAX Comments module:

> Provides ajax comments to Drupal sites. Features:
>
> * Makes AJAX submits
> * Allows replies to comments on the actual thread page
> * AJAX comments deleting
> * Works with CAPTCHA
> * Cool jQuery sliding
> * views integration

It will allow users to submit comments without a page refresh, bypassing the extra view count.

---
Tags: comments
---


# Question
Title: Modify the date popup to only accept special days
I may need your help please. I have installed the "Date" module and using it with the date popup (datepicker). I need to have the popup just accepting Wednesdays and Fridays as dates.

Can anybody give me some help on this issue?

Thanks alot!

# Answer
Found a solution. Just use jQuery and it's beforeShowDay attribute to check out if a date should be valid.
> 0 votes

# Answer
You can use Date Restrictions in conjunction with Weekdays to acomplish this.

Just download both projects and enable weekdays\_date\_restrictions module. Then edit the date field and go to "More settings and values" \> "Date Restrictions" \> "Allowed values" \> Choose restriction type: weekdays.
> 2 votes

---
Tags: javascript, datetime
---


# Question
Title: Is there a way to export all roles and permissions from testing environment to be imported/deployed on production environment?
I have testing and production environments that host drupal-7. I have some roles and permissions settled on the testing environment. Can I export these roles and permissions to the production environment to avoid double effort?

# Answer
Check out these modules Export Roles & Permissions or Features Roles & Permission
> 2 votes

---
Tags: 7, users, deployment
---


title: How to Remove "Edit Summary" Off Editor

text:
# Question
Title: How to Remove "Edit Summary" Off Editor
I would like to be able to remove the option to show the "Edit Summary" option. All I need is that users fill up the field and save. I believe this is called "Teaser" but I might be wrong.

# Answer
> 17 votes
You can actually disable user's ability to provide summary. I found this while pursuing the first solution:

Administration » Structure » Content types » Basic page

you should see "Manage Fields" tab. Click on it, and you should see a table. The row for Body should show Widget Type as "Text area with a summary" which is a link that allows you to edit it.

Rather than changing the Widget Type which is not possible if you already have one or more entries, go to the "Edit" tab.

About half-way down the tab is a checkbox: "Summary input" ("This allows authors to input an explicit summary..."). Uncheck it, and save. Your content edit page for Basic Page should be free of "Edit summary" options.

# Answer
> 3 votes
As an alternative solution, you can use a hook to hide the field:

```
/**
 * Implements hook_form_alter().
 *
 * @param $form
 * @param $form_state
 * @param $form_id
 */
function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'YOUR_NODETYPE_node_form') {
    $form['body'][LANGUAGE_NONE][0]['summary']['#access'] = FALSE;
  }
}

```

# Answer
> 3 votes
Go to the content type, then to **manage fields** then **edit** for the body field.

There is a check box to enable or disable the summary field display

# Answer
> 2 votes
Just go to the Manage Fields page for your entity (content type, user, taxonomy term, etc) and change the body field widget from Text Area with Summary to Text Area.

I'm assuming you're talking about the standard body field, but this should apply to any long text field.

**EDIT**

Actually, this won't work as the field TYPE is probably already set to Long Text with Summary - so you'll have to change your actual field type I'm afraid.

---
Tags: entities
---


# Question
Title: How can I find specific block name in structure->blocks in drupal-7?
I can see specific block in the home page. I need to show this block in specific roles. How I can find this block in the list of blocks in structure-\>blocks?

# Answer
1. You could enable the contextual links module and hover over the block and click the small gear icon to edit the block.
2. you could figure out what region the block is in using firebug or similar which will narrow it down in the block administration page assuming the block is set that way.

If the block is still not visible, the specific user/role may not have the permissions to see whatever content you are trying to view. Check the permissions for the role at `/admin/people/permissions`
> 1 votes

---
Tags: 7, blocks
---


# Question
Title: How to search both Users and Nodes simultaneously in drupal 7
I have a url for search nodes like **"?q=search/node/article/xyz"**
and
I have a url for search users like **"?q=search/user/xyz"**

now i want to search both at a time simultaneously so, what is the url for this in drupal 7.

I have links for Search Like **"Article Search"**, **"User Search"**, and **"All Search"**,

I have url for both article and user but not for All Links that's the problem
please help.

# Answer
> 1 votes
As AyeshK noted in the comments, you can't get this functionality with Drupal core (or even Views).

There are a couple of modules you can try though:

* Search API multi-index (relies on Search API)

> This module is an addition to the Search API module which allows users to search on several indexes at once.
>
> When the module is enabled, you'll get a new Views base table where you can search all enabled Search API indexes at once. Performance might suffer, though, if not all indexes lie on the same Solr server (or other backend server that supports this feature).
>
> Please note that, since multi-index searches aren't supported explicitly by the Search API, most other Search API add-on functionality (facets, autocomplete, saved searches, search pages, etc.) won't work with searches created with this module.
* Entity Backend Search (in alpha)

> This module enables highly customizable search pages for any entity type on a site for the editorial staff. It does not require any modules outside Drupal Core and is very easy to configure.

# Answer
> 0 votes
It can done without extra modules, sort of - by cheating in Views (Views being a necessary module for nearly any site). It's far too involved to show in an answer, but making a custom search block (form) that redirects to a Views page - the page is setup as a content search using a contextual filter, then as a header or footer, create a separate block view of users that uses the same contextual filter from the url.

Depending on your layout, it would then show say 10 pieces of content, and underneath, 10 users where the search criteria matched.

One problem in using Views for searches, is I believe it still uses = and not LIKE for searching, meaning that partial words won't be found - but I have heard of workarounds for that problem as well.

---
Tags: search
---


# Question
Title: How can I add previous and next controls to the views slide show?
I have the photo slider on home page using views-slideshow. Now I need to add previous and next controls to that slider. How can I?

# Answer
> 0 votes
I done it through css code, just follow this steps

```
#views_slideshow_singleframe_prev_gallery-block_1, #views_slideshow_singleframe_next_gallery-block_1 {   width:71px;   height:0px;   padding-top:71px;   position:absolute;   top:100px;   overflow:hidden; }

#views_slideshow_singleframe_prev_gallery-block_1 {   background:url('images/left-button-on.png');   left:0px; }

#views_slideshow_singleframe_next_gallery-block_1 {   background:url('images/right-button-on.png');   right:0px; }

 #views_slideshow_singleframe_playpause_gallery-block_1 {   display:none; }

```

And also take a look at https://drupal.org/node/691984

# Answer
> 0 votes
There is option for set the control for slideshow in views\_slideshow module, you could select the slideshow control option while creation slideshow. but it provide only content control(Prev/ Next). If you need image for control button you could change this with css.

---
Tags: views
---


title: How to use tokens in node titles?

text:
# Question
Title: How to use tokens in node titles?
For example if I've page title as "Income tax forms 2012" it should change automatically change to "Income tax forms 2013" in Y2013.

Tokens work for node body but not in title. It did not work when I tried.

Any suggestions?

# Answer
> 4 votes
If these titles are on nodes, and you have the Auto Node Title module installed, you *should* be able to use \[yyyy\] for the current year in the replacement patterns section. However, drupal won't automagically go and redo the title for you, but rather, you will have to resave it "next year" for it to take effect.

# Answer
> 0 votes
In addition to Jimajamma's answer, you could use Automatic Nodetitles in conjunction with Scheduling part of Rules. This will allow you to create a Rule which re-saves the particular node at the start of every year, which will update the node title.

---
Tags: 6, tokens
---


# Question
Title: Commerce: Extra information per quantity bought
Is there any module or solution that allows extra information to be collected for each item bought? Example of what I mean below:

A user can buy any number of tickets, and for the amount of tickets purchased they have to complete details of the other guests (name, email address etc...). So if they buy 10 tickets they have to complete 9 lots of guest information in addition to their own.

Is there any module that can facilitate this? Additionally, the user should be able to log in and change the details of the guests before the event occurs. This part I'm almost certain will be a custom module, but I'm open to any ideas!

# Answer
Not a simple answer here, you've got a lot of ways to do this, but if you're focusing in the ticket/registration case, you could take a look to Commerce Registration, that will provide the closest feature I know for that matter.

It is based in Entity Registration, so you've got there a starting point.
> 1 votes

---
Tags: commerce
---


title: Flag a node after click on the link

text:
# Question
Title: Flag a node after click on the link
I want to check if user has downloaded the file so afterwards I will allow him to post a review. To do that I want to flag the node after user download file, flag the node and allow flagged node to be commented. I have a script:

```
global $user;
$flag = flag_get_flag('downloaded');
$node = node_load(arg(1));
$flag->flag('downloaded', $node->nid, user_load($user->uid), TRUE);

```

but I don't know how to make that event to occure when clicked on link. Link is in `span.file a`

Does anybody have an idea how to achieve my goal? I will be so grateful for any answer.

# Answer
> 0 votes
If you're using the private file system, you can make use of hook\_file\_download, it is normally used for granting access but I don't see why not you can use it for flagging stuff.

See an example of this in Example of hook\_file\_download

If you're using the public one, it will be way trickier, you're going to need to wrap the download link to react with your custom code, this could be done by replacing the download link like the Public Download Count module does, or providing your own hook\_menu callback that is called via ajax to flag the content, but then you depend on whether the user has js enabled or not.

---
Tags: comments, flags
---


# Question
Title: How do I modify the individual links on comments (reply, delete, any others I add in Flags, etc...)?
I'm in my sub theme's comment.tpl.php, and I have `print render($content['links'])` \- how do I access the individual links within that? I tried doing a print\_r to see if it was a bunch of nested arrays - it appears it is(?) - but I can't seem to dig into those arrays to get the individual links? I tried `$content['links']['comment']['#links']['comment-reply']` for example (based on the structure returned form the print\_r) to get just the reply link, but I get nothing.

Ultimately what I'm trying to do: Due to various modules and some flags I have 5 links on every comment: reply, delete, edit, flag, and like. I want to group edit, delete, and flag (and any other future miscellaneous) into a little dropdown menu at the top of the comment. Then put reply and like in individual styled buttons at the bottom. I was planning to just handle the menu and buttons using Bootstrap since that's my theme base, but I can't "get to" the individual links to add the classes and markup I need. Additionally I want to change the displayed text, capitalize Reply for example and add some inline icons for edit, delete, etc.

I've come across theme\_links, but that page is over my head. Sounds like maybe I need to understand this? If so I don't even understand where to start to apply it - I searched across all files in my base theme (Bootstrap) and found nothing with that name to start from?

Where and how should I be trying to do all this?

# Answer
thanks to your link to the theme\_links i managed to solve my problems, so here's how i would solve yours.

the idea is to split the links in two parts, one to print before and the other after the content.

```
$group = $content['links']['comment']['#links'];
$plain = array();

if( isset($group['comment-like']))
{
    $plain['comment-like'] = $group['comment-like'];
    unset($group['comment-like']);
}
if( isset($group['comment-reply']))
{
    $plain['comment-reply'] = $group['comment-reply'];
    unset($group['comment-reply']);
}

$first = $content['links'];
$first['links']['comment']['#links'] = $group;
$second = $content['links'];
$second['links']['comment']['#links'] = $plain;

//before the print render( $content);
//note: apparently, you can't add a class to the <ul> element from here, so you should manually wrap it and fix your css accordingly
print '<wrapp class="something">'.render($first).'</wrapp>';

//after
print render($second);

```
> 0 votes

---
Tags: theming, comments, navigation
---


# Question
Title: React if user's text changes in existing node are major
I would like to ask about some ideas about following issue:
I have a content type - answer, that can be created and edited (not deleted) by users. From time to time, for any reason an user can delete all text inside node, thus completely destroying it.

I do not want to be informed about every subtle change in node, but I certainly want to be alerted and possibly approve, if there is a major change in node's content.
So the requirements are:

* detect negative change + restrict user to publish changes + alert admin for approval

Solutions?:
1) Count words in node and compare it to word count in node's revision. The word count may be saved inside a field in node and after compared by rules.

2) As suggested by @T-34, use custom module I found some modules but none of them gives the ability to figure out the difference percentage and use it with rules:
https://drupal.org/project/diff
https://drupal.org/project/rules\_diff
https://drupal.org/project/trevi \- suggested by @T-34 gives me an error + it seem s to work only on node edit page.
Thank you for ideas.

# Answer
I would use Diff and implement hook\_entity\_diff() (see diff.api.php), which allows modules to provide a comparison about entity properties.

Here you go:

```
function MYMODULE_entity_diff($old_entity, $new_entity, $context) {
  if ($context['entity_type'] == 'node') {
    $old_body = $old_entity->body[LANGUAGE_NONE][0]['value'];
    $new_body = $new_entity->body[LANGUAGE_NONE][0]['value'];
    $matching = similar_text($old_body, $new_body, $percent);
    $results['line'] = array(
      '#name' => t('Body'),
      '#old' => 'Number of matching chars: ' . $matching,
      '#new' => 'Percentage difference: ' . $percent,
    );
    return $results;
  }
}

```
> 0 votes

# Answer
After I wrote my first answer, I found module https://drupal.org/project/trevi. It seems to be unsupported, but description says that this module has Difference percentage review method. You can try this module too.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: How to use tables that are claimed by other modules in drupal?
How to use tables that are claimed by other modules in drupal?

I have a table in my database named "dictionary" used by a module for translation . now i want to use that table in views to show all data of that table. Is there any method by which i can use that table?

# Answer
You can expose information from other modules/"orphan" database tables from your own module by using hook\_views\_data in case nobody is exposing that table to views then you would "claim" it with all the consequences. If the table is already exposed to views but you want ton enhance the integration, you can use then hook\_views\_data\_alter for adding fields, altering filters, etc.

You can find an example of how to implement a hook\_views\_data in the views documentation.
> 0 votes

# Answer
There is a great presentation available here on exactly the same topic from Drupalcon NY 2011. It is a step by step guide to solve a similar problem.

You should also look at their blog here, it also contains a downloadable zip of the source code used for the presentation. You should be able to edit the files in the zip to get your stuff working.
> 0 votes

---
Tags: database, theming
---


title: Can't login to my Drupal website admin!

text:
# Question
Title: Can't login to my Drupal website admin!
I can't login My drupal website (D 7.23) now. I have changed the password and tried to login back, but still the problem exists. After I reset the password by using the one time password and can log in, but when we log out and try again to login, it will be a failed one.

Please help me to solve it.

# Answer
There is nice article on drupal.org on recovering administrator's password. Here is the link

Specifically, you would probably be using one of the two commands below:

Drush can generate a one-time login link.

```
drush uli

```

Reset password

```
drush upwd --password="givememypasswordback" admin

```
> 2 votes

# Answer
When you follow the reset password link, make sure you set a new password and save your account page at `/user/[uid]/edit`
> 0 votes

---
Tags: users
---


# Question
Title: How to embed my webiste Header(logo, menu) for each of my panel variant
I'am using Panel and I created several variant for many content type.

Is there a way to add my Top WebSite Header composed with (Logo, Main Menu, Second Menu, Search textbox, Language switcher and social network Icon) for each of my variant in a desired region.

Here is what I would like to do.

Create a kind of template called MyHeader where I would put any html element that I need for my Website Header(Logo, menu etc...). If it's possible to create a template for MyHeader, how to do that ?

Use MyHeader into each variant panel, I would like to drag it into a specific Region , like dragging a simple widget.

Is it possible to do this.?

Note: I'm using Omega 4 as base theme for my subtheme

Sory for my english.

Thanks a lot.

# Answer
> 0 votes
Create a block with the required Header and then assign that to your content regions in panels. I think that should be it.

And yes, you can theme your block as required using `block--block--[block-id].tpl.php` templates.

---
Tags: panels, theming
---


# Question
Title: View with paged output - how to alter number of pages?
I use Views 7.x-3.8.
I have view "taxonomy\_term". It has Paged output, full pager. Number of pages (the total number of pages) is set to 100, Items per page = 10. Now I want to show all pages for users with proper permission.

I tried to set pager option 'total\_pages' to empty string in hook\_views\_pre\_execute():

```
function MYMODULE_views_pre_execute(&$view) {
  if ($view->name == 'taxonomy_term') {
    if (user_access('view all pages')) {
      $view->query->pager->options['total_pages'] = '';
    }
  }
}

```

It actually works with pager: users with permission 'view all pages' can view page #101, #102 and so on, but nodes on these pages (more than #100) are the same as on page #100. It means that query has not changed, and query limit is still 1000 (10 items x 100 pages). I tried

```
$view->query->set_limit(0);

```

in hook\_views\_pre\_execute() and

```
$view->query->set_limit(0);
$query->set_limit(0);

```

in hook\_views\_query\_alter(), but it's not working.

I also tried to set $view-\>query-\>offset and $view-\>offset manually:

```
$view->query->offset = $view->offset = $view->query->pager->current_page * $view->query->limit;

```

with no effect.

What am I missing? How to change number of view' total pages AND query results programmatically?

# Answer
> 3 votes
I did it:

```
function MYMODULE_views_pre_execute(&$view) {
  if ($view->name == 'taxonomy_term') {
    if (user_access('view all pages')) {
      $view->query->pager->options['total_pages'] = NULL;
      $query = $view->build_info['query'];
      $offset = $view->query->pager->current_page * $view->query->limit;
      $query->range($offset, $view->query->limit);
    }
  }
}

```

---
Tags: 7, paging, views
---


title: Create a script page for handling ajax

text:
# Question
Title: Create a script page for handling ajax
I am a bit confused on the appropriate way to generate a drupal page for handling ajax posts. For example I'm creating a custom module that has favorites buttons. When a user clicks the button the ajax request sends the data to example.com/ajaxscripts/process.php. I need to create a page at process.php to handle the request but it shouldn't generate the full drupal theme. Rather it should just have access to the core drupal information such as $user and drupal database functionality. How can I create such a page? It seems that tying to use hook\_menu() would force a full page rendering.

# Answer
> 0 votes
In your hook\_menu, create a menu item with `'type' => MENU_CALLBACK`, like so:

```
$items['YOUR_MENU_PATH'] = array(
  'page callback' => 'YOUR_PAGE_CALLBACK',
  ...
  'type' => MENU_CALLBACK,
);

```

Then, in your page callback function, you can use the `drupal_json_output($some_array)` function to convert $some\_array to json, and return it, all in one go.

I wouldn't use the .php extension in the menu path.

# Answer
> 0 votes
In my opinion, services module is the best fit for your use case. Just create appropriate resources and define end-points for various types of calls. A nice tutorial on creating a resource can be found here. Although it may seem daunting at first, its really easy to manage if you have multiple end points. And plus, you don't have to worry about security if you are using a standard drupal module for providing web services end-points.

From the Services module intro page:

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

---
Tags: ajax, javascript, database, external-scripts
---


# Question
Title: How to make content creation form more organized. Taxonomy Checkbox list
I am preparing to allow users to edit specific fields of content. I have until now used autocomplete for myself.

I would like to start using the Check boxes, but as of right now it show my 30 terms as a one column list.

Is there a way to have these terms show in 4 columns instead of one long column. (to organize it better and utilize page space)

# Answer
> 1 votes
If you are familiar with using CSS to change the layout of your drupal site already, something like this should work:

/\* Make categories field 2 columns \*/

div.form-item.form-type-checkboxes.form-item-field-categories-und {

```
    -moz-column-count: 2;
    -moz-column-gap: 20px;
    -webkit-column-count: 2;
    -webkit-column-gap: 20px;
    column-count: 2;
    column-gap: 20px;

```

}

If not, it will depend on what theme you are using. We are using the seven theme for our admin pages, which include the node create pages. In the seven theme, I could just add the chunk of CSS above to the style.css file. Technically however, this chunk probably shouldn't be added into a core theme because it might get wiped out when/if you upgrade drupal core.

If you want to do it properly, you should create a new stylesheet with something similar to the CSS chunk above and give it a name. Then, add that stylesheet in your theme's .info file. (You can see specific instructions on how to do that here: https://drupal.org/node/171209)

Be sure that you don't have your CSS optimized when you are updating your stylesheets. If you aren't sure how to check this setting, go to admin/config/development/performance and make sure the option to aggregate and compress CSS isn't checked.

Without knowing more about your setup, what theme you are using, etc. it's hard to make a more specific recommendation.

---
Tags: taxonomy-terms, nodes
---


# Question
Title: hook_views_pre_render and hook_node_view
In my custom module I'm creating a logic with two fields.

The first field is an image and the second is date field. When I choose past date from the date field, the image field should be hidden. If the date value is present or made in future, the image will be visible.

It's working great on hook\_node\_view, but I can't figure out how to do this on views.

Here's my code:

```
<?php
function custom_alter_node_view($node, $view_mode, $langcode) {
 if ($node->type == 'hot_offers') {
    $c = strtotime($node->field_hot_offers_new_date['und'][0]['value']);
    $current_time = date("m/d/Y H:i:s");
    $d = strtotime($current_time);
    if ($c < $d) {
    $node->content['field_hot_offers_new_image']['#access'] = FALSE;
    }
  }
}

```

I know there's a hook\_views\_pre\_render, but how do I create the same logic, so the image will be visible only if the date field value will be present or in future?

# Answer
> 1 votes
I've solved the puzzle and I'm sharing the solution.

```
function custom_alter_views_pre_render(&$view) {
    if ($view->name == 'hot_offers') {
        //dpm($view);
foreach ($view->result as $key=>$value) {
    $c = @$value->field_field_hot_offers_new_date[0]['raw']['value'];
    $d = date("Y-m-d"); //2014-06-26
    if ($c < $d) {
    $value->field_field_hot_offers_new_image[0]['rendered']['#access'] = FALSE;
    }
  }
 }
}

```

The tricky part was to set the $d same format as the new\_date field, otherwise the if statement logic will not work.

# Answer
> 0 votes
You can do it using any of the following ways.

1. Install View PHP module and you will get a gobal php field in the views where you can write your logic as a php code.
2. Or as Jimajamma said, in `hook_views_pre_render(&$view)` you can check `$view->name` and unset the values from `$view->result`.
3. Or you can write your own views custom field handler for the image field and write your logic to display the way you want.

---
Tags: views, hooks
---


# Question
Title: How to list the most popular content for different periods of time with Radioactivity?
I'd like to create a view with the most popular content of the last week, the last month and of all time. I've installed the Radioactivity module and created the three required profiles. While adding a radioactivity field 'Popularity' to my nodes, I had to select one of these three profiles, so I assume that I'll have to add another two radioactivity fields with the other profiles and that I'll end up with three fields

* 'Popularity (week)'
* 'Popularity (month)'
* 'Popularity (all time)'.

Is that correct? If yes, I'm wondering whether I now have to create the same rules for the three fields every time in order to change their value. Isn't it possible to add an action that adds an incident to the three fields at the same time, as the incident-values will be the same in the three cases?

This repetition is not a very big problem, but I'm not sure whether the set-up for what I want to achieve is completely correct, because doing the same work multiple times in Drupal is wrong most of the time.

# Answer
> 1 votes
You are right. There is a one-to-one relationship between fields and profiles. Since one field cannot represent multiple profiles, you will need 3 fields.

In answer to your Rules question, it should be possible to create a rule with 3 actions to update the 3 fields at the same time.

---
Tags: 7, views, rules
---


# Question
Title: How to form_alter fields attached to an unlimited field collection?
Here are 2 unsuccessful experiments I've done:

```
<?php

/**
 * My first attempt with implementing hook_form_alter.
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'MYNODETYPE_node_form':
      foreach ($form['field_MYFIELDCOLLECTION']['und'] as $delta => $field) {
        if (is_numeric($delta)) {

          // None of these work:
          $form['field_MYFIELDCOLLECTION']['und'][$delta]['field_SOMEFIELD']['und']['#default_value'] = 'test';
          $form['field_MYFIELDCOLLECTION']['und'][$delta]['field_SOMEFIELD']['#default_value'] = 'test';

          $form['field_MYFIELDCOLLECTION']['und'][$delta]['field_SOMEFIELD']['und']['#value'] = 'test';
          $form['field_MYFIELDCOLLECTION']['und'][$delta]['field_SOMEFIELD']['#value'] = 'test';

        }
      }
  }
}

/**
 * My second attempt implementing hook_field_widget_form_alter.
 */
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($element['#field_name'] == 'field_MYFIELDCOLLECTION' && $context['instance']['bundle'] == 'MYNODETYPE') {
    // These don't work either:
    $element['field_SOMEFIELD']['#value'] = 'test';
    $element['field_SOMEFIELD']['#default_value'] = 'test';

    $element['field_SOMEFIELD']['und']['#value'] = 'test';
    $element['field_SOMEFIELD']['und']['#default_value'] = 'test';
  }
}

```

How can I alter the form API elements on fields attached to a field collection?

**PS:** The hook functions are running fine. The issue is that the form API values I set do not make any change on the loaded form.

# Answer
Check the array to make sure you are using the correct names and structure. You can use dpm() from the devel module to check this.

Both hook\_form\_alter or hook\_field\_widget\_form\_alter allow you to alter field collection child field form elements.

```
<?php

/**
 * Implements hook_form_alter.
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'MYNODETYPE_node_form':
      foreach ($form['field_MYFIELDCOLLECTION']['und'] as $delta => $field) {
        if (is_numeric($delta)) {

          $form['field_MYFIELDCOLLECTION']['und'][$delta]['field_SOMEFIELD']['und'][0]['value']['#default_value'] = 'default value';
          $form['field_MYFIELDCOLLECTION']['und'][$delta]['field_SOMEFIELD']['und'][0]['value']['#value'] = 'value';

        }
      }
  }
}

```

The following will also work:

```
/**
 * Implements hook_field_widget_form_alter.
 */
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($element['#field_name'] == 'field_MYFIELDCOLLECTION' && $context['instance']['bundle'] == 'MYNODETYPE') {

    $element['field_SOMEFIELD']['und'][0]['value']['#value'] = 'value';
    $element['field_SOMEFIELD']['und'][0]['value']['#default_value'] = 'default value';

  }
}

```
> 7 votes

---
Tags: 7, entities
---


# Question
Title: $fields is undefined - custom theme creation
I'm attempting to create a custom template for a view. The template file I'm creating is being loaded (if I add some static html it renders).

I'm having trouble accessing values from the view. The tutorial I'm using advises using

```
dpm($fields);

```

To output the available fields. This is coming up as an undefined variable.

Googling suggests using $rows instead of fields but this was also undefined in this case.

# Answer
The `$fields` variable will be available for theming only if you have selected to display fields instead of content, check under format section of view.

Secondly, the `$fields` variable is not available if your template file is views-view.tpl.php, you have to use views-view-field.tpl.php or if you want theme only a specific field, you can use views-view-field--fieldname.tpl. php.
> 1 votes

---
Tags: theming, entities
---


# Question
Title: How to install PEAR packages on Acquia Dev Desktop 2
I'm on Windows 7 and I would like to install PHP Code Sniffer on Acquia Dev Desktop.

I've set PATH to Dev Desktop's php executable so I can run `php` command from Command prompt.

I see pear command is not recognized. Is PEAR not installed on Acquia Dev Desktop? Or It's installed but I can't see it where?

What I want to achive is, install PHP Code Sniffer so Coder module is able to detect it.

# Answer
Pear is not installed on Acquia Dev Desktop. Install it manually:

* download `go-pear.phar`
* put in C:\Users\[my-account\]\
* from commandline, run `php go-pear.phar` (php.exe is set to Dev Desktop's)
* press enter when prompt appear
* install PHP Code Sniffer using pear

However, coder still showing error PHP/CodeSniffer.php is not found. But I use CodeSniffer from NetBeans IDE
> 1 votes

---
Tags: 7, acquia-dev-desktop
---


# Question
Title: In Drupal 7 how could I change style.css conditionally
Where in drupal themes files I could apply the following blueprint code:

```
if ($language->language == 'ar'){
// Do something to change the included style.css to be style_rtl.css
}

```

Does it template.php or html.tpl.php? and How to implement the comment in the code above?

I use Drupal 7

# Answer
You want to put it in template.php and probably want something like this:

```
function hook_css_alter(&$css) {
  global $language, $theme_path;
  if ($language->language == 'ar'){
    unset($css[$theme_path . '/css/style.css']);
    drupal_add_css($theme_path . '/css/style_rtl.css', array('group' => CSS_THEME, 'every_page' => TRUE));
  }
}

```

I think there is something in the Domain Access project regarding theme settings, if you are using that suite of modules.
> 2 votes

# Answer
Another way to do this would be using prefixing your CSS classes/id's with .i18n-en and .i18n-es (for English and Spanish respectively). Here's an example:

```
.i18n-en .myclass {
    color: #ff0000;
}

.i18n-es .myclass {
    color: #336699;
}

```

You'll see this in the `<body>` tag.

You can also make use of hook\_css\_alter. Check this page for the official documentation and some examples.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Can't add contextual Filter (taxonomy term ID (with depth)) to a View (User)
please help me out here:

I can't find a contextual filter by taxonomy term **with depth** on a view of users and/or profiles. When I make a view of content it can be chosen. I'd like to provide a filter for Regions, so Filter for Europe should result in a List of Users from all over Europe and so on.

The users are associated with a taxonomy term.

Thanks for your help or any suggestions.

Christian

# Answer
> 1 votes
In D7, you can only do that with the node table (the content).

If you want to have a working solution for every entity of your system, you have to use this module.

Once installed, don't forget to rebuild the index of your entities, then, in views, you'll have the possibility to add a new relationship ('Taxonomy Entity Index: Taxonomy terms on User') and a filter with depth ('Taxonomy Entity Index: Has taxonomy terms on User (with depth and indexed in taxonomy\_entity\_index)').

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


# Question
Title: How to do "has term (with depth)" filter on field of a related field
i have a content type 'product', and two taxonomy lists 'company' and 'country'.
Country list has one level of depth like:

........
state1
-city1
-city2
........

Each product has a 'company' field. Each 'company' term has a 'country' field.
I'm trying to create a view for 'product', filtering by 'country'.
By adding the relationship "content: Company" i have only "taxonomy term: field\_country" filter without depth.
There is a way to filter with depth like "Has taxonomy term (with depth)" ?

I'm on drupal 7

# Answer
> 0 votes
You would not require a Relationship, just two Contextual Filters.

Based on your requirements Company would be one Contextual Filter - Content: Has taxonomy term ID and Country would be a second Contextual Filter - Content: Has taxonomy term ID (with depth).

# Answer
> 0 votes
In D7, you can only do that with the node table (the content).

If you want to have a working solution for every entity of your system, you have to use this module.

Once installed, don't forget to rebuild the index of your entities, then, in views, you'll have the possibility to add a new relationship ('Taxonomy Entity Index: Taxonomy terms on User') and a filter with depth ('Taxonomy Entity Index: Has taxonomy terms on User (with depth and indexed in taxonomy\_entity\_index)').

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


# Question
Title: Multiple OR conditions are not working with Rules
Multiple OR conditions are not working with the Rules module in Drupal 7.

I have profile2 module. And I want to notify user with an email if one of the fields from the user's profile is empty, I have written a rule but multiple OR conditions are not working.

Any help?

# Answer
> 0 votes
I have tried it and found out that it is working fine for `main profile` but if you create any other profile it is not working. I debugged and found out that it is throwing exception `unable to get the data property as the parent data structure is not set` while executing the `function value()` in `entity.wrapper.inc` which is called from `function rules_condition_data_is_empty($data)`. I will debug it further when I have time, but as of now I hope this helps.

---
Tags: 7, rules
---


title: How to hide comments from indexing?

text:
# Question
Title: How to hide comments from indexing?
I am using Drupal 7. I do not want comments to index in search module. How can I achieve this?

# Answer
Note that I'd strongly recommend to go for Search API with maybe the db engine for these kind of customizations in case you don't have access to a Solr server.

Comments get indexed with their nodes through the invocation of hook\_node\_update\_index I believe, in comment\_node\_update\_index, so if you stop that hook from happening, comments won't ever index, with all the consequences, you could achieve this with hook\_module\_implements\_alter.

Check out how migrate module does this to avoid some potentially harmful hooks to run on the migration:

```
/**
 * Implements hook_module_implements_alter().
 */
function migrate_module_implements_alter(&$implementation, $hook) {
  // Ensure that the Migration class exists, as different bootstrap phases may
  // not have included migration.inc yet.
  if (class_exists('Migration') && $migration = Migration::currentMigration()) {
    $disable_hooks = $migration->getDisableHooks();
    if (isset($disable_hooks[$hook])) {
      foreach ($disable_hooks[$hook] as $module) {
        unset($implementation[$module]);
      }
    }
  }
}

```

Another option you have is to just index the content and modify the search index/ search results to not display any trace of the comment, but I'm guessing what you're looking for is that the result is just not there.
> 0 votes

# Answer
One possibility is to create a custom search page using Views and Search API. With Search API you can select precisely what you want to get indexed.
> 1 votes

---
Tags: 7, search, comments
---


title: How to group rules together in the UI?

text:
# Question
Title: How to group rules together in the UI?
My website has a lot of rules and it's becoming hard to find a specific one fast via the UI. I know I can filter them, but I almost never use that feature. Is there a way to group rules with the same tag together in an expandable block or something? That would make life a lot easier. (Maybe I should post this as a feature request on the Rules' issue queue.)

# Answer
As you've mentioned, Rules provides a tagging feature to tag / label rules. You then apply a filter to view that set of Rules only.

Any other grouping of Rules would require custom coding to retheme / template the layout of that page.
> 1 votes

---
Tags: rules, 7
---


# Question
Title: How to show terms in a Views in its hierarchical structure?
I have create a view to show the terms of the **Products** vocabulary.

I the view I set:

**Format:** Html list

**Show:** field

**Fields:** Taxonomy term: Name

It works fine but it the hierarchical structure is lost.

The Products vocabulary has this structure:

-**Cars**

--Ford

--Volvo

-**Computers**

--Desktop

--Laptop

But in the Views the terms lost the hierarchical structure and are listed like:

-**Cars**

-Ford

-Volvo

-**Computers**

-Desktop

-Laptop

What am I missing here??

# Answer
> 16 votes
I would recommend that you give a try to Views Tree module which installs a tree-style (adjacency) Views style plugin which allows you to list vocabulary in a hierarchical way.

Comment: Views Preview does not show the tree layout but normal page display does output as a tree.

# Answer
> 13 votes
Views Tree is nice for fast and simple hierarchy configuration but it lacks some features like different fields/configuration for different tree levels and grouping

You can get more flexible configuration with Views Field View.

This is the setup I needed for a taxonomy tree of three levels where I needed grouping by top level term.

1. Create a view of terms with a page display(or any other display)
2. Add relationship "Taxonomy term: Parent term"
3. Add Field : Term name(without relationship), Term Name(Parent relationship, excluded from display)
4. Add Filter Taxonomy term: Parent term (Parent relationship) equal to 0. (show only level 2)
5. In Format settings, use grouping with field (Parent) Term Name.(to display level 1)
6. Add A new display (an attachment is good)
7. Override its fields (just click any field, choose this attachment(overridden) from the select box on top, and then save the field. (this is to avoid recursion)
8. Override the attachment Contextual filters by adding Taxonomy term: Name (Parent relationship)
9. Add a view field (Global: View) to your view fields.
10. Use the attachment in the view field config, and add the token for the term name (not the parent) as the contextual filter value sent to the attachment.

You can remove the relationship from the filter in step 4, this will display the top level in main display, so you can skip grouping (step 5), then add a new display for each level you want to display (control no. of levels to display)

For me this gave almost the same results of Views Tree but with the flexibility I needed.

# Answer
> 4 votes
If you only have 2 level category tree and don't mind losing the ul nested format or hacking away with theme files, you can obtain such a functionality by following:

1. Adding a "Parent Term" relationship to the View and require it.
2. Having two "Term Name" fields. One without a relationship, and another hidden from display field using the newly created relationship.
3. Use the hidden field as a grouping field.

Not sure if it was exactly that which was intended...

# Answer
> 4 votes
I've solved similar task by using the Taxonomy menu module.

> Transform any of your taxonomy vocabularies into existing menus easily!
>
> ### Features:
>
> * Custom Menu per vocabulary
> * Uses the Terms default Path
> * Integrate with Views
> * Integrate with Path Auto
> * Customize the menu path to anything using hooks: Developer Documentation for version 6.x-2.x
> * It doesn't interfere with other menu modules

# Answer
> 4 votes
You may use the module Views Term Hierarchy Weight Field. It provides a new sort filter to sort terms by their hierarchical order.

# Answer
> 1 votes
Views Hacks has a views\_summary\_taxonomy submodule that seems to do what you are looking for:

"It displays a hierarchical summary of the taxonomy terms in your view results."

http://drupal.org/project/views\_hacks#views\_summary\_taxonomy

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


title: Do I have to delete the default folder?

text:
# Question
Title: Do I have to delete the default folder?
Do I have to delete `default` folder which is located under `/sites`? Because I installed new theme and I think there is no need to keep the default theme.

And, if I can't delete it, please tell me why?

# Answer
> 3 votes
Unless you're running a multi-site or another non-standard configuration (and the way the question is phrased, I do not think you do), you can't delete the `sites/default` folder or the files within it.

The reason you can't delete it is because: This directory (unless you've set up a multi-site or similar) contains (among other things) the `settings.php` for your site. If you delete it, all you settings including the database credentials will be lost, and your site will stop working.

Please also note that the `sites/default` folder has *nothing* whatsoever to to with the theming of your site.

If you have installed a new theme, and have the problem that the new theme is not used, this problem is *not* related to the presence of the `sites/default` folder on your site.

# Answer
> 1 votes
Drupal default themes should be on themes/\* and you shouldn't touch those, either modify or delete any content of what's considered core is not recommended.

Anything that is under sites/ is considered part of your application so if you're sure you're not using the themes under sites/default, there's no problem with deleting them.

You need to be sure to leave your settings.php, files and other useful content intact as you're using those (either in default or in a multisite)

---
Tags: theming
---


# Question
Title: 'Content Type' link not available for new content type
I have created a new content type (I can see in Content type list), but this is not available on "content \>\> Add Content".

Checked most parameters on creating the content type. No success.

# Answer
> 0 votes
Go to Structure \>\> Menus \>\> Navigation \>\> list links

(/admin/structure/menu/manage/navigation)

Make sure that the content type link is enabled.

---
Tags: nodes
---


# Question
Title: Limit currency for one product in Drupal Commerce
I have enabled two currencies for price in Drupal commerce but I want to enable only one of them for one of products. At this moment I can see both of them in product creation time. Where or how can I set this?

# Answer
> 0 votes
I'm afraid there's no custom module for this, you'll need to alter the product form add/create to adapt to your settings/conditions (simplified logic below):

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function my_module_commerce_form_commerce_product_ui_product_form_alter(&$form, &$form_state, $form_id) {
  // Calculate the currency for a given product.
  $currency_code = 'USD';
  $form['commerce_price'][LANGUAGE_NONE][0]['currency_code']['#type'] = 'value';
  $form['commerce_price'][LANGUAGE_NONE][0]['currency_code']['#default_value'] = $currency_code;
  $form['commerce_price'][LANGUAGE_NONE][0]['amount']['#field_suffix'] = $currency_code;
}

```

A more complex and customizable option would be to use hook\_field\_widget\_info\_alter and modify the settings form to add whatever conditions you want for selecting a currency on a product form.

---
Tags: commerce
---


# Question
Title: change field from int to big int in drupal
I have a integer field in a custom content type, first we did't estimate that we have a data more than `2 147 483 647`(max integer number\_ , but I have some data that bigger than max integer range, we input very data to that field and it not logic that install bigint module then remove integer field and create a bigint instead of it ( all of our data will lost), I know I can change table in mysql database by myself,but maybe in future needs update drupal to newer version , what is your suggestion to me ?

# Answer
> 3 votes
Use the bigint module.

> The default core fields do not include a bigint field. This module allows you to have a true BigInt (19) value. That means the number can contain 19 digits.

So, with this module you can define fields with the appropiate range.

Your problem now is to migrate data from your current field to a new bigint created field.

The usual steps will be:

* Create and configure the new bigint field.
* Edit affected nodes copying data form old int field to the new bigint field (using Batch API, for example). Or using a direct SQL commands, if your are brave enough.
* Update related configuration to use the new field (for example, Views).
* Delete de old field.

Depending on your usual workflow you can do this by different means:

* Manually, closing the web during update.
* Using Features for the configuration (fields, Views, etc).
* Update script (for example, a hook\_update\_N if you are using a installation profile).

---
Tags: entities
---


# Question
Title: Show the second depth term name and image along with its associated nodes title
I have a *Category* vocabulary.

* Electronics:
    + Notebooks
        - Asus
            * Node 1
        - Apple
            * Node 2
            * Node 3

I want to make a view to show popular categories, the second child term, the image field, along with 4 of its nodes.

# Answer
Ok based on what Joe said on previous answer I suggest a little modification to make it work:

> 1. Create a Taxonomy term based view
> 2. Add your preferred fields including "Radioactivity field" for sorting
> 3. Add Radioactivity Sort Criteria
> 4. Add a Relationship: Taxonomy term: Content with term
> 5. Add a Contextual filter: Content: "Has taxonomy term ID depth modifier" with the relationship of node (previously created relationship)

Based on your comment, you can use Aggregation as Joe mentioned before to lower the chance of duplication, but since you want just a specific number of items per category you might need to use a 3rd party module such as views\_limit\_grouping

> This is a basic Views style plugin that allows for a limit on the number of rows displayed within a grouping field.

ok, download and install the module the usual way and head back to your views. Remember that using this module you can group fields under another field. so you need a basic wrapper field (which is excluded from display)

> 1. Under Format Section Choose "Grouping Field (With Limit)"
> 2. Under Setting, Use your Radioactivity Field as the Grouping field Nr.1
> 3. There's a new setting after you enabled first grouping to LIMIT ITEMS TO BE DISPLAYED, so Set your preferred number and go on with the rest of Grouping field that you need.

Note that for having this module to work as it supposed to you have to set views default pager to "Display All Items".

Here is the output of my views on a project similar to this one you try to achieve:

```
$view = new view();
$view->name = 'popular_categories';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'Popular Categories';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Popular Categories';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'grouping_limit';
$handler->display->display_options['style_options']['grouping'] = array(
  0 => array(
    'field' => 'field_term_popularity',
    'rendered' => 1,
    'rendered_strip' => 0,
    'grouping-limit' => array(
      'grouping-limit' => '4',
      'grouping-offset' => '0',
    ),
  ),
  1 => array(
    'field' => 'field_term_image',
    'rendered' => 1,
    'rendered_strip' => 0,
    'grouping-limit' => array(
      'grouping-limit' => '1',
      'grouping-offset' => '0',
    ),
  ),
  2 => array(
    'field' => 'name',
    'rendered' => 1,
    'rendered_strip' => 0,
    'grouping-limit' => array(
      'grouping-limit' => '4',
      'grouping-offset' => '0',
    ),
  ),
);
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Taxonomy term: Content with term */
$handler->display->display_options['relationships']['nid']['id'] = 'nid';
$handler->display->display_options['relationships']['nid']['table'] = 'taxonomy_index';
$handler->display->display_options['relationships']['nid']['field'] = 'nid';
/* Field: Taxonomy term: Term ID */
$handler->display->display_options['fields']['tid']['id'] = 'tid';
$handler->display->display_options['fields']['tid']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['tid']['field'] = 'tid';
$handler->display->display_options['fields']['tid']['exclude'] = TRUE;
$handler->display->display_options['fields']['tid']['separator'] = '';
/* Field: Taxonomy term: Image */
$handler->display->display_options['fields']['field_term_image']['id'] = 'field_term_image';
$handler->display->display_options['fields']['field_term_image']['table'] = 'field_data_field_term_image';
$handler->display->display_options['fields']['field_term_image']['field'] = 'field_term_image';
$handler->display->display_options['fields']['field_term_image']['label'] = '';
$handler->display->display_options['fields']['field_term_image']['exclude'] = TRUE;
$handler->display->display_options['fields']['field_term_image']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_term_image']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['field_term_image']['settings'] = array(
  'image_style' => '',
  'image_link' => 'content',
  'field_formatter_class' => '',
);
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['exclude'] = TRUE;
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = TRUE;
/* Field: Taxonomy term: popularity */
$handler->display->display_options['fields']['field_term_popularity']['id'] = 'field_term_popularity';
$handler->display->display_options['fields']['field_term_popularity']['table'] = 'field_data_field_term_popularity';
$handler->display->display_options['fields']['field_term_popularity']['field'] = 'field_term_popularity';
$handler->display->display_options['fields']['field_term_popularity']['label'] = '';
$handler->display->display_options['fields']['field_term_popularity']['exclude'] = TRUE;
$handler->display->display_options['fields']['field_term_popularity']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_term_popularity']['click_sort_column'] = 'radioactivity_energy';
$handler->display->display_options['fields']['field_term_popularity']['settings'] = array(
  'energy' => '10',
  'type' => 'none',
  'accuracy' => '100',
  'field_formatter_class' => '',
);
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['relationship'] = 'nid';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['element_label_colon'] = FALSE;
/* Sort criterion: Global: Random */
$handler->display->display_options['sorts']['random']['id'] = 'random';
$handler->display->display_options['sorts']['random']['table'] = 'views';
$handler->display->display_options['sorts']['random']['field'] = 'random';
/* Sort criterion: Taxonomy term: popularity (field_term_popularity:radioactivity_energy) */
$handler->display->display_options['sorts']['field_term_popularity_radioactivity_energy']['id'] = 'field_term_popularity_radioactivity_energy';
$handler->display->display_options['sorts']['field_term_popularity_radioactivity_energy']['table'] = 'field_data_field_term_popularity';
$handler->display->display_options['sorts']['field_term_popularity_radioactivity_energy']['field'] = 'field_term_popularity_radioactivity_energy';
/* Contextual filter: Content: Has taxonomy term ID depth modifier */
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['id'] = 'term_node_tid_depth_modifier';
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['table'] = 'node';
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['field'] = 'term_node_tid_depth_modifier';
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['relationship'] = 'nid';
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['summary_options']['grouping'] = array(
  0 => array(
    'field' => 'field_term_popularity',
    'rendered' => 1,
    'rendered_strip' => 0,
    'grouping-limit' => array(
      'grouping-limit' => '4',
      'grouping-offset' => '0',
    ),
  ),
  1 => array(
    'field' => 'field_term_image',
    'rendered' => 1,
    'rendered_strip' => 0,
    'grouping-limit' => array(
      'grouping-limit' => '1',
      'grouping-offset' => '0',
    ),
  ),
  2 => array(
    'field' => 'name',
    'rendered' => 1,
    'rendered_strip' => 0,
    'grouping-limit' => array(
      'grouping-limit' => '4',
      'grouping-offset' => '0',
    ),
  ),
);
/* Filter criterion: Taxonomy vocabulary: Machine name */
$handler->display->display_options['filters']['machine_name']['id'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['table'] = 'taxonomy_vocabulary';
$handler->display->display_options['filters']['machine_name']['field'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['value'] = array(
  'tags' => 'tags',
);
/* Filter criterion: Taxonomy term: image (field_term_image:fid) */
$handler->display->display_options['filters']['field_term_image_fid']['id'] = 'field_term_image_fid';
$handler->display->display_options['filters']['field_term_image_fid']['table'] = 'field_data_field_term_image';
$handler->display->display_options['filters']['field_term_image_fid']['field'] = 'field_term_image_fid';
$handler->display->display_options['filters']['field_term_image_fid']['operator'] = '!=';
$handler->display->display_options['filters']['field_term_image_fid']['value']['value'] = '0';

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');
$handler->display->display_options['block_description'] = 'Popular Categories';
$translatables['popular_categories'] = array(
  t('Master'),
  t('Popular Categories'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('node'),
  t('Term ID'),
  t('.'),
  t('All'),
  t('Block'),
);

```

Let me know if you still have any other issues.
> 0 votes

# Answer
I've created a taxonomy that looks like this: Vocab: Electronics Terms:

* Notebooks
* Asus
* Apple
* Television
* Panasonic
* Sony

Then set up a view of Taxonomy Terms, using Filter Criteria to limit to your Electronics vocabulary (all straight forward so far). What will help you is adding Advanced \> Relationship \> *Taxonomy term: Content with term* . This will allow you to output the node fields that reference each term, per result.

Then enable Advanced \> other \> aggregation. This will allow you to group your results together by term.

To get closer to your required output, you can GROUP the fields using the FORMAT \> settings. Let me know if this takes you in the right direction, or even gets you close. Or if you've tried this all before and I can remove the answer.

NOTE: the node will reference a specific TERM. You can get access to that term's parent(s) tree etc, but bare in mind the relationships begin with the node-\>referenced TERM.
> 1 votes

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


# Question
Title: How do i customize theme_link() for a particular node, or view only?
i have a View that displays some DVD product teasers. What id like to do is customize or change the wording of the 'Read More' link of each teaser.

i also have another view where i want to remove that link altogether. now i know how to do this with CSS but i'm trying to learn how to override theme functions.

i have Themer Info turned on see a candidate function name for theme\_link() but i think that would override all the theme\_link functions for the entire site. how do i customize theme\_link() for a particular node?

and how do i find out what function calls theme\_link() ?, if i want to remove it entirely?

in other words, i need to get into $content variable!, how do i do that?

*much* *thanks* in advance!

# Answer
You can use `hook_node_view_alter(&$build)` and overwrite the link. Here is an example to change the `Read More` title and removing `Add comment` link. You can use `dpm()` function of **devel** module to see the array structure.

```
function mymodule_node_view_alter(&$build){
  if($build['#node']->type == 'DVD' && $build['#view_mode']=='teaser'){
    $build['links']['node']['#links']['node-readmore']['title'] = t('New Title');
    unset($build['links']['comment']['#links']['comment-add']);
  }

}

```
> 1 votes

# Answer
In a view admin page (/admin/structure/views/view/your\_view/edit/display\_id), you should have access to the Pager setting. In D7, this is in the middle column under Block Settings, Header, and Footer.

It's called "More Link". You can toggle that off/on per display and once it's on, you can then customize the text. Doesn't appear to use tokens, though, so might not help if you wanted something more dynamic.
> -1 votes

---
Tags: theming
---


# Question
Title: OAuth token parameter missing when configuring Google Analytics Reports
I'm displaying Google Analytics reports at my site using Google Analytics Reports module which uses Oauth.

At the localhost on my computer it works fine.

But on a site my.example.com it is showing "OAuth token parameter missing" when I go to "admin/config/system/google-analytics-reports" and press "Start setup and authorize account".

I see this error in the watchdog:

> Code: 401 - Error: Unauthorized - Message: GDataauthErrorAuthorizationInvalid Credentials

If I migrate my site from localhost to this site then also it works fine until I clear my cache.

# Answer
The Linux server running my.example.com which was giving problem had time lag of 45 minutes. The moment I corrected it .. it worked.
> 0 votes

---
Tags: 7, google-analytics
---


# Question
Title: Show users a view of nodes tagged with the terms they flagged - Drupal 7
I want users to be able to create taxonomy terms and other users to be able to flag these taxonomy terms (using the flag module, sort of Follow). Then i want each user to have a view of nodes which have been tagged with those taxonomy terms they flagged. Is this currently possible with views contextual filters? Any alternative also welcome.

Example use case: i flagged terms Technology and Business created by admin or other users. When a user posts a node tagged with Technology or Business, i will see the post on my wall (My wall is an admin created view of all nodes tagged with the terms that i have flagged)

# Answer
> 0 votes
Here is how this can be done:

1. In the View, add a Relationship to the node's taxonomy term (using "Content: Taxonomy terms on node")
2. Either add a filter criteria for the term, or add a contextual filter that would limit the terms to those flagged by the particular user.

---
Tags: 7, views, flags
---


# Question
Title: What function should I use in instead of mimemail()?
I was using `mimemail()`, a function defined from the MIME mail module, in Drupal 6 to send emails using attachments.

The Drupal 7 module doesn't have `mimemail()`.

What function should I use in Drupal 7, instead of `mimemail()`?

# Answer
The reason the `mimemail()` function does not exist for Drupal 7 is because it is not needed.

See, for instance, issue: API function for quick send html mail without uneccessary operations (mimemail analog from 6.x) in the project's issue queue;

> On Drupal 7 calling `drupal_mail()` is enough. See the `README.txt` and `drupal_mail_system()` for more information.

The general idea is that you set up the Drupal to use `MimeMailSystem` for some or all mail messages sent by your module:

```
mailsystem_set(array(
  '{$module}_{$key}' => 'MimeMailSystem', // Just messages with $key sent by $module.
  '{$module}' => 'MimeMailSystem', // All messages sent by $module.
));

```

and then calling `drupal_mail()` is enough.
> 3 votes

---
Tags: 7, mimemail
---


# Question
Title: Node relationships, backwards or forward?
I know node references are not as popular as entity references are, but I'm curious on backwards and forward relationships.

This is a use case I see someone doing.

Job \< -- Job Application

2 content types, and the node reference in the Job application point to Job.

In reality, shouldn't Job be pointing to the Job applications?

2nd use case

Project --\> Files

When you create a project, you attach files to it, most of the time files are known beforehand so additional ones after parent node creation would be unlikely.

This is the more "correct" way as I see it, a Project can "have many" files. I also notice it could be done in the reverse as well, a file could reference a project.

The whole idea of Many to one, one to many, and many to many relationships in Drupal using the node / entity references module really make me wonder.

With the project user case, you can use references dialog, and you can create children right then and there. Doing the reverse of that, creating a parent could be possible, but why would one do that?

I've watched many videos, and I can see people doing it both ways almost with no consistency. I almost get confused myself when thinking about this. I come from doing things where these relationships are a bit more defined, and the DB schema is setup as so.

So does it really matter which way you put the reference? Also is it bad to have 2 node reference each other? I noticed there is some back references modules etc, what use do these have outside of making it easier for views? Did they have provide any other practical uses? (I know views3 with the node reference module , back references work out of the box now). Does it really just come down to workflow and how it would be easiest to get the creation forms to have the experience you want?

If someone could clear this up for me, I would really appreciate it.

# Answer
> 1 votes
A one-to-many relationship (also in DB design) is typically created by referencing the parent from the child. In the Jobs/Job Applications case, this translates into a reference from Job Application to Job, not vice versa.

In the Project/File case, if each file can only belong to one project, then it's also a one-to-many relationship and so File should reference Project. This is definitely how it should be if we were designing database tables for those entities.

However, in terms of Drupal and node references and given this particular example, Files are almost like properties to the Project node. So I wouldn't be surprised to see Files referenced from Project in a multiple-value node reference field, just for convenience.

---
Tags: entities, nodes
---


# Question
Title: Can't locate where Commerce Authnet stores the API and Key
I am using Drupal Commerce and the Commerce\_authnet module to connected to Authorize.net. I have custom functionality which requires me to make a separate call to the Authorize.net CIM API. I have done so sucessfully by adding a submit handler to the Checkout button, catching the API Login and Key, and used those in my API calls.

```
$login = $form_state['values']['commerce_payment']['payment_methods']['authnet_aim|rules_authorize_net_aim_credit_card_test_association']['settings']['login'];
$key = $form_state['values']['commerce_payment']['payment_methods']['authnet_aim|rules_authorize_net_aim_credit_card_test_association']['settings']['tran_key'];
define("AUTHORIZENET_API_LOGIN_ID", $login);
define("AUTHORIZENET_TRANSACTION_KEY", $key);
```

However, I need to create a separate way of users updating their Authorize.net account settings from their user profile form. I have looked in the commerce database tables and in the drupal variable editor to see if I could pull it from the database, but I have not found where its stored. How can I access this data?

# Answer
I figured out how to retreive the credtials with this post https://stackoverflow.com/a/9996895/1015214.

You can get the rule machine name from the rules\_config table.
> 0 votes

# Answer
I'm assuming you're using the latest version of Commerce authnet.

Drupal Commerce payment system (as well as discounts, taxes..) is based in rules, you can see here how the settings form are included: http://cgit.drupalcode.org/commerce/tree/modules/payment/commerce\_payment.rules.inc#n250 in the rules UI, so it is basically stored by rules in a rules\_config object, specifically in the unserialized data column.

So if you want to see the settings in the database, you can go to rules\_config table and check the data db field.

Modifying this from outside rules is another story, I've never done this, but I'm quite sure that rules doesn't provide an API to alter this data field, you'll probably need to use the Database API to access rules\_config table and unserialize/serialize the data information to alter it.

It is probably advisable to find an alternative way to do this, i.e providing a new module that runs a slightly modified version of the charge callback of authnet (http://cgit.drupalcode.org/commerce\_authnet/tree/commerce\_authnet.module#n750)
> 2 votes

---
Tags: commerce, payment-gateways
---


# Question
Title: Alter a form in a block only if it is in a certain region
In my template.php I'm trying to alter a form in a views exposed block, but I only want to do this if that block is in a certain region in my theme.

I'm using Drupal 7.

Is that possible? What php code would I use?

Here is what I'm using now:

```
function cmfzen_form_alter(&$form, &$form_state, $form_id) {

  // change the main search form
  // see http://drupal.stackexchange.com/questions/28404/easiest-way-to-add-x-webkit-speech-to-the-search-blocks-input-element
  // see http://adaptivethemes.com/html5-placeholder-text-for-your-drupal-7-search-field
  if ($form_id == "views_exposed_form" && $form['#id'] == "views-exposed-form-site-search-page"){

    $form['site-search']['#type'] = 'searchfield';
    $form['site-search']['#attributes'] = array(
      'class' => array('search-site'),
      'placeholder' => t("I'm looking for..."),
      'speech x-webkit-speech spellcheck' => 'false',
      );
    // change form submit button

    $form['submit']['#attributes'] = array('class' => array('search-button'));
  }
}

```

# Answer
> 3 votes
use this code in `hook_form_alter`:

```
function cmfzen_form_alter(&$form, &$form_state, $form_id) {
    switch($form_id){
         case 'views_exposed_form':
         $region = 'NAME_OF_A_REGION';
         $blocks = block_list($region);
         kpr($blocks);
         //if the block is in the $blocks array do the changes.
         break;
    }
}

```

using `block_list($region)` you will get the blocks that are placed in a specific region, and it returns array of block objects (for more detail visit this page). Now check if the block you are looking for is in the `$blocks` array.

# Answer
> 1 votes
Try this

```

function cmfzen_form_alter(&$form, &$form_state, $form_id) {

  if (**block_load**('views','-exp-site_search-page')->region == 'header' &&
    $form_id == "views_exposed_form" &&
    $form['#id'] == "views-exposed-form-site-search-page"
  ) {
    // alter form
  }
}

```

Change 'header' to your region name and ensure the block delta '-exp-site\_search-page' is the right one.

One more solution (may be better performance) is to make your own function that queries the database for just the region of a block :

```

function mymodule_block_region($module,$delta) {
    return **db_query**('SELECT region FROM {block} WHERE module = :module AND delta = :delta'
    , array(':module' => $module, ':delta' => $delta))->**fetchField**();
}

```

And then use it instead of `block_load('views','-exp-site_search-page')->region`

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


# Question
Title: Enabling a block to inherit the settings of a sub theme
Being relatively new to Drupal, I apologize in advance if what I'm saying is unclear, but I'd imagine that a fix should be simple enough:

Basically, I'd like to add a header block that functions identically to the other block regions on my Drupal site. At the moment, the text of that header is not responsive to window size, unlike the rest of the site. How can I inherit the default settings of my theme when creating a new block?

Thanks in advance, a solution to this would help me tremendously.

# Answer
You can style a block however you like - since it is going in the header, it sounds like a css issue for the header region. I would start by comparing the css for the content and/or footer regions with that of the header. If all else fails, you can theme individual blocks - here is some info.
> 0 votes

---
Tags: blocks
---


# Question
Title: I want the view to show no results when the filter doesn't containing anything
I am trying to use the Views module for an auto-submit field, to get the names from my taxonomies. How can I get the field to show the results after the users type something into the input box, instead of showing all the results when nothing has been entered as value for the filter?

I have tried a number of contextual filters but no luck.

This what the current search looks like, if I type in one of the terms or the field name it matches up to what I type which is how i wanted it to work, the problem is the the results are showing by default before I type anything.

# Answer
> 15 votes
This is built into views 3:

1. Edit your view
2. Set Advanced | Exposed Form | Exposed Form Style to **input required**

# Answer
> 13 votes
If you set the exposed filter to "Required" with nothing in the default 'Value' box, then the view shows nothing until a user fills in and uses it.

Tip: If you find that your exposed filter doesn't show up when it is empty, then (after checking 'Use AJAX' is selected if it's a block) add something to the view's "No results behavior" field on the right, such as a `Global: Text area` containing a space or ` `.

---

Another option is setting a default value that doesn't match anything - for example, if the default value is a friendly message like "Enter team name here" or "Search teams", or something neutral like "0" or "–––", there will be no matches until they enter their input, so the view will be blank until they enter input. This does mean there will be one unneccessary extra query on the page - but this should usually be cached.

If you use the default, for improved usability, you can do what the "Search finance" text in the Google page you link to does, and save your users the inconvenience of deleting that default entry themselves with some jquery code that clears the field when it gains focus, and for even better usability, you can style the default text to be lightly greyed out, then remove this style when the field gains focus.

There are lots of guides out there on how to do this, I won't duplicate them here. Here's one example. You could drop code like that into your theme's scripts.js file (using `Drupal.behaviors` instead of `$(document).ready` so it still works when elements get updated by AJAX). There might be a way to do this in Drupal php on the server side or in configuration too, but I don't know of one off the top of my head.

You can also get the **best of both** options, avoiding that extra query and only showing the default "Search..." text to people who have Javascript enabled (who it won't be a nuisance to), by ticking the "Required" checkbox, leaving `Value` blank, and using something like `$('#whatever-the-input-field-is').attr('value', 'Search teams');` in addition to code like the above to write in the friendly disappearing message on page load, only for people with javascript is enabled, without causing a query that will find nothing.

---

If I misunderstood your question, and it's the autocomplete feature you're asking about, then check out autocomplete\_deluxe

---
Tags: 7, views
---


# Question
Title: Schedule a mail on the 1st day of the following month
I currently have a rule set up using scheduler which - when a user logs in, a rule component is scheduled to send a mail '+1 week' from this time. This works fine.

However, I need to alter this so when the user logs in - the component mail is scheduled for the 1st of the following month.

Essentially, for example: if a user logs in today 16-06-14 - the component is scheduled to be executed on the 01-07-14.

Any ideas? Not sure how to set the offset. Would this be better via cron instead?

# Answer
> 2 votes
Try **"first day of +1 month"** as your scheduled date.

---
Tags: rules
---


# Question
Title: Make a block from a "part" of a drop down menu
I have a D7 site with a drop down menu at the top, the second item across the top is "About Us". Presently it looks like this, see attached pic.

I want the "contents" of this part of the menu to be a "BLOCK" that I can display on several pages. How can I do that?

In Drupal menus, the arrangement looks like this, see attached pic:

The menu item "about us" has a URL of "about-us". I'd like the content of this to show up in a sidebar that I could drop in perhaps as a block or other method. How can I make a block out of just a "section" of a menu, and yet have this as dynamic content? I want the users to be able to edit the list of menu links included in "about-us" but not have to manually put the contents of the new links into the sidebar. I'm thinking of maybe a "view" but I've never made a view of a menu before.

Thanks for the help.

Dave N

# Answer
I would advise using menu block (https://drupal.org/project/menu\_block), which allows blocks to be created from menus. The most important part would probably be starting level and max depth, which allows you to specify the options you'd like to use.

If you'd like an example usage similar to what you're attempting to achieve, just let me know and I'll take some screenshots.
> 1 votes

---
Tags: 7, routes, blocks
---


# Question
Title: Allow user to enter unpublished content from the site in Drupal 7
I have a content type "User Bio" in my Drupal 7 site. On my site I created a form with all the fields in User Bio for the anonymous user to fill.

Now when the user enters and submits this information I want the node of "User Bio" type to be created but it should be unpublished. When the admin reviews, only then it can be published.

Is there a way to do it?

Thanks

# Answer
> 1 votes
Workbench Moderation Module might be a good candidate for your requirement.

> Workbench Moderation adds arbitrary moderation states to Drupal core's "unpublished" and "published" node states, and affects the behavior of node revisions when nodes are published. Moderation states are tracked per-revision; rather than moderating nodes, Workbench Moderation moderates revisions.

But if are considering to use user bio to create user profiles after admin publishes the user bio content, I would recommend you to use User entity instead of having a separate content type.

# Answer
> 2 votes
You will probably want to set the content type to not be published by default, by simply editing the content type, and un-checking "Published" in the lower tab menu.

This will create the content unpublished, and from there you can handle the approval process however you'd like.

---
Tags: nodes
---


# Question
Title: Standard bootstrap main menu with dropdown?
When using bootstrap with drupal what is the standard way to create a main menu?

When I add the main menu block to a region it does not display as a bootstrap navbar.

When I try with superfish I can add some classes but for example the active-trail cant be changed on li.

# Answer
Your "standard" Bootstrap subtheme launches with your "standard" Bootstrap Nav Bar. For most intents and purposes this is the main-menu... links added to the main menu at admin/structure/menu/manage/main-menu appear there ...

Oddly the navbar isn't available to configure from the blocks page as you might expect nevertheless ... there are some navbar options available under admin/appearance/your-bootstrap-subtheme/settings.
> 1 votes

---
Tags: routes, navigation
---