title: My server ignores the .htaccess file

text:
# Question
Title: My server ignores the .htaccess file
I have a terrible problem: I have written rubbish within the *.htaccess* file, in order to break my web site, and cause an error 500. Result: nothing, nothing happens, the web site continues to be online.

That is, **the *.htaccess* file is ignored completely**. Why does this happen? I understand that this only has an answer: the Apache server is misconfigured. This is absolutely correct? Or are there other possible causes?

My file system: image 1 and image 2.

Originally the website was hosted on a folder within a server (mydomain.com/folder), and everything worked fine. Now I am migrating the website to another server, but within a subdomain. The features of the new server:

* **Subdomain:** domain.company.com
* **Apache:** 2.4.7 (*Ubuntu*)
* **Port:** 80
* **phpinfo:** Open phpinfo

**UPDATE.**

1) **DNS.** I checked my subdomain with http://whois.domaintools.com/ and http://mxtoolbox.com/SuperTool.aspx. I found no problems.

2) **.htaccess.** The file contains RewriteEngine on. RewriteBase is commented, because I don't know what to put when a subdomain. Anyway, no matter what I put in the file, it is completely ignored.

3) My **settings.php** has:

I cleared the cache Drupal. I cleared the browser cache. I truncate all tables that start with cache\_.

**It does not work.** The file .htaccess remains ignored. This, I can not enable friendly URLs.

# Answer
This generally happens when your web server does not have access to make the overrides to your webroot.

Check if your `httpd.conf` file has something of the following format

```
<Directory "/Applications/MAMP/htdocs">
    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   Options FileInfo AuthConfig Limit
    #
    AllowOverride All

    #
    # Controls who can get stuff from this server.
    #
    Order allow,deny
    Allow from all

</Directory>

```

The important piece above is `AllowOverride All`, which will make possible for *your* .htaccess file to override the settings.

If you cannot change the settings in this file, I would recommend you to create a `.conf` file specific to your site (e.g. `mysite.conf` using the default file `000-default`) in on of `/etc/apache2/sites-enabled` or `/etc/apache2/sites-available`, and modify the `<Directory>` tag to point to the root of your site.

Restart Apache in order to make this change visible. The site should now be able to pick up your `.htaccess` file.
> 4 votes

# Answer
Make sure you have:

1) DNS setup properly

2) .htaccess - Look for the RewriteBase setting AND RewriteEngine on

3) settings.php - Look for $base\_url and $base\_path

Don't forget to clear the cache after you change these settings. If you can't access the site, use drush cc all or login to your database and truncate all tables that start with cache\_ (sometimes clearing the cache still leaves persistent entries).
> 0 votes

---
Tags: .htaccess, uri
---


# Question
Title: Create View with a join on the same content type
I am trying to create a View that produces 1 stop itineraries. I have a content type `"Route"`, with the following fields.

```
From To Method

```

The data looks like:

```
From | To | Method
 A   | B  | Method 1
 A   | Z  | Method 3
 B   | C  | Method 3
 Z   | C  | Method 3

```

If a user searches `"From: A"`, `"To: C",` the view should return:

```
From | To | From | To |
 A   | B  |  B   |  C |
 A   | Z  |  Z   |  C |

```

which ultimately results in B and Z as the intersection points (and a more friendly output to the user).

```
From | Via | To
 A   |  B  | C
 A   |  Z  | C

```

For the life of me, I cannot figure out how to produce this join against the route table.

Any advice? I have even replicated the Route content type to `"Route 2"`, and attempted a relationship on the inner `"From"` and `"To"` fields of Route and Route 2, but cannot produce this expected output. Any advice?

# Answer
> 1 votes
Install Equi Join module

> The Equi Join module allows you to create relationships between different entities based on an arbitrary field. This allows the use of relationships in Views without having to add Node References to a content type, which may not be an option when displaying data stored on a third-party database or data provided through custom Views handlers. That said, it works with nodes as well.

Using only a **single** content type `Route` create your view as follows:

1. Add your `from` and `to` fields.
2. Add a Relationship of `Equi Join: Content` and give it a name. Set Left field to `field_to` and Right field to `field_from`
3. Add a second set of `from` and `to` fields, but set the relationship on them to the new Relationship you added.
4. If you wish you can then either remove the first `To` field or the second `From` field.

---
Tags: views
---


# Question
Title: Display a grid view without border columns
I'm trying to display a specific number of products in a e-commerce drupal site in the front page.

I would like to use a display as in my theme's demo : http://demo.morethanthemes.com/tophit/

I tried one module for horizontal slideshow but it turned out to have some bugs and another one for responsive grid did not help me fix my problem.

I am now using the original grid view, without pager.

I want to change the column color from grey to white, in order to be my products aligned but not displayed as a table.

Do you know any way to simple display a set of products/nodes horizontal ? I prefer to use views, because the products probably will change.

Thank you,

Konstantina

# Answer
> 0 votes
I would use the Views Slideshow Module to build your slider, it's been the easiest to install and configure in my experience.

As far as changing colors, you are likely going to need to change your theme's CSS, which is not a Drupal specific problem. This search should get you started.

# Answer
> 0 votes
The basic views grid display format is not very suitable for a 'tile' layout as it is not responsive, meaning that it will not work very well on mobile phones. Try resizing your browser window to see this.

You have a number of options. For Drupal 7 you could try Views Responsive Grid module https://www.drupal.org/project/views\_responsive\_grid . This will probably get you where you want to be with the minimum of css theming work.

Your chosen theme uses the Bootstrap framework and therefore a better fit will probably be Views Bootstrap module https://www.drupal.org/project/views\_bootstrap \- Indeed your theme may already be using this. If this is the case then the answer to your grid questions will be about using the correct Bootstrap classes in your view. This module allows you to do this without diving into css code.

To get more out of your theme, learning about Bootstrap will be time well spent and the following videos may help get you started

https://www.youtube.com/watch?v=jWfYKdCEpOc

https://www.youtube.com/watch?v=g3j7eRunzv4

As Scott Joudry says, when we start asking about colors, css and frameworks we are straying away from asking about Drupal, but given that Bookstrap is well used by the Drupal community I think there is a place for some of your questions here.

---
Tags: 7, views
---


# Question
Title: Is there any preprocess hook for date api?
As I asked in above, Is there any **theme preprocess hook** for all of the dates that displayed in Themes Files?
I want to perform some mathematical operations on Dates that show on any content type, Is there any solution to achieve it in my **Themes** Files.

# Answer
Date API introduces several theme functions:

* theme\_date\_combo
* theme\_date\_display\_combination
* theme\_date\_display\_interval
* theme\_date\_display\_range
* theme\_date\_display\_single
* theme\_date\_text\_parts

All of which can be preprocessed.

If the output you need to override isn't the result of one of those functions, you'll need to look for a different solution (e.g. depending on context you might be able to preprocess a field template).
> 1 votes

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


# Question
Title: Add a span and class to menu items that has children
I'm customizing the main menu using the Menu Block Module. I need to set a class for all li elements that has children regardless of level. I might need to add a span inside the a-tags as well. Is it possible to do this in the template.php or do I need to alter module files. I would preffere not to edit module files if possible.

Like:

```
<li class="expanded menu-mlid-871 has-children">
   <a href="...">Menu item name<span class="test"></span></a>
   <ul> <!-- (children items) --> <ul>
</li>

```

Is this doable with some:

```
function theme_menu_link(array $variables) { ...?... }

```

\[edit\]

Menu items with no children has the `class="leaf"`. It should be possible to style the menu items `li` (has children) and then cancel the rule-set for the class `li.leaf` (has no children). The span can be added by using some `li::after` rule-set and removed with eg `li.leaf::after {display:none;}`

In this way it can be solved with CSS only. The problem is I need to use the `<span class="test"></span>` for a click event. So at least I need a real span inside the `li a` witch is not a "leaf".

Anyone who can help me with a theme functions for this?

# Answer
Menu items with no children has the `class="leaf"`. It is possible to style the menu items `li` (has children) and then cancel the rule-set for the class `li.leaf` (has no children).

A span can be added to all li's (set to display:none for leafs). How do I insert a \<span\> \</span\> tag inside the \<a\> \</a\> tag on my main menu
> 0 votes

---
Tags: blocks
---


# Question
Title: Is in Drupal the way to cache whole region?
I have a region which contain several blocks, each of them is changed rarely. I want to cache whole region (for each user), but i can not find the solution. Watching into the sourses gives no result too. Is anybody who knows is it possible, and how to do that? Thank you for every answer!

# Answer
Rather cache the individual blocks. There is a module for that: Block Cache Alter

> Alter cache settings per block. Cache settings per block are now set in code, but if you don't like the default - usually none - you can now easily change this. Install this to speed up block rendering for authenticated users.

It will give you the optioon in the Block UI to alter the cache settings for that block:
> 0 votes

---
Tags: caching, theming
---


# Question
Title: maintenance-page--offline template not working
I am following this tutorial. https://www.drupal.org/node/195435. I have created maintenance page and its working with admin configuration site under maintenance setting. I want to create dboffline mode maintenance page. so for that, i have created another tpl "maintenance-page--offline" in same directory where "maintenance-page.tpl.php" has created. Path is like `sites/all/theme/mytheme/templates/`.

previously it was working but currently its showing me `Additional uncaught exception thrown while handling exception.` error. Its not overriding maintenance-page--offline when i am disconnecting DB, by entering wrong password in settings.php file.

# Answer
This is caused when `class_exists()` is being called from within `alpha_get_theme()` and autoloading fails. I have a patch that fixes this by wrapping those calls in a try/catch block. I'm not quite sure what should be done in the case of an error though, so I have just done nothing.

See theme Omega issue =\> https://www.drupal.org/node/1722586

It is working for me, I had the same problem.
> 0 votes

---
Tags: theming, maintenance-mode
---


# Question
Title: how can add external php function or class to theme file?
As I asked above, is it possible to add or include externally written classes or functions files to drupal theme files e.g 'theme\_name.theme' file?

# Answer
> 4 votes
A .theme file is processed as PHP - anything you can do in a PHP file, you can do in your theme's .theme file.

So if you want a service:

```
$some_service = \Drupal::service('foo');

```

Or a function from a module file:

```
module_load_include('inc', 'foo_module');

```

And so on.

---
Tags: 8, theming
---


# Question
Title: How to create template file for specific node?
As I asked above is it possible to create template file for specific node id.
I now we can create template file for content type, but not clear for node id.

E.g. Suppose there are 10 Articles in website, each has node id from 1-10. Now question is I want to create template file for node id 3. When user visit article node id 4, then user will see different page.

# Answer
In Drupal 7, you can use node--\[node-id\].tpl.php for theming specific nodes. In your case, you can use node--3.tpl.php.
> 0 votes

---
Tags: theming
---


# Question
Title: Change a variable dynamically without it persisting in the DB
I am wanting to change a variable (google analytics ID) programmatically based on the environment, BUT I do not want to change the saved value, so variable\_set() is not an option.

Ideally I would also like the value that I set to be cached so as to not undermine performance.

# Answer
So this is what I came up with, an implementation of hook\_init(). Perhaps there is a better solution?

```
function MYMODULE_init() {
  global $conf;

  // If we have the environmental variable ENV && we are not on a config page
  if ($env = getenv('ENV') && current_path() != 'admin/config/system/googleanalytics') {

    // Alter the googleanalytics_account ID
    if ($env == 'dev') {
      $conf['googleanalytics_account'] = 'UA-xxxxxxxx-x';
    }
  }
}

```
> 0 votes

---
Tags: 7
---


# Question
Title: Facetapi combined filter of city and zip code
I am using address field module with search api and facetapi modules.

I want one filter of two fields, city and zip code. Which will be an autocomplete field.

I have used the Search API Combined Fields module. Created a combined fields filter with the following configurations:

```
Imitate field : Address » Locality (i.e. City)
Contained fields : Address » Locality (i.e. City), Address » Postal code

```

But the problem is, in facet settings I can see only links and links with checkboxes widgets. there is no autocomplete widget.

and second when I select one of a widget from links and links with checkboxes, it only displays the city names on the search page.

can anyone know the solution for this?

# Answer
I used the search\_api\_combined.

In the search index, there will be a new tab with the name "autocomplete". Go to that tab and select your view and save the settings.

Then in the view filter, select your desired field and make it expose filter.

And also make that combined field a multivalue field with type *full text*.
> 0 votes

---
Tags: 7, ajax, search, entities
---


# Question
Title: If Drupal Commerce Cart is not Empty, add a class to body
I'd like to add a class to body if the current user's cart is not empty.

I'd like to take the preprocess approach and not using rules.

so far using commerce\_cart\_order\_load function I came up with this in template.php:

```
function THEME_preprocess_html(&$vars) {
    global $user;
    $order = commerce_cart_order_load($user->uid);

    if ($order != 0) {
        $vars['classes_array'][] = 'cart-loaded';
    }
}

```

but unfortunately it throws an unknown error.

# Answer
Using this resource and thanks to @rémy I come up with this solution:

```
function THEME_preprocess_html(&$vars) {
    global $user;
    $cart = commerce_cart_order_load($user->uid);
    foreach (entity_metadata_wrapper('commerce_order', $cart)->commerce_line_items as $delta => $line_item_wrapper) {
      if (in_array($line_item_wrapper->type->value(), commerce_product_line_item_types())) {
        $vars['classes_array'][] = 'cart-loaded';
      }
    }
}

```

> So after a while of testing I ended up with an error with anonymous users, so I digged a little bit deeper and come up with something new and no errors this time:

```
function THEMENAME_preprocess_html(&$vars) {
    global $user;
    $quantity = 0;
    $order = commerce_cart_order_load($user->uid);
    if ($order) {
        $wrapper = entity_metadata_wrapper('commerce_order', $order);
        $line_items = $wrapper->commerce_line_items;
        $quantity = commerce_line_items_quantity($line_items, commerce_product_line_item_types());
        if ($quantity) {
            $vars['classes_array'][] = 'cart-loaded';
        }
    }
}

```
> 5 votes

# Answer
Using rules you would probably need to install context and context\_rules module .., see here Is it possible to add css class to the page's body tag with rules when certain conditions are met?

So i would go with this approach: Function to determine whether my Cart is empty?

But doing it in preprocess html like here: https://stackoverflow.com/questions/7700838/adding-a-class-to-body/7700886

If you're using ajax cart (fe with dc\_ajax\_add\_cart) you'll need to write some javascript too ..
> 2 votes

---
Tags: 7, theming, commerce
---


# Question
Title: How are the default search results are sorted on D7?
I have a basic search configured on my site. I wanted to know how is the default search results are sorted in drupal, is it by the number of words found on the content or based on date the content is created or something else. I know it can be altered using custom modules. But I am curious to know how default on works.

# Answer
> 2 votes
Drupal's defaul search result is sorting on the basis of:

1. Number of comments
2. Keyword relevance
3. Content is sticky at top of lists
4. Content is promoted to the front page
5. Recently posted

Under Content Ranking configuration (admin/config/search/settings) you can setup the influence of the above factors while searching.

Thanks, ARUN AK

---
Tags: search
---


title: Need help with Views and Glossary

text:
# Question
Title: Need help with Views and Glossary
Note: as a neophyte user, I'm not allowed multiple links or images. It has been suggested that I edit my original content in order to add updates. Also it's been suggested to edit the hyperlinks so they're not quite right. Hopefully you can sort out what's going on.

I've been following this post by Kristin Brinner "Drupal Tutorial: Use Views to Create an Alphabetical List of Taxonomy Terms" (at h ttp://getlevelten.com/blog/kristin-brinner/drupal-tutorial-use-views-create-alphabetical-list-taxonomy-terms) but my sample does not produce the results illustrated and by now I'm very confused.

Part 1: said to create new view showing taxonomy terms, display in grid format and create menu link. Done.

Part 2: grouped terms alphabetically (add Taxonomy term: Name, label it "Grouping", exclude from display, rewrite to max length = 1 and uncheck 'trim on word boundary' and 'add ellipsis'). Under Grid-Settings use "Grouping" apply to all displays. My view looks like the sample. Done.

Part 3, Create a Views page for each letter of the alphabet: said to add a Contextual Filter: Taxonomy term: Name. When the filter value is NOT in the url, display all results for specified field. Under More, click Glossary mode, character limit = 1. Note that I now have a Taxonomy term: Name in the Contextual Filter section. *I don't know how to test these results.*

Part 4, Create A-Z list (create a block that will display the list of first letters in a cute list above the grouping grids) says to add a **new** Contextual Filter for this block (override). When the filter value is not available, 'display a summary', sort by alphabetical, unformatted, display record count and display items inline. This isn't working as predicted, here is what the tutorial says should be the result: **Image 1** in the diagram (h ttp://imgur.com/l9TbLyv). My content continues to look the same as it did previously in the exercise, i.e. like this: **Image 2** in the diagram. However when I put "S" into the Preview with contextual filters, I get: **Image 3** in the diagram. I was asked for screenshots, so without contextual filters is h ttp://imgur.com/zXCnsvA and with "s" in contextual filters is h ttp://imgur.com/7DF6UUD .

When I created the new contextual filter in Part 4, I got a copy of what was in the Page, so I have **two** contextual filters, both with Taxonomy term: Name. If I delete the first contextual filter from the block, then my preview shows the same information as **Image 1** in the diagram. I think I'm missing something &/or the blog post is unclear. Should I have started "this block override" with 0 contextual filters? I.e. Should I have started by deleting elements from the page which were copied into the block?

Part 5 instructs to "Add the alphabetical list on our page with the grouped terms and Go back to our Page display".

I've got the view working correctly now. The thing which stumped me was that adding a block created an entire copy of the original page which (philosophically) I don't understand. When there's a page and a block override which give instructions about the view, how does drupal know which instructions to pay attention to?

Thanks to all the folks who have helped.

# Answer
I am posting here in return, my block configuration, you will see that your contextual filters differ from mine, and for that matter, from what the tutorial describes.

Whatmore, the tutorial from Kristin Brinner describes in "Part 4. Create A-Z list" how to set up this block, which is what I did and got the expected result.

I would suggest you go through that part in the Tutorial again, the block you have at the moment is not configured according to the instructions of the tutorial.

And a useful quote from the Views 3 Handbook (accessible via Advanced Help):

> Each display can have its own settings, but when created, a display will take all of its basic settings from the default display which all Views must have. For most settings, there is an override button that will override that single setting for the current display. Overridden settings will have a mark in the summary for that display. All 'default display settings' are shown in the other displays in 'italic'. When you override a setting, then it is shown 'normal'.

Will keep an eye on this post! Best of luck!
> 1 votes

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


title: How to implement facets in Views

text:
# Question
Title: How to implement facets in Views
I'm trying to implement a search function with location in Drupal.

At the moment I have a base setup with a custom Content Type (Discount), which has a Geofield parameter. This gets indexed in Solr with the proper fields, filters and facets.

Then, after this I see there are two options:

* One is using directly Search API, which creates a search page with the facets. (Ok, deadly simple and works). Problem: I can't do really strange things like showing stuff on a map.
* Use Views with Search API: it is also quite simple and I can show the output in a map (as well as I'm more used to them). However, I don't have any idea on how to implement facets there... I took as a reference this project.

I've tried with both this options and I can make them work properly.

So, my question is, how do I add a map to the Search Page in Search API, or how do I add facets into the Views page. I'd rather prefer views if possible, as I'm trying to setup a system which detects all the Discounts in a certain distance in your area, depending on your geolocated IP.

The only idea I have would be to create a Taxonomy, with which I could tag the Discounts with Country and category, and then use that somehow in the view, but not quite sure on how to do so.

Thanks a lot!

# Answer
> 0 votes
Ok, I answer myself as I realized what I was doing wrong. Just make sure that the facets you are selecting are the indexed facets, so this way they match with the indexed fields you want to filter by.

It works really nice now!

---
Tags: search, location, views
---


# Question
Title: Deleting feature[]=logo from .info file, enlarged the whole website font-size?
During the theme learning I deleted the `feature[]=logo` line from .info file to check its effect at UI. As expected it got deleted from the toggle list at appearance-\>theme-\>toggle option. But simultaneously font-size of whole site got increased, I re-wrote the `feature[]=logo` in .info, saved, cleared cache, but no effect. Something wrong has happened, has anybody experienced this? I am searching but not getting such kind of issue.

# Answer
@codenext: Can you paste the screenshot of the css in chrome devtools. So that we can see which css code is creating that problem?
> 2 votes

# Answer
check this page for a detailed instructions.

Drupal theme settings
> 0 votes

---
Tags: 7, theming, .info
---


# Question
Title: Advantage of including file in .info file and also in hook_theme()
While studying the code in the Elements module, I noticed that the file `elements.theme.inc` is listed in `elements.info`, but is also listed for each theme implementation in `elements_theme()`.

## elements.info

```
name = Elements
description = Provides a library of Form API elements.
core = 7.x
files[] = elements.module
files[] = elements.theme.inc

```

## elements.module -\> elements\_theme()

```
function elements_theme() {
  return array(
    'emailfield' => array(
      'arguments' => array('element' => NULL),
      'render element' => 'element',
      'file' => 'elements.theme.inc',
    ),
    'searchfield' => array(
      'arguments' => array('element' => NULL),
      'render element' => 'element',
      'file' => 'elements.theme.inc',
    ),
    'telfield' => array(
      'arguments' => array('element' => NULL),
      'render element' => 'element',
      'file' => 'elements.theme.inc',
    ),
    'urlfield' => array(
      'arguments' => array('element' => NULL),
      'render element' => 'element',
      'file' => 'elements.theme.inc',
    ),
    'numberfield' => array(
      'arguments' => array('element' => NULL),
      'render element' => 'element',
      'file' => 'elements.theme.inc',
    ),
    'rangefield' => array(
      'arguments' => array('element' => NULL),
      'render element' => 'element',
      'file' => 'elements.theme.inc',
    ),
  );
}

```

# The Question

is there any advantage or performance improvement from listing the `elements.theme.inc` file in both places? Is there another reason why this might be necessary?

As always, I appreciate all responses.

# Answer
The Elements module is using that slightly incorrectly; `files[]` is used to inform Drupal's autoloader of files that contain classes, so that they can be used without manually including the file they're declared in.

As elements.theme.inc doesn't contain any classes, listing it in `files[]` actually does nothing at all. Though it doesn't cause any problems, such is the nature of autoloading.

So to directly answer the question, there can't really be an advantage of using one method over another, as they're used for different things. If elements.theme.inc contained a class as well as the theme functions, it would be perfectly valid to have both declarations.

As an aside, I've seen this plenty of times before - there was a bit of confusion when D7 first came out as to what `files[]` was for, and quite a few people chose to list all of, or the 'main' files of, their module.
> 2 votes

# Answer
Theme files should be included in hook\_theme().

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_theme/7

> **file:** The file the implementation resides in. This file will be included prior to the theme being rendered, to make sure that the function or preprocess function (as needed) is actually loaded; this makes it possible to split theme functions out into separate files quite easily.

Files, declared in .info should include dynamic-loading code registry (class or interface). https://www.drupal.org/node/542202#files

> Drupal supports a dynamic-loading code registry. To support it, all modules must declare any code files containing class or interface declarations in the .info file. When a module is enabled, Drupal will rescan all declared files and index all the classes and interfaces that it finds. Classes will be loaded automatically by PHP when they are first accessed.
> 1 votes

---
Tags: theming, forms
---


# Question
Title: Dynamically loading terms in a term reference tree from a huge taxonomy so users may select nodes as options
I'm trying to create a form that uses a bushy taxonomy of about 30,000 (max depth is ~9) terms to allow users to select multiple nodes from the tree. The Taxonomy Term Reference Tree Widget fits the functionality I need perfectly, but with the size tree that I'm using each expand/collapse or select event takes a couple of seconds to complete, which isn't acceptable in terms of performance.

I'm new to drupal, but haven't been able to find a widget that can perform this task quickly. Are there any D7 widgets or modules that can accomplish this task? It seems that if I were able to have the widget not load all of the children all at once that performance might increase, but I can't say I'm sure.

# Answer
> 1 votes
You can try some contrib modules:
Hierarchical Select

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

Simple hierarchical select

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

You can use it with High-performance JavaScript callback handler

Also you can try https://www.drupal.org/project/views\_jstree

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


# Question
Title: Fallback value for contextual filter, in case the "provided default value" does not exist
I want to display a block on each page (nodes as well as pages created by Views) that displays links to nodes that are tagged with a certain taxonomy term.

How to decide which tag should be used:

* **{1}** If the page is a node that references a taxonomy term:
use the referenced term
* **{2}** If the page is a node that doesn’t reference a taxonomy term (= empty value):
use the term with ID 1
* **{3}** If the page is not a node (= created by Views):
use the term with ID 1

I managed to get the links shown in case **{1}**, by using the relationship "Content: Taxonomy terms on node" and the contextual filter "Taxonomy term: Term ID" which uses the relationship.

I selected "Provide a default value" (Type: "Taxonomy term ID from URL" + "Load default filter from node page, that’s good for related taxonomy blocks"). So I can’t specify the default value here for case **{2}** and **{3}**.

Then I thought I could use the validation options somehow, but "Action to take if filter value does not validate" does not allow me to set a specific value in case the original default value does not exist.

How could I solve this?

**tl;dr:** I need something like: Take term ID from URL (via node ID), and if this gives no term ID, use term ID 1 instead.

# Answer
> 0 votes
Just set your contextual filter to return 1 when the value is not available like so:

---
Tags: 7, views
---


title: Custom Module Login

text:
# Question
Title: Custom Module Login
I am trying to write a module in which I have to send a mail if the user enters wrong password three times. In the mail he should have a link to reset his password. What should I write in validation function for failed attempts? Please guide me.

I got one suggestion you could also just set the variable 'user\_failed\_login\_user\_limit' to 3, and add an extra validation function to login which triggers an email when flood control triggers.Please guide me how to do this.

```
/**
 *Implement hook_form_alter()
 *
 */

 function login_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'user_login':
    case 'user_login_block':
      $user_login_final_validate_index = array_search('user_login_final_validate', $form['#validate']);
      if ($user_login_final_validate_index >= 0) {
        $form['#validate'][$user_login_final_validate_index] = 'login_final_validate';
  }
    break;
  }
}

 function login_final_validate($form, &$form_state) {
 //debug($form_state);
  if($form_state['values']['pass'] != 'abc') {
        form_set_error('pass',t('Sorry, there have being three failed login
        attempts for this account.A link has being sent to reset pass.'));
    }
  }

```

# Answer
> 0 votes
The User module uses 4 persistent variables to limit the number of attempted logins a user can do: user\_failed\_login\_ip\_limit (default to 50), user\_failed\_login\_ip\_window (3600), user\_failed\_login\_user\_limit (5), and user\_failed\_login\_user\_window (21600).
The first two are used before to check if the account with those credentials exists; the last two are used after loading the user account matching the credentials passed in the login form. The first two values set a limit of 50 failed attempts per hour for the same IP; the last two values allow 5 failed attempts every 6 hours.

Considering that the first limit is reasonably high limit to handle the case of only one apparent IP for all users at an institution, you could set user\_failed\_login\_user\_limit to 3 and user\_failed\_login\_user\_window to 3600 (1 hour). If that is the only change you need, there isn't any need to replace the validation handler for the login form: Just set the value of those persistent variables in `hook_install()`, and eventually check their values in a hook that Drupal executes less or more periodically.

---
Tags: users
---


# Question
Title: How to add Search form/Advanced search form view to advanced forum pages?
I found two things in Advanced forum.

**1.** Advanced forum provides the views, one of which is advanced forum search as shown in the following image, which provide the specific search on the forum.

**2.** But it is a separate link, and totally separate page, if it will be under the title of the advanced forum topic and on every forum discussion page, it will be very suitable for visitors. As shown in this image.

Now, how to add that advanced forum box and advanced option selection box provided in views under the forum title? **I mean all on all the pages of forum except the first main page. Very Thanks.**

# Answer
> 1 votes
You need to display the exposed filters in a block, and then display that block on single forum node pages.

Here's how to do that:

1. Edit the Forum Search view: `/admin/structure/views/view/advanced_forum_search/edit`.
2. Under "Exposed form" -\> "Exposed form in block" choose "Yes".
3. Save the view.
4. Navigate to `/admin/structure/block`.
5. Enable the "Exposed form: advanced\_forum\_search-page" block, and show it for example in the "Content" area and only for "Forum topic" nodes. You can change this to your liking of course.

Users now can use this form from single forum nodes, and submitting it will take them to the search page.

### Update

If you want to make this available in your templates and position it within other elements, you'll have to edit the `template.php` of your theme add a `hook_preprocess_X()` implementation.

Choice depends on the template you want to add the form to. For example:

* `hook_preprocess_node()` \- to make the form available in `node.tpl.php`
* `hook_preprocess_page()` \- to make the form available in `page.tpl.php`
* `hook_preprocess_html()` \- to make the form available in `html.tpl.php`

Here's the code:

```
function YOUR_THEME_preprocess_REPLACE_THIS(&$variables) {
  // Load the view and generate the search form.
  //
  // You can have any dynamic conditions here (e.g. limit to some content types
  // and so on).
  $view = views_get_view('advanced_forum_search');
  $view->set_display('page');
  $view->init_handlers();
  $form_state = array(
    'view' => $view,
    'display' => $view->display_handler->display,
    'exposed_form_plugin' => $view->display_handler->get_plugin('exposed_form'),
    'method' => 'get',
    'rerender' => TRUE,
    'no_redirect' => TRUE,
  );
  $variables['search_form'] = drupal_build_form('views_exposed_form', $form_state);
}

```

Then in your `.tpl.php` file you would use this code to display the form:

```
<?php print render($search_form); ?>

```

Note that this way the visibility settings in admin won't be applied.

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


title: Display plugin block markup raw

text:
# Question
Title: Display plugin block markup raw
I have built a custom block plugin in Drupal 8. However, I needed to insert some svg elements in the markup, which get all filtered out. Is there a way for me to specify to display the raw output, so that the svg does not get filtered out?

```
  public function build() {

    return array(
      '#type' => 'markup',
      '#markup' => '<div><svg>.....</svg></div>',
    );
 }
?>

```

I have tried adding `'#template' => '{{ value|raw }}'` and played some with it - but could not get it to work. There must be some way to allow me to insert svg in there...

# Answer
> 3 votes
You can use an inline template:

```
  public function build() {

  return array(
    '#type' => 'inline_template',
    '#template' => '<div><svg>{{ var }}</svg></div>',
    '#context' => array(
      'var' => $svg,
    ),
  );

```

You can use the inline template with an empty context, if you have no vars that need to be escaped:

```
  return array(
        '#type' => 'inline_template',
        '#template' => '<div><svg>...</svg></div>',
        '#context' => array(),
      );

```

---
Tags: 8, blocks
---


title: Full access to admin panel

text:
# Question
Title: Full access to admin panel
So I have an access to the site as 'content' manager (at least it says content in the username field when im into dupal panel). And they asked me to change the menu a bit. But all I can do is making a limited amount of actions by default (like adding a page or a product info, etc.). There's no link to edit block or menu. As I consumed there're different types of access cos as I've seen in documentation the real administrative panel is quite functional. Am I right? So I asked for the FTP access and I got it but all I can do is changing some style rules in css and injector-css. So as I understand I can change html only in the real admin panel, right? Can I do something without that panel just having an access to FTP? And if yes, where I can find it in root folder? Thanks in advance!

# Answer
If they ask you to update menus then they should give your user role the permissions to make menu changes, whether you have access to FTP doesn't really matter in this case.
> 0 votes

---
Tags: users
---


title: Print array in field value

text:
# Question
Title: Print array in field value
I have created a custom form in form field following code is there.

```
 $form['display_result'] = array(
   '#title' => 'Result' ,
   '#type' => 'textarea',
   '#value' => !empty($dval) ? $dval : null,
   '#default values' => '',
 )

```

Problem is $dval is array which includes following code:

```
    stdClass Object
(
    [to] => Tove
    [from] => Jani
    [heading] => Reminder
    [body] => Don't forget me this weekend!
)

```

I am getting following warning:

> Warning: htmlspecialchars() expects parameter 1 to be string, object given in check\_plain() (line 1571 of /var/www/html/D7/includes/bootstrap.inc)

# Answer
> 2 votes
It's recommended to use `#default_value` instead of `#value`.

You have to use property of object instead of whole object. For example `$dval->body`.

```
$form['display_result'] = array(
    '#title' => t('Result'),
    '#type' => 'textarea',
    '#default_value' => !empty($dval->body) ? $dval->body : '',
  );

```

---
Tags: entities
---


title: Drupal 6 end of life

text:
# Question
Title: Drupal 6 end of life
Is there a documented date, or a believed date for the end of life of Drupal 6? In other words, when will official development stop on Drupal 6?

# Answer
> 28 votes
I think the advice from Choosing a Drupal version is probably the best to follow:

> At any given time, there are two major release series of Drupal which are supported. Currently, these are Drupal 6 and Drupal 7.

Essentially, official support for Drupal 6 will stop when Drupal 8 is officially released.

You can find further discussion on the So long, Drupal 5.x (End of Life Announcement)

# Answer
> 15 votes
While the official answers above are correct you need to look at the big picture. There is extremely little core work going on with Drupal 6 as it is tough to fix bugs without the extensive testing framework in place (and even with that, D7 bugfixes occassionally go haywire). Views is essentially on life support too. Obviously, quite a few contrib followed. There are only so many hours in the day and for a lot of people it's better spent on Drupal 7 (in the case of Views, Drupal 8 even).

So while it would not be impossible perhaps to gather a few large Drupal 6 sites and extend the support of D6 perhaps as a commercial venture (we considered this even for Drupal 5), but the problem for such a thing would be that you need to maintain *everything*: core and contributed modules, including the modules that were crappy four years ago and are without a maintainer. You get the picture.

The former security team lead (one of the very few who could actually pull this off) hints at such a commercial venture being planned at http://groups.drupal.org/node/291243#comment-907858. Edit: this one won't happen. Other, unknown entities of course might still pull it off but I have serious doubts.

# Answer
> 14 votes
It stops to be supported when Drupal 8 will have its first official release that is not an alpha release, a beta release, or a candidate release. The exact date of when that will happen is not known, but in the moment it happens, Drupal 6 will not be anymore supported.

This is exactly what happened with Drupal 5: When the first official release of Drupal 7 (excluding alpha, beta, and release candidates) was released, Drupal 5 stopped to be supported. So, in general, you can say Drupal X stops to be supported when Drupal X+2 is officially released.

# Answer
> 1 votes
Drupal 6 reached its end of life (EOL) on **24th February 2016** which is 3 months after Drupal 8 came out. See: Drupal 6 end-of-life announcement

The usual policy of the community is that it support only the current and previous stable versions (mainly to prevent maintainers to support more than 2 active major versions), so when Drupal 6 was out, Drupal 4.7.x was marked as unsupported, the same happened when Drupal 7 came out, Drupal 5.x become unsupported. However this policy has been questioned and the decision was made to end its life 3 months after Drupal 8 is released (See: Drupal 6 extended support announcement). This is to give extra time for the migration and provide support for upgrade processes and patches, so users could upgrade either to Drupal 7 or Drupal 8 anytime between Drupal 8 release date and 3 months after. Alternatively find some organization which will provide extended support for Drupal 6. See: Drupal 6 Long Term Support

---
Tags: 6
---


title: Created variations for products (error)

text:
# Question
Title: Created variations for products (error)
Good evening, I created variations for products and when I add references to the display product, I get the following error "error message The Data 1 uses tokens (tokens) following invalid: \[node : field-product: commerce\_price\] ". Look at the setting in the screenshot below

# Answer
> 0 votes
Since you're using a field with multiple options, you need to use a delta. So if your token looks like this:

`node:field_product:commerce_price`

It should include a delta after the field name:

`node:field_product:0:commerce_price`

---
Tags: commerce
---


# Question
Title: Why is "/es" showing up twice in my URLs?
I have a bilingual website using locale.

I have a content type that has the "link" field.

I have an Image Slider created with Views with the link as one of the fields.

The url in the link field is "services". In English, this works fine and goes to

```
www.domain.com/services

```

While viewing the view in Spanish, it adds "/es" to the URL twice

```
www.domain.com/es/es/services

```

Instead of:

```
www.domain.com/es/services

```

Is this an issue with pathauto? Views? Link?

# Answer
In case anyone is having a similar issue, this is how I fixed it.

*There may be a better way to do this but I can at least say that this worked for me.*

**Situation:**

So let's say that there is a view that contains two fields. "Path" (for the path to the node being listed) and the "Name" (Arbitrary text field).

The value of the "Path" field contains something along the lines of "/services" (English) or "/es/services" (Spanish). I exclude it so I can link the outputted title as a link to that path.

**My Initial Situation:**

I INITIALLY did what seemed logically correct (and what usually works). I chose to "Output this field as a link" and chose the "Path" token (under "Re-write results").

For some reason, using this was outputting the path incorrectly,

**Solution:**

Interestingly, doing the following fixed it:

Rather than selecting "Output this field as a link" and specifying the value of the "Path" field as the "Link path", I re-wrote the results entirely by coding it by hand.

It baffles me since to me, it appears that doing both of these methods should produce the same results.

Regardless, if you have the same issue I had, this will definitely work.

PS: Modules I have enabled that may have contributed to this:

* Views
* Pathauto
* Locale (for multiple languages)
* Links
> 2 votes

# Answer
Your link URL has to be "/services" or "services" depending on what you are trying to do, test both. URL path must NOT be "site.com/services."
> 1 votes

---
Tags: 7, views, i18n-l10n, path-aliases, navigation
---


title: Varnish + Adaptive Theme

text:
# Question
Title: Varnish + Adaptive Theme
Using the Adaptive theme on Acquia platform and seeing an issue with mobile rendered views being cached and served to desktop browsers with block regions hidden for mobile display. The issue seems sporadic for certain pages.

Clearing Varnish and/or Drupal caches fixes the issue. I think I know what's happening but not sure why. I'm considering disabling Drupal's cache.

I'm working in a sys admin / back end capacity so am limited, experience wise, as to where to look for the source of the problem.

# Answer
> 1 votes
Do you perhaps use Context Breakpoint? I had a similar experience using that module. The module states the following on its project page:

> # Caching implications
>
> This module has implications for using the Drupal page cache. Check the README.txt under CACHING for a detailed explanation and possible solutions.
>
> A more detailed explanation is in the README.

I ran into the same situation and it is caused by the way Drupal 7 caches content. It only checks the URL. So if you were to open a page on a mobile phone, which already existed in cache, you will receive the desktop version.

The inverse is also true. If cache is emptied or outdated and the next user to request the page is using a mobile phone, that user will make sure the mobile version is stored in the cache and served to desktop users.

This is certainly true for Drupal's internal caching system, and disabling the `Cache pages for anonymous users` option solves the problem. An alternative could be to use Context Mobile Detect. Which does seem to play nice with Drupal's page cache.

---
Tags: caching, proxies, theming
---


# Question
Title: How can I show list of users that bookmarked article?
How can I do it? I using flag module and I want to have the list of users that bookmarked article. Can I do it only with views?

# Answer
> 4 votes
If you really want to do this with Views you will need the following:

1. A Content View for articles
2. with a Nid as a Contextual Filter, in order to limits the results to the article node you are interested in
3. one relationship that will restrict your results to content that has been flagged with the bookmark flag (by any user)
4. one relationship that will return all users that flagged content using the flag from the relationship in (3).

Here is a Screenshot of the View:

and one of the end-result, in a sample node:

Hope this helps!

---
Tags: flags
---


# Question
Title: Rules: Copying field from user's account to field in content type
D7. Using the File Field Rules module, I am trying to copy the content of the image field of the user's account ("picture") to another image field ("field\_node\_image") in the same user's image gallery (each user has his own photo gallery.)

The purpose of this is for when a user uploads a picture to his account profile, a copy of it is also posted in his image gallery along with all the other pictures he may post there (displayed via Views.)

The module requires the selection of a source entity and a destination entity. Then a field is chosen from each entity.

I am making the event react upon updating the user's account, so that gives me access to the "account" selector for the source entity where the module finds the "picture" field.

But I need help in finding the destination selector. This, evidently, should be a node since the gallery is a content type. It also has to be a node that belongs to the user. But all base selectors I have begin by "site" or "account."

Can anyone help me find this second selector?

Thanks. :)

# Answer
I think you need to add some more stuff in that Rule; namely, following from your explanation, you need to:

1. "Create a new entity": Create a new node in an action, before the image-copying action. This new entity is a Gallery-type node.
2. Use the "entity\_created" variable as the destination entity.

That should be enough to accomplish your goal, hope this helped some!

**Appendix A**: An export of such a Rule that worked.

```
{ "rules_196457" : {
    "LABEL" : "196457",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "file_rules" ],
    "ON" : { "user_update" : [] },
    "IF" : [
      { "NOT data_is_empty" : { "data" : [ "account:field-user-image:file" ] } },
      { "NOT data_is" : {
          "data" : [ "account:field-user-image:file" ],
          "value" : [ "account-unchanged:field-user-image:file" ]
        }
      }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "node",
            "param_type" : "article",
            "param_title" : "New pic for [account:name] | [site:current-date]",
            "param_author" : [ "account" ]
          },
          "PROVIDE" : { "entity_created" : { "new_article" : "Created entity" } }
        }
      },
      { "file_rules_copy_file" : {
          "source_entity" : [ "account" ],
          "source_field" : "field_user_image",
          "destination_entity" : [ "new-article" ],
          "destination_field" : "field_image",
          "remove_source" : "0"
        }
      },
      { "drupal_message" : { "message" : "A new Article has been created with the new user\u0027s image" } }
    ]
  }
}

```

**Appendix B**: An screenshot of the Rules UI
> 2 votes

---
Tags: 7, rules
---


# Question
Title: Datatables Module not Sorting all Columns
I am using the DataTables module (https://www.drupal.org/project/datatables). The sorting option does not work for all columns, and I am not sure why. I'd like the ability to have all columns sortable as this is just in the DOM, shouldn't that be a possibility?

For example:

* Columns that do sort: Content Text, Terms, Dates...
* Columns that do not sort: View Conditional (if this then that results)

Here is 2 of the table columns html output:

```
<th class="views-field views-field-title sorting_asc" tabindex="0" aria-controls="datatable-1" rowspan="1" colspan="1" aria-sort="ascending" aria-label="Title        : activate to sort column ascending">Title</th>

```

There is a checkbox in the views datatable settings next the "TITLE" column above...

There is not checkbox enabling sorting on the column below (views conditional):

```
<th class="views-field views-field-views-conditional sorting_disabled" rowspan="1" colspan="1" aria-label="BLM">BLM</th>

```

EDIT: This might be due to the sType (https://datatables.net/development/sorting)

In the DataTables module, changing line 298 from FALSE to TRUE allows all sorting... I am sure there is a reason not to allow this, but not sure why. Investigating sType more to apply another elseif on string or whatever type is being produced by the views conditional...

Line 298:

```
if (empty($options['info'][$field]['sortable']) || !$fields[$field]->click_sortable()) {
        $column_options['bSortable'] = TRUE; //changed from FALSE
      }

```

Line 301: //checks what sType the data is:

```
else {
        // Attempt to autodetect the type of field in order to handle sorting
        // correctly.
        if (drupal_strlen($fields[$field]->last_render) != drupal_strlen(strip_tags($fields[$field]->last_render))) {
          $column_options['sType'] = 'html';
        }
        elseif (is_numeric($fields[$field]->last_render)) {
          $column_options['sType'] = 'numeric';
        }
        elseif ($fields[$field] instanceof views_handler_field_date) {
          $column_options['sType'] = 'date';
        }
        $column_options['bSortable'] = TRUE;

```

**STRING** is not one of the options in here. Though the documentation says it could be: http://legacy.datatables.net/usage/columns#sType

I attempted to add it like so real quick with no results:

```
elseif (drupal_strlen($fields[$field]->last_render) != drupal_strlen(strip_tags($fields[$field]->last_render))) {
      $column_options['sType'] = 'string';
    }

```

# Answer
> 1 votes
I used a `hook_views_data_alter()` to add 'click sortable' to the field that didn't have that option.

```
/**
 * Implements hook_views_data_alter().
 */
function utagta_helper_views_data_alter(&$data) {
  // Allow the views fields to be sortable.
  $data['views']['view']['field']['click sortable'] = TRUE;
}

```

# Answer
> 0 votes
If I am reading your question right, you are wanting to sort a Views Conditional field on the database level. The issue is, the value that would be sorted by is only available after the database work is done and the view starts processing the conditions. Therefore, the database sorting does not work even if you force the ui to allow it.

What you can do is use a hook\_views\_pre\_render to alter the ordering of the results, effectively sorting it yourself. I have done this when I was making a site usage report and the client wanted multiple layers of aggregation with filters. If you have the ajax setting on No, and force the ui to permit sorting on the fields, then you can listen for the sort in the url and use the pre\_render to perform it.

Other options are treat this like a rewritten field, and do one of these: sort-view-on-a-rewritten

---
Tags: 7, entities
---


# Question
Title: Advaced forum area going off-page in firefox browser?
I have installed advanced forum and facing the weird issue. When I hover on the configuration button gear the area covered by it shows off-page as in the image(dotted line which automatically shows in drupal modules). I did check on two sites, in case my one site has the css issue. And due to this in my one site the page border of the main-content page sifting all the way to left. You can see the dotted line in the image. For the complete views I have zoom out the browser and you can see the how entire layout gets sifted in the second image.

**Edit-2:**

I have created the sandbox link with a Username: admin and password: admin. If you hover on the configuration gear of the views forum tab, it shows dotted line, but the left side dotted line has no end (off the page). Why this issue matters because when I create the page-border, page border also gets off-page along with that. **This happens with Firefox browser only as described in the Edit-1.**

**Edit-1:**

**I did check in all browsers, and this is happening in Firefox browser only. My current browser is 45.0.1 which is the latest one. I did check in chrome and safari also, but there is no issue.**

# Answer
> 3 votes
The issue that a contextual link is causing your page to break. **Please note that this issue only occurs for users that have permissions to modify panels, so your end users (visitors) should not see this.**

The solution could be to disable the contextual link on the panel. Or disable the contextual links module entirely (what would remove the gear icon everywhere).

To disable contextual links only on some pages you might want to look at this question for how to disable a specific link: Is it possible to remove the contextual link for deleting a node?

Or you could try the Hide Contextual Links module.

**UPDATE:**

The main cause of this issue is a firefox bug, where outlines are drawn around descendant elements: https://bugzilla.mozilla.org/show\_bug.cgi?id=687311

You can see it asked here on stackoverflow: https://stackoverflow.com/questions/10662902/css-outline-different-behavior-behavior-on-webkit-gecko, where the recommended action is to replace the outline with a box-shadow (no dashes), or the alternative to append `overflow: hidden` to the element. I tried with `overflow: hidden` and that worked so I'd try that first to keep the dashed line.

In Drupal, in you theme's css add:

```
.contextual-links-region-active {
  /* Override the old outline */
  outline: none !important;

  box-shadow: 0px 0px 0px 1px #FFF;
  /* OR */
  overflow: hidden;
}

```

But once again, this is a firefox bug that is likely to influence only administrators who have permissions to modify panels (I have no idea about the company you are building this for, but that cannot be many users). So ask yourself if it is worth putting effort into this.

**UPDATE-2:** by@codenext,

As @Neograph734 has provided the very nice research on this issue in above UPDATE(basically it is FIREFOX BUG). Please follow the following comments and question details to understand the issue. I am just providing the final solution as final solution is just the extension of this answer.

**SOLUTION:** The main issue is, the outline(left part) of the contextual-link-region goes off the page as shown in the second image above(a dashed line area), and along with that it takes the page-border/outline css off the page too. Hence we can put the `overflow:hidden;` in the #page/#content-column selector(as in my case, I have put border: and outline: css in these selectors) instead of putting it in `.contextual-links-region`. Hence, this way you can prevent the displacement of page-border and outline which caused the `.contextua-links-region`(originally the firefox bug).

---
Tags: theming, nodes
---


# Question
Title: X-Frame-Options and Strict-Transport-Security are prohbiting me from uploading any images via ajax error due to self signed cert (on a dev box)
When trying to upload an image in a Node Edit form, I'm getting an Ajax error in the main browser window. The browser console is displaying complaints surrounding Strict Transport and X-Frame options.

> Strict-Transport-Security: The connection to the site is untrustworthy, so the specified header was ignored.\[Learn More\] form-VHZcgnXwba2plRQ9nE0JQPqgblsvmrgYHtOtCywfYmo

And

> Load denied by X-Frame-Options: https://server.ext/file/ajax/field\_module\_images/und/0/form-VHZcgnXwba2plRQ9nE0JQPqgblsvmrgYHtOtCywfYmo does not permit framing

**We're I'm at now:** I've followed guildlines in Securing file permissions and ownership. I've not run into this issue with other sites. The only difference in this site and others we run is that this is our first on RHEL 7. I've read other reports about playing with jQuery Update with little luck.

**Potential issue:** Could this be because I'm on a dev server with a self signed certificate?

What I've tried:

I've tried adding the follwing inside /etc/httpd/conf.d/Xframe.conf

```
<Location /var/www/html>
        Header always append X-Frame-Options SAMEORIGIN
</Location>

```

This seems to have had to impact after a service restart.

# Answer
> 0 votes
File under just being a bad morning.

It turned out to be the ADMIN THEME was using jQuery 1.4 instead of an updated version. Using jQuery Update, the admin theme now has a 1.8 and content creators are happy.

# Answer
> 0 votes
Make sure you are not using a module called "Security Kit". If you are, check the admin settings. There is a manual setting for the X-Frame-Options header: /admin/config/system/seckit

---
Tags: ajax, files
---


# Question
Title: How can I remove the default generated <div> tags in view's result?
I am using a views in my drupal web site. I have set 'style' to **'Unformatted'** and 'Row style' to **'Fields'**

Also I have Rewrote the output of the field with my HTML tags.

But I have a problem in the result. Every row is located inside a \[div\] tag for example the first row is located in

```
<div class="views-row views-row-1 views-row-odd views-row-first"></div>

```

How can I setup the view in order to remove this extra \[div\] tag ?!?!?

I don't need this wrapper.

# Answer
> 7 votes
If you don't want to touch the theme you could use Semantic Views module to strip all the extra div's.

# Answer
> 9 votes
The easiest thing to do is copy the template files from "sites/all/modules/views/theme/" into you theme (I normally make a "views/" subdirectory).

If you want to make this change for all themes, edit "views-view-unformatted.tpl.php".

If you want to just change that view, edit the view then click on the **Theme: Information** link. It will show the template suggestions for the view. Copy If you want to make this change for all themes, copy "views-view-unformatted.tpl.php" to the proper name, and edit that file.

In both cases, make sure you clear the Drupal caches to make sure the system finds the new files.

# Answer
> 7 votes
This solution combines and builds on David Paul's and MDP's solutions and removes the `<div class="views-row ...">` in a consistent way for all views that are properly configured without additional modules.

## Drupal 7 & 8+

**Step 1: Disable all class configurations in the *Style options* of the view's *Format* section.**

You must do this for any and all views that you want to remove the wrapper from:

## Drupal 7

**Step 2: Copy `views-view-unformatted.tpl.php` from the Views module into your theme's `templates` folder** and modify the logic to ignore the div when classes are empty.

Change the following lines from:

```
<div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
  <?php print $row; ?>
</div>

```

to:

```
<?php if ($classes_array[$id]) : ?><div class="<?php print $classes_array[$id]; ?>"><?php endif; ?>
  <?php print $row; ?>
<?php if ($classes_array[$id]) : ?></div><?php endif; ?>

```

## Drupal 8+

**Step 2: Copy `views-view-unformatted.html.twig` from the Views module into your theme's `templates/views/` folder** and modify the logic to ignore the div when {{row.attributes}} are empty.

Change the following lines from:

```
<div{{ row.attributes.addClass(row_classes) }}>
  {{ row.content }}
</div>

```

to:

```
{% if default_row_class or row.attributes is not empty %}
<div{{ row.attributes.addClass(row_classes) }}>
  {{ row.content }}
</div>
{% else %}
  {{ row.content }}
{% endif %}

```

Honestly, I'm not sure why the Views module doesn't do this itself... its a total WTF and could be a nice improvement for Themer's eXperience.

# Answer
> 1 votes
You want to look into the `Theming: Information` section and override one of the styled templates for your view. That's where the stuff happens. Be sure to use the Rescan button when you create an appropriately named tpl file, so that Drupal picks it up.

# Answer
> 1 votes
To remove this in Drupal 7 you can click on the Fields settings and turn off "Provide default wrapper elements"

# Answer
> 0 votes
If you're on Drupal 7 then you don't need to play with template files to remove the wrapper divs. Those wrappers come as part of the output, which suggests they can be controlled in the view, which they can.

Under FORMAT \> Show: fields | settings - click settings, then uncheck the wrapper option. That's it.

# Answer
> 0 votes
I have achieved this by overriding views-view.tpl.php file. Copy this file from views module into your theme directory and remove the beginning wrapper.

Also remove the div wrapping the $rows.

---
Tags: views
---


title: Views slideshow + ajax content

text:
# Question
Title: Views slideshow + ajax content
if there any solution for this? I need to do views slideshow with content loading (with ajax).

# Answer
> 1 votes
Have a look at the Flex Slider module. It provides this functionality, but you might need to theme it a little bit. A screenshot similar to what you want is below. Note that you are not limited to pictures, but you can use any type of content in the display.

It is quite a hassle to start with at first, but I found these youtube videos very valuable:

Basic set-up instructions: https://www.youtube.com/watch?v=MboDby9-PCE

Theming guide: https://www.youtube.com/watch?v=-Jukg7UlSZA

# Answer
> 0 votes
You can use Jcarousel module. You can use it for views and you will get required output. Have a look at examples of jcarouscel slider.

---
Tags: ajax, views
---


title: Custom form, webform, or entityform

text:
# Question
Title: Custom form, webform, or entityform
Would it be best to create my own form or use contrib. drupal7 modules to complete my following need. If i use contrib. modules, which ones should i use.

I want to make a form that has 3 fields. 2 autofill and 1 auto complete. One of the autofill fields would just autofill the current users 'first and last name.' The auto complete field will auto complete existing users in the site - so if you begin to type in a users name it will auto complete for you. The other autofill field will autofill the autocompleted user's supervisor.

Spent a bunch of time trying to configure webforms or entityforms, then kinda wondered if this should just be done with an in house custom form. Whats the best Drupal7 practice for this?

At the end it will email 3 people and then be put into some review process. The 3 people will be the autocompleted user, the autofilled supervisor and a static HR email address. I suppose i would bake that all in a submit handler, if i did my own custom form.

# Answer
The best and quick way to go with is using EntityForm. The module provides advantage of using field using which you can have Entity/User Reference fields with auto-complete, without writing a single line of code. To notify 3 users on Email, you can use Rules Module. And the other advantage is, it is maintained by Community so all security issues are tracked and fixed before the site can get affected.

Webform module doesn't support auto-complete by default you'll need to use Webform Autocomplete module for that. I've not used this module, so not sure if this provides the option for referencing existing entity.

If you're building it custom, you'll need to build everything by your own using Form API and Mail System. Which will be time consuming as compared to using EntityForm.
> 1 votes

---
Tags: forms, webforms, entities
---


# Question
Title: How to translate Select List options used in exposed filters of a view?
I'm having an issue with translation of exposed filters in Views.

I'm using a text list field as an exposed filter in my view. The problem is that even though I translated the list terms via strings (Regional and Language \>\> translate interface \>\> translate) the terms always appear in the original language.

I checked but there is not an option in the view to show the translated terms in the filter. There are other exposed filters translated the same way that appear in the correct language, but they're not select lists but taxonomy terms.

I also checked the advanced views settings and the Localization translation method is already on "core". I don't know what else to check.

I'm using Better Exposed Filters and MEFIBS - More exposed forms in blocks for the exposed filters (I'm not sure if this may be related).

# Answer
> 2 votes
# Option 1

Try something similar to what is mentioned in Comment #1 of issue # 1762488, i.e:

> ... visit 'Manage Display' and switch from "Default" to "Default translated".

# Option 2

Try using the Internationalizations Views module, which extends the i18n module with multilingual support for Views.

True, the Internationalizations Views module only has an **alfa1** version for D7, but right now there are over 41K users using this version. Therefor I think "DEV" is not a valid release qualifier for that version anymore, because *+41K users can't be wrong*, right?

**Note**: Filtering Views results in a multi language site can sometimes be challenging, as illustrated also in discussions such as in How to filter views results to the current language nodes.

# Answer
> 3 votes
I can confirm this issue. While working with BEF, me too faced the same translation problem. Probably this is a bug in BEF module which do not handle translations properly. Meanwhile, to solve this issue I explicitly used a **hook\_form\_views\_exposed\_form\_alter()** to wrap the non-translatable string in **t()**.

May this helps you.

# Answer
> 1 votes
You can Rewrite filter options:
\__
\__
\__

---
Tags: 7, i18n-l10n, views
---


# Question
Title: Custom Views Sort Order Using Filter Value
I have a View containing a list of events. There is a date field on the event content type which contains start and end time:

There is a filter for start time, which is setup using the Views Between Dates Filter:

This means that entering `11:00am` in the filter will ensure that the event with time `10:00 AM to 3:00PM` exists in the results since 11 falls between 10 and 3.

The full result set might look like the following when using `11am` for the filter:

```
7am to 3pm
8am to 12pm
9am to 11:30pm
11am to 12:00pm
11am to 1pm

```

How can I create a custom sort, such that the exact matches for start time are ordered first? These are the results I need:

```
11am to 12:00pm
11am to 1pm
7am to 3pm
8am to 12pm
9am to 11:30pm

```

Is there a way to create a custom sort handler for views using filter values?

EDIT: I'd hoped I could use `hook_views_post_execute` to re-order the data but I'm using a pager, so only the first 10 results exist in `$view->result`

# Answer
> 0 votes
In the end, my client agreed this feature was overkill and it was ommitted but I thought of a way it could be achieved.

**Potential Solution**

The following is only feasible if you have a finite and relatively low number of filter values because you need to create a field for every filter value.

* Create a field of type boolean for every filter value. In our case we had `10, 11, 12, 1, 2, 3` as potential values for hour and `00, 15, 30, 45` for minute. 24 possible combinations, so 24 fields need added to the event type.
* The field should be named according to the filter combination, e.g. `Sort: 10:00`, `Sort: 10:15` etc.
* The field value should be set as either `1` or `0`. If the event start time matches the time in the name of sort field then this should be set to `1` otherwise it should be set to `0`. `hook_node_insert` and `hook_node_update` could be used to set the values.

E.g on each event you would have:

```
Start Time - 11:00

Sort 10:00 - 0
Sort 10:15 - 0
Sort 10:30 - 0
Sort 10:45 - 0
Sort 11:00 - 1
etc (the rest would be set to 0).

```
* When the filter is applied, use `hook_views_query_alter` to grab the filter value. Then set the sort based on that field.

E.g if the user entered `11:00` as the filter value, we could force the sort to use the `Sort: 11:00` field. The following is written off the top of my head, so would need some tweaks:

```
function my_module_views_query_alter(&$view, &$query) {
  if($view->exposed_input['field_start_time'][0]['value'] == "11:00am") {
    $view->query->orderby[0]['field'] = "field_data_field_sort_11_00_value";
    $view->query->orderby[0]['direction'] = "DESC";
    // Add any secondary sorts.
  }
  else if($view->exposed_input['field_start_time'][0]['value'] == "11:15am") {
    $view->query->orderby[0]['field'] = "field_data_field_sort_11_15_value";
    $view->query->orderby[0]['direction'] = "DESC";
    // Add any secondary sorts.
  }
}

```

---
Tags: 7, views
---


# Question
Title: Jquery Validation & number field with comma
In my form i have this element :

```
   $form['poidsMin'] = array(
        '#type' => 'number',
        '#title' => $this->t('Poids minimum en gramme'),
        '#default_value' => $frais_port_entity->get('poidsMin'),
        '#description' => $this->t("Poids minimum du produit"),
        '#required' => TRUE,
    );

```

When i put 10 or 20, all is good but if i put 10.3 or 10,3 drupal 8 jquery validate tell me to insert a value like 10 or 11 with no comma.

My field in mysql is a float, how can i disable this validation for number type field ?

# Answer
Browser support may vary, but essentially you want to add an attribute of `step="any"`:

```
$form['poidsMin'] = array(
    '#type' => 'number',
    '#title' => $this->t('Poids minimum en gramme'),
    '#default_value' => $frais_port_entity->get('poidsMin'),
    '#description' => $this->t("Poids minimum du produit"),
    '#required' => TRUE,
    '#attributes' => ['step' => 'any'],
);

```
> 3 votes

---
Tags: entities, 8
---


# Question
Title: Is there a bulk method of doing 301 redirects from old nodes to new node pages?
I am updating an old drupal 7 site and many of the old nodes now have newer counter parts with new nodes. Since alot of my old nodes have already been spider-ed, I want to do a 301 redirect to the new nodes. I'm currently doing it manually by deleting the old node and then copying the URL alias into the redirect module and redirect it to the new node path. Is there a easier way to do this if I have 1000 nodes that need redirection?

# Answer
> 0 votes
Have you tried the Global Redirect module, I think it will do what you are looking for.

http://drupal.org/project/globalredirect

Also have a look at this module it is rely handy it searches Google for inbound links to the site. https://drupal.org/project/google301

# Answer
> 1 votes
**Redirect Module + Path redirect import Module**

The module Redirect has great options, one of which creates redirects when you rename a page and hence change an alias.

The module Path redirect import works with Redirect and allows you to upload a CSV of redirects (or use Drush), it even checks if a page you are redirecting to exists.

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


title: set up triggers for items

text:
# Question
Title: set up triggers for items
Any way to set up triggers for items in their cart to remind buyer to check them out after 30 days?

# Answer
> 0 votes
Yep:

Commerce Abandoned Cart Notification

> This module allows you to notify your customers by email about their abandoned their cart.

It's in dev so be warned; I'm not aware of any other pre-existing solutions, but writing your own module for this would also be a pretty straightforward option if that module doesn't work for your needs.

---
Tags: commerce
---


# Question
Title: How can I disable a user that should still be visible on the site?
It seems that User name on blocked user account not visible in view for anonymous users is basically the same question I'm asking, but it doesn't have an accepted answer or one that works for me. This is a different take on the question than the one I'm making.

I am migrating a site from another CMS. I am bringing over staff members, both past and current as users of the site. As part of the migration, users who are no longer with the organization are being marked as blocked to prevent them from logging into the site.

These users are then associated with nodes on the site via various entity reference fields. The problem I run into is that for anonymous users, indeed for anyone that doesn't have bypass access controls on their account, these user accounts are not visible.

**What is the proper way to keep an account visible, while not allowing users to log-in to it?** For me, the answer will need to be something that will work with the Migrate Module.

Obviously blocking the user seemed like the obvious way to do it for me, but I can't find any permission that will allow access to blocked user info. Is there another way of doing this, or is there a way of making blocked account info visible?

## My Solution

Based on the accepted answer from @kiamlaluno, I created a solution that works for me:

I already have an end\_date field for each user (`field_user_end_date`), so most of the time, that would suffice as a limiting factor for the login, but based on discussions with the stakeholders, I added an additional admin only boolean field named `field_user_account_locked`.

I implement `hook_form_alter` to add my validation function to the form:

```
function mymodule_form_alter(&$form, &$form_state, $form_id)
{
    if ($form_id == 'user_login' || $form_id == 'user_login_block') {
        $form['#validate'][] = 'mymodule_user_login_validate';
    }
}

```

And here is my validation module:

```
function mymodule_user_login_validate($form, &$form_state)
{
    if (!empty($form_state['uid'])) {
        // The user trying to login is not limited by flood control;
        // user_login_authenticate_validate() found a user with the username and password entered in the login form.
        $user = user_load($form_state['uid']);
        $end_date = (isset($user->field_user_end_date[LANGUAGE_NONE][0]['value'])) ? strtotime($user->field_user_end_date[LANGUAGE_NONE][0]['value']) : time() + 300000;
        if ($end_date < time() || $user->field_user_account_locked[LANGUAGE_NONE][0]['value'] == 1) {
            form_set_error('name', t('The username %name cannot be used to login.', array('%name' => $form_state['values']['name'])));
        }
    }
}

```

I'd love some constructive criticism on it, if you have some.

# Answer
Using a custom module, you could change the permission to see user profiles. For example, the following code could be used for Drupal 7.

```
function mymodule_permission() {
  return array(
    'access blocked user profiles' => array(
      'title' => t('View user profiles of blocked users'),
    ),
  );
}

function mymodule_menu_alter(&$items) {
  if (isset($items['user/%user'])) {
    $items['user/%user']['access callback'] = 'mymodule_view_access';
  }
}

function mymodule_view_access($account) {
  $uid = is_object($account) ? $account->uid : (int) $account;

  // Never allow access to view the anonymous user account.
  if ($uid) {
    // Admins can view all, users can view own profiles at all times.
    if ($GLOBALS['user']->uid == $uid || user_access('administer users')) {
      return TRUE;
    }
    elseif (user_access('access user profiles')) {
      // At this point, load the complete account object.
      if (!is_object($account)) {
        $account = user_load($uid);
      }
      if (is_object($account)) {
        // If the account is blocked, show the profile to users with the right
        // permission.
        return ($account->status ? TRUE : user_access('access blocked user profiles'));
      }
    }
  }
  return FALSE;
}

```

Give the new permission to anonymous users, and they will be able to see the user profile of blocked users.

This is probably easier than changing password and email, and it's easier to revert if you block by mistake a current employee: Just unblock the account.

The code I shown works for a direct access to the user profile, and for modules that only verify the user has the *access user profile* permission to show the link to a user profile. This is what Drupal does, for example in `template_preprocess_username()`.

```
  $variables['profile_access'] = user_access('access user profiles');
  $variables['link_attributes'] = array();
  // Populate link path and attributes if appropriate.
  if ($variables['uid'] && $variables['profile_access']) {
    // We are linking to a local user.
    $variables['link_attributes'] = array('title' => t('View user profile.'));
    $variables['link_path'] = 'user/' . $variables['uid'];
  }
  elseif (!empty($account->homepage)) {
    // Like the 'class' attribute, the 'rel' attribute can hold a
    // space-separated set of values, so initialize it as an array to make it
    // easier for other preprocess functions to append to it.
    $variables['link_attributes'] = array('rel' => array('nofollow'));
    $variables['link_path'] = $account->homepage;
    $variables['homepage'] = $account->homepage;
  }

```

Any module using `theme('username')` (for which `template_preprocess_username` is a preprocess function) to show the user name will print the link to the user profile, even if the shown user account is blocked, if the currently logged-in user has the *access user profile* permission.

If there are modules that check the user account is blocked before showing a link to the user profile, then this method will not work.

In this case, the alternative I would adopt is the following:

* Don't block the user accounts for those ex employees
* Add a flag to the user accounts that says if an account can be used to log in
* Using an extra validation handler for the login form, return an error if one of those accounts is used to log in

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login' || $form_id == 'user_login_block') {
    $form['#validate'][] = 'mymodule_user_login_validate';
  }
  elseif ($form_id == 'user_register_form') {
    $form['account']['can_login'] = array(
      '#type' => 'checkbox',
      '#title' => t('The user account can be used to log in'),
      // The form is for registering a new user; there is nothing to load from the database.
      '#default_value' => TRUE,
      // See user_register_form() which set the following value to TRUE if
      // the currently logged-in user administer users.
      '#access' => $form['administer_users']['#value'],
    );
    $form['#submit'][] = 'mymodule_register_submit';
  }
  elseif ($form_id == 'user_profile_form') {
    if ($form['#user_category'] == 'account') {
      $form['account']['can_login'] = array(
        '#type' => 'checkbox',
        '#title' => t('The user account can be used to log in'),
        '#default_value' => mymodule_load_flag($form['#user']->uid),
        '#access' => user_access('administer users'),
      );
      $form['#submit'][] = 'mymodule_profile_submit';
    }
  }
}

function mymodule_user_login_validate($form, &$form_state) {
  if (!empty($form_state['uid'])) {
    // The user trying to login is not limited by flood control;
    // user_login_authenticate_validate() found a user with the username and password entered in the login form.
    if (!mymodule_load_flag($form_state['uid'])) {
      form_set_error('name', t('The username %name cannot be used to login.', array('%name' => $form_state['values']['name'])));
    }
  }
}

function mymodule_register_submit($form, &$form_state) {
  if ($form_state['values']['administer_users']) {
    // The user submitting the form can administer users.
    // user_register_submit() sets $form_state['values']['uid']; save it in
    // a database table the module creates when installed.
    mymodule_save_flag($form_state['values']['uid'], $form_state['values']['can_login']);
  }
}

function mymodule_profile_submit($form, &$form_state) {
  if (user_access('administer users') && $form['#user_category'] == 'account') {
    // user_profile_submit() sets $form_state['values']['uid']; save it in
    // a database table the module creates when installed.
    mymodule_save_flag($form_state['values']['uid'], $form_state['values']['can_login']);
  }
}

```
> 2 votes

# Answer
Show all the users in a View. Views is capable of showing all data to everybody (so you will have to be careful).

When you create a view that lists users, you have an option to filter by status. If you omit that filter, you will list every user in the system blocked and unblocked. If it is still not working, change the default 'View user profiles' permission into something else.

1. Install and enable the Views module.
2. Create a View that lists "Users".
3. Add additional filters.
4. Check permissions.
> 1 votes

---
Tags: 7, users, migrations
---


# Question
Title: How to download and enable module needing to subscribe to rss?
I want to download and install "Node Redirect" module for version 7 of Drupal but I can't find a way to subscribe to rss as needed. What are the steps to follow to download the module?

# Answer
> 0 votes
In the right side menu there will a link Browse code repository. There you can find git clone URL

```
git://git.drupal.org/project/node_redirect.git

```

So you can clone it.

---
Tags: 7, feeds, files
---


# Question
Title: Creating a custom login system by developing a new module
I've created 2 files:

* `login_process.info`
* `login_process.module`

I've created the table "user" in the database that Drupal is using. I want to display a custom login form with fields "Username" and "Password".

Assuming the data from Username and Password fields are in the correct format(proper validations), when the submit button is pressed, a query is done and data to check if the values matches that found in the table.

```
If no result is found, it displays an error message

else it redirects to to the welcome page.

```

Here are the codes:

`login_process.info`

```
name = "My login process module"
description = "Performs login process"
core = "7.x"
version ="7.x.1.0"
package = "Login/Register"`

```

`login_process.module`

```
<?php

/*
*Implements hook permission
*/

function login_process_hook_permission()
{
 return array(
    'submit login_process' => array(
      'title' => t('Submit login form'),
      'description' => t('Submit the login form')
    ),
  );
}

/*
* Implements hook menu
*/

function login_process_hook_menu() {
  $items = array();
    $items['login-process'] = array(
  'title' => 'login',
  'type' => 'MENU_NORMAL_ITEM',
  'access arguments' => array('submit login_process'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('login_process_form')
    );
    return $items;
}

/*
* The login form
*/

function login_process_form($form,&$form_state)
{
  $form['Username'] = array(
  '#type' => 'textfield',
  '#title' => t('Username'),
  '#size' => 20,
  '#maxlength' => 20,
  '#required' => TRUE,
  '#description' => t('Please enter a valid username'),
  );

  $form['Password'] = array(
  '#type' => 'textfield',
  '#title' => t('Password'),
  '#size' => 20,
  '#maxlength' => 20,
  '#required' => TRUE,
  '#description' => t('Please enter a valid password'),
  );
  $form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Add item')

  );
  return $form;
}
/*
* Validation handler for the login_process_form
*/

function login_process_form_validate($form,&$form_state)
{
  print('<pre>'.print_r($form_state['values'],1).'<pre>'); die();
  if (!preg_match("/[a-zA-Z]/",$form_state['values']['Username']))
  {
    form_set_error('Username', t('Username must contain only alphabets'));
    return FALSE;
  }
  return TRUE;
  //add more validations for Username and Password
}

/*
*Submit handler for the login form
*/

function login_process_form_submit($form,&$form_states)
{

  $username = $form_state['values']['Username'];
  $password =  $form_state['values']['Password'];
  $results = db_query("SELECT Username,Password FROM user WHERE Username='".$username."' AND Password='".$password."'"));
  if(is_null($results))
  {
    form_set_error('Username', t('Wrong username or password. Try again!!!!'));
    return FALSE;
  }
  else
  {
  echo "Welcome".$form_state['values']['Username']."<a href="logout.php">Logout</a>" // it will be better if it is displayed in a block
  }
}

```

It neither display errors nor the login form created from the module. Can anyone help me here? Do I have to install additional modules to make it work?

Most of the codes are based from Daily dose of Drupal episode 16 to 22.

# Answer
> 1 votes
You don't need any other modules, to just show a form. Your code is not correct in some points, though, and that needs to be corrected.

A form validation handler doesn't return `TRUE` nor `FALSE`; it just calls `form_set_error()` in case the submitted data doesn't pass the validation.

A form submission handler doesn't validate the submitted data; that is the task of the form validation handlers. The purpose of the form submission handlers is to take the necessary actions (e.g. loading data from the database, saving data to the database), but they don't return anything.

You don't inject values entered from user directly in the query, as you do with `db_query()`. That is the perfect way of given a malicious user access to the user #1 access, for example, and without the user knowing the user #1 account.
Always use placeholders for input obtained from users, when you are using it in a query. See what `user_login_authenticate_validate()` does.

```
$account = db_query("SELECT * FROM {users} WHERE name = :name AND status = 1", array(':name' => $form_state['values']['name']))->fetchObject();

```

The correct way to show a message to the user is using `drupal_set_message()`. In the specific case, showing a message with a logout link is not much helpful, since the users will not see it anymore after moving to a different page. In any case, you don't use `echo()` to print anything on a Drupal page from a form submission (or validation) handler.

# Answer
> 0 votes
To me it looks like you made a form which is not used.

How do you display this form ?? Are you using example.com/login-process ?

If you want to alter the default login form use:

```
function login_process_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_login_block' || $form_id == 'user_login') {
    $form['#validate'][] = '_login_process_form_validate';
    $form['#submit'][] = '_login_process_form_submit';
  }
}

```

So, there we added these custom validate and submit handlers:

```
function _login_process_form_validate($form, &$form_state) {

}

function _login_process_form_submit($form, &$form_state) {

}

```

---
Tags: 7, forms
---


# Question
Title: Restrict Drupal Search to few content types
I am having drupal 7 site with search enabled. I want to restrict the search to a particular content type/types, by excluding which types i dont want to appear in the result. How can i do this?

And can i also disable the advance search feature? Are there any module for this?

# Answer
> 15 votes
I guess that Custom Search module can help you: http://drupal.org/project/custom\_search. acording Custom Search module description:

> The module adds options to select:
>
> ```
> * which content type(s) to search
>
> ```

here a snapshot of **Custom Search** settings related with content type configuration:

Other alternative seems to be Search Configuration module http://drupal.org/project/search\_config that give to Search settings (in **Additional Node Search Configuration \> Only of the type(s) settings**) options to filter search by content type:

# Answer
> 5 votes
you could just add a view with the title as an "exposed filter". Then you can limit the search to certain nodes.

# Answer
> 5 votes
Drupal's contrib module Search Restrict is a lightweight module that just does the basics - it allows administrators to restrict by role who can search for each content type.

From the module's page:

> Approach of this module is to re-write the search query, so that content is indexed and available as search results to users in role(s) that have permissions to view it, but not displayed to other roles. Integrates with Apache Solr to exclude results based on the role of the person searching.

Simply download, install, and enable the module. Then to restrict (by role) which users can search which content types, edit each Content Type individually and there will now be a 'Search Restrict' section option (below the Display Settings). It allows you to specific, for each content type, which roles can search nodes of that content type.

# Answer
> 1 votes
My evaluated best solution uses all content types in search config and lets you exclude the unwanted types: https://www.lullabot.com/articles/hiding-content-from-drupals-search-system

---
Tags: 7, search
---


# Question
Title: Error when using LDAP Views within Rules
My objective is to pick a user from an ldap and then create his drupal account.

In order to do this,

1) a user picks a name (dn) from an LDAP server using the LDAP Entry Reference module (which offers autocomplete search)

2) after the user has completed his input, I use a Rule to create the drupal account : \- dn enables me to search the LDAP with a "View Loop" and get the email \- with the name and the email, the rules can create the drupal account.

I use LDAP Query and LDAP Views to build the view.

The problem is that the View Loop returns empty results although the views results are correct if I use the views from UI.

I have tested the view with no parameter, no filter, simple LDAP Query, minimalistic ldap (3 users in the LDAP). My connection to the LDAP is OK : new users can log in with LDAP before drupal account creation : all this is OK.

Do you know of such an error using LDAP Views as a Rules View Loop ? or could you advice how to debugg ?

Or do you know another way to achieve my goal ? (pick a user from ldap then programmatically create the drupal account ?)

my need is exactly what is described here : https://drupal.asu.edu/resources/docs/modules/asu\_userpicker . But the module is not available at this url and is designed to be used with other tools.

Thanks

# Answer
> 1 votes
I solved the problem by another way :

Within Rules : First action : create a new entity (user) set the account name, set the account email with a fake value in the email. **Second action : unblock user** (if blocked, the user account will not be synchronized from LDAP)

Then , when the account is created, the Drupal account is automatically synchronized from LDAP and get the good email.

(In LDAP configuration , be sure to configre LDAP User / BASIC PROVISIONING TO DRUPAL ACCOUNT SETTINGS/ Drupal Account Provisioning Events to "**Create or Synch to Drupal user anytime a Drupal user account is created or updated.**"

---
Tags: views, rules, authentication-authorization
---


# Question
Title: How to hide terms with no nodes in "Simple Hierarchical Select" in views?
I am using a Simple Hierarchical Select as an exposed filter in views.

How would I hide terms that have no nodes from the select box?

# Answer
> 1 votes
There is no simple way to do that without writing custom module to eliminate the terms you wanted. That said, you can write `hook_form_alter` to achieve this.

```
/**
 * Implements hook_form_alter
 *
 **/
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form' && $form['#id'] == 'YOUREXPOSEDFORMID') {
    foreach ($form['field_tags_tid']['#options'] as $tid => $term_name) {
      if (is_numeric($tid)) {
        $result_count = db_select('taxonomy_index', 'ti')
        ->fields('ti')
        ->condition('ti.tid', $tid, '=')
        ->execute()
        ->rowCount();

        // Removing the option for tags with no-content
        if (!$result_count) {
          unset($form['field_tags_tid']['#options'][$tid]);
        }
      }
    }
  }
}

```

NOTE: Here, I assumed field\_tags\_tid as the field name, should be replaced with the appropriate field name.

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


# Question
Title: Move menu code to the template.php with the associate hook
I have created a **region** (called **menuCustom**) .info file in my template, I created a custom menu and I'm showing in the previously created region.

I created a file called **block--menuCustom.tpl.php** to show it as a **block**.

**My question:** ***How I can move code from the .tpl file to the file template.php?***

I have managed to show the links with the structure needed with the following code:

```
<?php
    $contenidoDesple = $elements['#content'];

    $templateMenu = '<ul class="' . 'desple">';

    foreach ($contenidoDesple as $key => $item) {

        if ($key != '#sorted' && $key != '#theme_wrappers') {

            $enlace = $contenidoDesple[$key]['#href'];
            $nombreEnlace = $contenidoDesple[$key]['#title'];

            $templateMenu .= '<li class="' . 'item">';
            $templateMenu .= '<a class="' . 'link-k" href="' . $enlace . '">' . $nombreEnlace . '</a>';

            if (count($contenidoDesple[$key]['#below']) != 0) {

                $templateMenu .= '<ul class="' . 'sub-menu">';

                foreach ($contenidoDesple[$key]['#below'] as $newKey => $newItem) {

                    if ($newKey != '#sorted' && $newKey != '#theme_wrappers') {
                        $enlace2 = $contenidoDesple[$key]['#below'][$newKey]['#href'];
                        $nombreEnlace2 = $contenidoDesple[$key]['#below'][$newKey]['#title'];

                        $templateMenu .= '<li class="' . 'item">';
                        $templateMenu .= '<a class="' . 'link-k" href="' . $enlace2 . '">' . $nombreEnlace2 . '</a></li>';
                }
            }

            $templateMenu .= "</ul>";

        }

        $templateMenu .= "</li>";

    }

}
$templateMenu .= "</ul>";

print $templateMenu;

?>

```

# Answer
You can add your code to custom module as custom block:

```
/**
 * Implements hook_block_info().
 */
function custom_block_block_info() {
  $blocks = array();
  $blocks['my_block'] = array(
    'info' => t('My Custom Block'),
  );
  return $blocks;
}
/**
 * Implements hook_block_view().
 */
function custom_block_block_view($delta = '') {
  $block = array();
  switch($delta) {
    case 'my_block' :
      $block['content'] = my_block_view();
      break;
  }
  return $block;
}

/**
 * Custom function to assemble renderable array for block content.
 */
function my_block_view() {
  $output = '';
  $menu_array = menu_tree_all_data('main-menu');
  // Prepare your $output variable from $menu_array (like in your code).
  $block = array(
    'menu' => array(
      '#type' => 'markup',
      '#markup' => $output,
    )
  );
  return $block;
}

```

Then show this block in created region.
> 0 votes

---
Tags: theming, hooks
---