title: Export / import content via MySQL

text:
# Question
Title: Export / import content via MySQL
I want to migrate all my content from my old D7 website to my new D7 site, with the Features module I exported/imported all my custom views, fields, etc.

But I don't understand how to export content.

Is there a way to do it from PHPMyAdmin? My two sites are on the same host. I have zero content in the new website. Can I overwrite the tables?

# Answer
Is there way via phpMyAdmin or importing SQL into the database? Yes. Between 2 Drupal installs of the same version that is possible, but that comes with a ***big caveat***. **You need to know exactly what you're wanting to import and that you're not missing anything.**

For example, say you want to import roles. You could export/import the **role.sql** from the `role` table, but that would only get you the *role definition*. If you want the permissions with those roles, you'd need to copy over the `role_permission` table. Depending on your needs this might work; the smaller number of table dependencies, the easier this approach can work without a problem.

However, in your case, you've mentioned a few Drupal components that span multiple data tables (e.g. node types, views, fields, etc.), not to mention other configurations (e.g. module settings in the `variable` table) that a module might depend on to behave the same between 2 installs. To take the example above, the `role_permission` is filled with permission items that are created by various modules. There might be a problem if you don't have all the same modules installed on your new site.

In these cases, and in general, you're better sticking with the tools that the community has created to handle importing the various components of Drupal. For example, the maintainers of Views have already built in a export/import feature for views. There many posts on Drupal Answers discuss these tools (and how to use them). Here are a few examples:
> 1 votes

# Answer
Actually i think, its no good idea to export/import nodes directly via mysql.. there are to many problems like timeouts, awrong machine names and so on...

I would go a way like this post mentions: Node Export and VBO

In this case, the user wants something pretty similar to your goals and you definitely should check out VBO and node export
> 0 votes

---
Tags: 7, database, importing-exporting
---


title: Drupal terms and arrays

text:
# Question
Title: Drupal terms and arrays
I am struggling a bit with the array structure of Drupal.

I am using PHP in a contextual filter inside views. I have the same vocab on both a content type and user via profile2. I manage to get the filter working for single term. The key is in how I return the values at the end of my function.

```
return $items[0]['tid'];

```

This returns 2, a correct tid on user profile taxonomy.

I can also get other values by using:

```
return $items[1]['tid'];

```

This returns 4, also a correct tid.

How would I be able to say?

```
return $items[ALL_ARRAYS]['tid'];

```

So that it would print all the term ids associated with that vocab?

My PHP code:

```
global $user;
$profiles = profile2_load_by_user($user);
    foreach ($profiles as $profile) {
      if ($items = field_get_items('profile2', $profile, 'field_your_interests')) {
        break;
      }
    }
$tids = array();
foreach ($items as $item) {
  $tids[] = $item['tid'];
}
//returns nothing in view, not sure if a contextual filter can handle 'and'?
//return implode(',', $tids);

//This works with 1st value in array
//return $items[0]['tid'];

//This doesn't return anything
  return $tids;

```

# Answer
> 2 votes
There are a few ways you can do this, but this is probably the most straightforward:

```
$tids = array();
foreach ($items as $item) {
  $tids[] = $item['tid'];
}

// Return this if you want to use "or" logic
return implode('+', $tids);

// Return this if you want to use "and" logic
return implode(',', $tids);

```

---
Tags: views
---


# Question
Title: Drupal Commerce product sale price using Rules
I tried Rules like explained here enter link description here. It works but when it comes to checkout, order total amount displays 0. I've got no clue why. Here is my rule:

```
{ "rules_sale_price" : {
    "LABEL" : "\u0426\u0435\u043d\u0430 \u0441\u043e \u0441\u043a\u0438\u0434\u043a\u043e\u0439",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "sale price" ],
    "REQUIRES" : [ "rules", "commerce_product_reference" ],
    "ON" : { "commerce_product_calculate_sell_price" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "commerce-line-item" ], "field" : "commerce_product" } },
      { "entity_has_field" : {
          "entity" : [ "commerce-line-item:commerce-product" ],
          "field" : "field_produkt_sale_price"
        }
      },
      { "NOT data_is_empty" : { "data" : [ "commerce-line-item:commerce-product:field-produkt-sale-price" ] } }
    ],
    "DO" : [
      { "data_set" : {
          "data" : [ "commerce-line-item:commerce-unit-price" ],
          "value" : [ "commerce-line-item:commerce-product:field-produkt-sale-price" ]
        }
      }
    ]
  }
}

```

# Answer
I found the right way to do this: In the rule action I used **Set the unit price to a specific amount** instead of **Set a data value**.
> 1 votes

---
Tags: commerce, rules
---


# Question
Title: Entity Reference Colorbox Format Display
I'm having trouble in creating an album with many galleries, that reference images through entity reference content type from Biblio. I have tried many ways to create the following. But all partially failed.

In my last try I followed the following tutorial: Creating-a-drupal-7-image-gallery-using-content-types-nodes\_tech , it works out fine with the referenced image.

But couldn't complete the tutorial in the following step: I need to change the referenced image format to colorbox, from the Manage Display of Node Image content. Is there way to do the following on a referenced entity?

Is there a better solution?

# Answer
> 1 votes
In the manage display change the format for the referenced image to rendered entity. Then select the gearbox and select colorbox view.

You will need to edit this view mode.So go to biblio content type and manage display. Select colorbox view and change the image field format to colorbox.

---
Tags: entities, javascript, media
---


# Question
Title: How to default a content type's Language field to the authenticated user's language?
We are using Entity Translation so that content can be created in several language. One item we noticed is that on the basic page, for example, has a language field that you can set when you create a piece of content. As of right now, any users regardless of if their profile's preferred language is set to French (for example), the French user is still able to create a content in English.

Ideal scenario:

If a French user logs in and creates content of type basic page, then the language field should be set to French. If a German user logs in and performs the same actions, the language should be restricted to just creating content using the German language.

Any thoughts on how I would set this up?

# Answer
> 1 votes
actually, i would create a custom module (i hope, you know how to code a bit)

the code should be something like the following:

```
    <?php
    function YOUR_CUSTOM_MODULE_node_presave($node){
        global $user; // gets the current user account
        $node->language=$user->language;
    }

```

---
Tags: views, i18n-l10n, multi-sites
---


title: removing the link in the listings title

text:
# Question
Title: removing the link in the listings title
I have removed the title node module element from my listings and replaced it with a text field. The problem is that the text field still works as a link. How do I get rid of the link?

# Answer
> 0 votes
Shawn. OK, I had a content type of "listing." There is a "title" field which has the field type as "node module element" which is automatically created as a field by the view for this page. This field, the title, links to a page displaying the full content. I had to remove this automatic linking. I downloaded a couple of modules to hide the title, and created a new text field to replace the title field, strange enough, this was also converted into linkable text. I then edited "node.tpl.php" to remove the

---
Tags: navigation
---


# Question
Title: What is the difference between using Drupal as a CMS and using it as a Portal?
I have a lot of already existing web applications that are not in Drupal. They are independent systems. I am looking to create an Intranet solution to tie them all together, meaning, have links to them, not an integration with Drupal.

Is this using Drupal as a CMS or a Portal? Does this go against the philosophy of what Drupal is for? I want to use Drupal 8 if it matters.

# Answer
> 1 votes
> Is this using Drupal as a CMS or a Portal?

I would say "CMS", and probably even "CMF" (Content Management *Framework*). E.g. using things such as Webservices.

> Does this go against the philosophy of what Drupal is for?

No, it's just 1 out of dozens of usages of Drupal.

> I want to use Drupal 8 if it matters.

Depends how much in a hurry you are, but I'd strongly recommend to not yet use D8 in production. Some more details on that:

* Use Drupal 7 if you want to build production ready sites today, or in the near future.
* Use Drupal 8 to get ready for "the future". To answer the (next) predictable question (= by when would I have to be ready for that), be aware of the famous quote from "Mr. Dries", which is something like: *Drupal 8 will be ready when it's ready ...*.

# Some more words/thoughts about D8

* I do not think the D8 development architecture will change anymore (therefor it's too late).
* So to start developing with D8 with a production date far away from today might make sense. And if you adapt to the new (OOP) stuff with Symphony, etc, then you probably don't need many more changes by the time D8 gets released.
* Be careful however with an assumption like "... D8 is just about ready". Even if there are only a seven critical issues left before RC1.
* D8's first beta was released at DrupalCon A'dam (2014). And I wouldn't be surprised if somewhere between Sept 17, 2015 and Sept 24, 2015 the first RC1 would be released (at DrupalCon Barcelona). But from then on an official release will not be just a matter of weeks (I "hope" for somewhere in 2016 ... and would "love" it to be in "2015" still).
* The key challenge after D8 is released will be the contrib modules you'd need: if you can get the job done with hardly any contrib modules (now that Views is in core), then you're fine. But what if you'd depend on modules that only support D7? Or modules that don't have a stable D8 release yet, such as the Rules module?

# Future-Proof your Drupal 7 site

To make transitioning to Drupal 8 easier, there are quite some decisions can you make now on your current or new Drupal 7 sites.

For more details on that, refer to the (amazing I think) presentation of David Reid about all those amazing contributed modules in Drupal 7, which are like backports of new Drupal 8 features.

---
Tags: nodes, 8
---


title: One-One mapping between content types

text:
# Question
Title: One-One mapping between content types
I have 2 content types named ***All Events*** and ***Event***. Event as the name is self descriptive it represents an single event (programme). Whereas *All Events* contains additional data related to events, that is not part of any single event.

I need to have a relationship which says '***Featured Event***'. And that relationship is going to be one-one. What would be the best way to select featured event among those events?

To organize this I can create a *field collection* field where each collection represents an event. And again selecting featured content would be question. Having a field in event to make it featured won't work, since 'one-one' wont be respected by the system and user need to take care of it.

# Answer
It's not too clear to me what you are asking but if you want to relate a content-type to another content-type you can use the `Node reference` from the References module.

You can include a field on your `Event` content type called **Featured Event** and relate it back to the `All Events` content type. Then limit the amount of values to one. Then when you create a node from the `Event` CT, you can relate it to whatever node you want from the `All Events` CT. Vice-versa you can create a relationship through the `All Events` nodes if you wanted to as well.

Then if you wanted you could use the Corresponding node references module to sync up `node to node`. This module will warn you if you have overloading references (more than 1:1 for a node) basically helping keep the integrity of the 1:1 relationship.
> 2 votes

---
Tags: entities
---


# Question
Title: How can I add rows to grouping in views?
I have a view that lists terms from two different vocabularies (Product Categories, and Traits). The Product Categories vocabulary looks something like this:

* Sweet Corn
    + Type 1
    + Type 2
* Onions
    + Type 3
    + Type 4
* Popcorn
    + Type 5
    + Type 6

Each of these parent categories also have specific traits that are identified in the Traits vocabulary that looks like this:

* High Expansion
* Augmented
* Celebrate

High Expansion is a trait of Popcorn, Augmented is a trait of Sweet Corn, and Celebrate is a trait of Onions. Traits are different from Categories, and must be defined in a separate vocabulary due to other definitions and functionalities on the site. So, I can't just make them children of the above parent terms.

I have a view that is a main landing page for the product categories that displays the icons for all the Categories and Traits, that the user can click to see a filtered view of products within the category clicked. I am grouping the view results by Parent term, but also need to include the Traits in the appropriate groups.

On my landing page view, I need to list the Traits under the appropriate grouping, so my landing page view should look something like:

* Sweet Corn
    + Type 1
    + Type 2
    + Augmented
* Onions
    + Type 3
    + Type 4
    + Celebrate
* Popcorn
    + Type 5
    + Type 6
    + High Expansion

Is there any way to accomplish this type of grouping?

Thank you for your help!

# Answer
> 0 votes
For this to work "properly" (I say properly because you could fudge it visually with CSS and javascript but let's not do that) without custom code you're going to need to do one of 2 things:

1. Make the "Trait" terms reference the "Category" terms rather than the other way around ...or:
2. Make the "Trait" field on the "Category" terms be an entityreference field rather than a term reference field. This is necessary because entityreference gives you views relationships that let you access the referencing entity.

I'll assume you went with option #2 for the purposes of this write-up. The solution will be quite similar if you went with option #1, but you just won't need to add a relationship in the first view we create, below.

Once you've done that, create 2 views:

1. One that can be used with the Views Field View module (could also be done with the EVA module in a similar fashion) to list the items that belong under the top-level categories.
2. One for listing the top-level categories

## View #1:

This one is the more complicated view. This view is going to take in a term ID of one of the parent categories (like the tid of "Sweet Corn") and we want it to list any terms that are either child terms of that term, *or* are traits of that term.

Install the Views Field View module and the Views Contextual Filters Or module. This view should also be a list of taxonomy terms and needs to be configured like so:

**Relationship:** Add a relationship to the referencing entity via the traits field.

**Contextual Filters:**

1. A contextual filter on the parent term ID.
2. A contextual filter on the term ID (be sure to set this to use the relationship to the referencing entity that we already set up)

Now, we need to make our contextual filters use "or" logic, so if you installed the Views Contextual Filters Or module you will now have an option in your view under Query Settings to turn this on.

## View #2:

This should be pretty straightforward. This will also be a view based on taxonomy terms. You'll probably want to make this use a "page" display and give it a URL. And you'll want to choose to render the terms using "fields".

**Fields:**

* Term name
* Term ID - set this to be excluded from display, we only add it to make it available as a token for our next field
* Global: View -- you'll be able to select the appropriate view and display that you configured when you set up view #1, above. You'll also get to enter arguments to pass to the view, so enter \[!tid\]/\[!tid\]

**Filters:** (just regular filters, not contextual filters)

* Vocabulary (so that it only shows terms from the "Category" vocab.
* Parent term. Set this filter to be equal to 0. This will ensure only top-level terms are displayed.

# Answer
> 1 votes
The views Format Settings has your answer. There is a drop-down for "Grouping field Nr.1" that does exactly this.

As it is, you have one "row" showing for each unique set of values because this is what mysql returns. By setting this field grouping, Views will match up the values from the selected field and use them as headers for sub sections of your results.

If this is not a good enough match to your issue, please provide details on how it doesn't work and I can update the answer.

---

**Continued**:

The view is a tool for making a mysql query and then theming the returned result. With this in mind, you need to craft a set of data relations and filters to get the appropriate data linkages for the ratios you want in your display. This means you want the database handing you a field table like:

Category parent | product | category | trait

1. Sweet Corn | corn product 1 | Type 1 | Null
2. Sweet Corn | corn product 2 | Type 2 | Null
3. Sweet Corn | generic corn product | Null | Augmented
4. Onions | onion product 1 | Type 3 | Null
5. Onions | onion product 3 | Null | Celebrate

Then once you have the dataset you need, you work on the theming side of the views tool. Use the above mentioned Grouping field setting on the Category Parent. This will make the sections with the parent titles as indicated in your question, but it might look like

* Sweet Corn
    + corn product 1 | Type 1 |
    + generic corn product | | Augmented

Then use the "exclude from display" on the product field, or actually remove it from the fields list. I have it included here because it is needed to show the data grouping as I understand it in your question. Finally, configure the "category" field with the link you want it to have and exclude it from display; use the "No Results Behavior" rewrite option on Trait to put in the token for the Category field, something like \[field\_term\_category\]. You should be able to find this token in the list of "replacement patterns" available in the Rewrite Results area.

You should now have a list of parent categories showing the linked sub categories and traits where you want them. The "trait" field will either have the category or the trait in there, as it shows trait when trait is present, and category when not. Be sure to uncheck the "hide if empty".

---
Tags: views, theming
---


# Question
Title: Views Contextual filter: php code for getting the value from url
Im trying to set up a Contextual filter in drupal views based on the URL.

The contextual filter is operating with a text field that sets the node alias.

I have it working with "RAW value from URL" based on the position (parentpage/childpage/grandchild-page), but the position could change (only parents and child for example), so do i need to use the "PHP code", or is there a better way?

What i want to happen:

"If last section of page url, (grandchild-page), matches field set in contextual filter, then true (show fields).

# Answer
Though the solution you have implemented worked but my suggestion is to use the request\_uri() instead of the `$_SERVER['REQUEST_URI']` because of the following reasons:

* `$_SERVER['REQUEST_URI']` is only available on Apache, whereas `request_uri()` generate an equivalent using other environment variables.
* Apache does nothing by default to sanitize the `$_SERVER` variables so directly using it without passing through the `check_plain` should be considered unsafe.

So its better to get the URL like this:

> $current\_url = check\_plain(request\_uri());

Example: if the url is `http://www.example.com/param1/param2/param3` than the `$current_url` will contain `/param1/param2/param3`.

Rest you can build the logic to get the last params, there are numerous ways of doing that.
> 1 votes

# Answer
You do not have to use PHP code - there is a module for that: https://www.drupal.org/project/views\_contextual\_filter\_query

OR you could use Context: https://www.drupal.org/project/context\_query\_param
> 1 votes

# Answer
Thank you J. Reynolds for pointing me in the right direction!

I have used the following in "When the filter value is NOT available \> provide a default argument \> PHP Code"

```
$url = $_SERVER["REQUEST_URI"];
$url_path = parse_url($url, PHP_URL_PATH);
$basename = pathinfo($url_path, PATHINFO_BASENAME);
return $basename;

```

($basename is matching the last segment of the URL which is set via pathauto from a custom pseudo title field on my content type, and this field is also used the operational contextual filter in Views.)

EDIT: I also have a Relationship "Content referencing Content from field\_related\_products" that is selected in the contextual filter.

*Please refer to the answer from Ankit Agrawal for a better way to retrieve the URL*
> 0 votes

---
Tags: views
---


# Question
Title: Managed_file form does not show #default_value
I am using managed\_file in Drupal 7 for my custom module. Other than the form api and managed\_file, I'm using my own custom tables for this module.

This will eventually be used on shared hosting via Dreamhost, so the requirements of using PECL extensions are probably not available at this answer suggests.

The behavior I want is when the file is uploaded by clicking the "upload" button, I at least want the image file to be a link that appears to indicate to the user that the file is uploaded. When I left the default #progress\_indicator in place, the AJAX indicates it never uploads. However, this is false as I can see the file in managed\_file table in the db.

I've looked through several searches for this and this is the form that I've come up and I cannot see what I'm doing wrong.

$item is the result of a database call of the previous object. Its genesis was derived from a post jaypan provided.

```
$form['#item'] = $item;

dpm($item); => //every attribute to the sponsor object in the database.

$uri = isset($item->logoFileID) ? fetch_name('file_managed', 'uri', 'fid', $item->logoFileID) : '';

$uri = isset($item->logoFileID) ? fetch_name('file_managed', 'uri', 'fid', $item->logoFileID) : '';
dpm($uri); => 'public://logos/myfile.gif' //to show valid return of $uri
dpm($item-logoFileID); => 'public://logos/myfile.gif'

  $form['logoFileID'] = array(
    '#title' => 'file key',
    '#type' => 'hidden',
    '#default_value' => $item->logoFileID,
    );
 $form['logo_fid'] = array(
    '#type' => 'managed_file',
    '#title' => t('Logo'),
    '#description' => t('Upload a file, allowed extensions: jpg, jpeg, png, gif'),
    '#upload_location' => 'public://logos/',
    '#progress_indicator' => 'none',
    '#default_value' => $file->uri,
    );

```

As I said, managed\_file does save the file and returns an fid that I save with the sponsor record. The behavior I have gotten in this module is that the filename was showing in this part of a form, that when clicked in Drupal shows a popup modal of the image. My question is how do I get this back link back to appear in the form to show the user it has been uploaded?, thx sam

# Answer
The value of a managed file field is a file ID, rather than its URI.

Assuming `$file` in your code is a file object, change the element array to:

```
$form['logo_fid'] = array(
  '#type' => 'managed_file',
  '#title' => t('Logo'),
  '#description' => t('Upload a file, allowed extensions: jpg, jpeg, png, gif'),
  '#upload_location' => 'public://logos/',
  '#progress_indicator' => 'none',
  '#default_value' => $file->fid,
);

```
> 2 votes

---
Tags: files
---


# Question
Title: Varnish is serving sometime wrong cache theme on desktop or in mobile
**Setup** \- We have Varnish in front of three drupal backend server. Varnish is serving as a cache and load balancer. Load balancer is using round robin director. It also does the device detection together with a drupal module (https://www.drupal.org/project/mobile\_switch\_varnish) to switch between the desktop and mobile theme.

**device- detection code (vcl) is below -**

```
sub vcl_recv {
  call identify_device;
}

sub identify_device {
    unset req.http.X-UA-Device;
    set req.http.X-UA-Device = "pc";

    # Handle that a cookie may override the detection alltogether.
    if (req.http.Cookie ~ "(?i)X-UA-Device-force") {
        /* ;?? means zero or one ;, non-greedy to match the first. */
        set req.http.X-UA-Device = regsub(req.http.Cookie, "(?i).*X-UA-Device-force=([^;]+);??.*", "\1");
        /* Clean up our mess in the cookie header */
        set req.http.Cookie = regsuball(req.http.Cookie, "(^|; ) *X-UA-Device-force=[^;]+;? *", "\1");
        /* If the cookie header is now empty, or just whitespace, unset it. */
        if (req.http.Cookie ~ "^ *$") { unset req.http.Cookie; }
    } else {
        if (req.http.User-Agent ~ "\(compatible; Googlebot-Mobile/2.1; \+http://www.google.com/bot.html\)" ||
            (req.http.User-Agent ~ "iPhone" && req.http.User-Agent ~ "\(compatible; Googlebot/2.1; \+http://www.google.com/bot.html")) {
            set req.http.X-UA-Device = "mobile-smart"; }
        elsif (req.http.User-Agent ~ "(?i)ipad")
                    { set req.http.X-UA-Device = "mobile-tablet"; }
        elsif (req.http.User-Agent ~ "(?i)ip(hone|od)")
                    { set req.http.X-UA-Device = "mobile-smart"; }
        /* how do we differ between an android phone and an android tablet?
           http://stackoverflow.com/questions/5341637/how-do-detect-android-tablets-in-general-useragent */
        elsif (req.http.User-Agent ~ "(?i)android.*(mobile|mini)")
                    { set req.http.X-UA-Device = "mobile-smart"; }
        // android 3/honeycomb was just about tablet-only, and any phones will probably handle a bigger page layout.
        elsif (req.http.User-Agent ~ "(?i)android 3")
                    { set req.http.X-UA-Device = "mobile-tablet"; }
        /* Opera Mobile */
        elsif (req.http.User-Agent ~ "Opera Mobi")
                    { set req.http.X-UA-Device = "mobile-smart"; }
        // May very well give false positives towards android tablets. Suggestions welcome.
        elsif (req.http.User-Agent ~ "(?i)android")
                    { set req.http.X-UA-Device = "mobile-tablet"; }
        elsif (req.http.User-Agent ~ "PlayBook; U; RIM Tablet")
                    { set req.http.X-UA-Device = "mobile-tablet"; }
        elsif (req.http.User-Agent ~ "hp-tablet.*TouchPad")
                    { set req.http.X-UA-Device = "mobile-tablet"; }
        elsif (req.http.User-Agent ~ "Kindle/3")
                    { set req.http.X-UA-Device = "mobile-tablet"; }
        elsif (req.http.User-Agent ~ "Touch.+Tablet PC")
                    { set req.http.X-UA-Device = "mobile-tablet"; }
        elsif (req.http.User-Agent ~ "Mobile.+Firefox")
                    { set req.http.X-UA-Device = "mobile-other"; }
        elsif (req.http.User-Agent ~ "^HTC" ||
            req.http.User-Agent ~ "Fennec" ||
            req.http.User-Agent ~ "IEMobile" ||
            req.http.User-Agent ~ "BlackBerry" ||
            req.http.User-Agent ~ "BB10.*Mobile" ||
            req.http.User-Agent ~ "GT-.*Build/GINGERBREAD" ||
            req.http.User-Agent ~ "SymbianOS.*AppleWebKit")
                    {
            set req.http.X-UA-Device = "mobile-smart";
                    }
        elsif (req.http.User-Agent ~ "(?i)symbian" ||
            req.http.User-Agent ~ "(?i)^sonyericsson" ||
            req.http.User-Agent ~ "(?i)^nokia" ||
            req.http.User-Agent ~ "(?i)^samsung" ||
            req.http.User-Agent ~ "(?i)^lg" ||
            req.http.User-Agent ~ "(?i)bada" ||
            req.http.User-Agent ~ "(?i)blazer" ||
            req.http.User-Agent ~ "(?i)cellphone" ||
            req.http.User-Agent ~ "(?i)iemobile" ||
            req.http.User-Agent ~ "(?i)midp-2.0" ||
            req.http.User-Agent ~ "(?i)u990" ||
            req.http.User-Agent ~ "(?i)netfront" ||
            req.http.User-Agent ~ "(?i)opera mini" ||
            req.http.User-Agent ~ "(?i)palm" ||
            req.http.User-Agent ~ "(?i)nintendo wii" ||
            req.http.User-Agent ~ "(?i)playstation portable" ||
            req.http.User-Agent ~ "(?i)portalmmm" ||
            req.http.User-Agent ~ "(?i)proxinet" ||
            req.http.User-Agent ~ "(?i)sonyericsson" ||
            req.http.User-Agent ~ "(?i)symbian" ||
            req.http.User-Agent ~ "(?i)windows\ ?ce" ||
            req.http.User-Agent ~ "(?i)winwap" ||
            req.http.User-Agent ~ "(?i)eudoraweb" ||
            req.http.User-Agent ~ "(?i)htc" ||
            req.http.User-Agent ~ "(?i)240x320" ||
            req.http.User-Agent ~ "(?i)avantgo")
                    {
            set req.http.X-UA-Device = "mobile-other";
                    }
    }
}

sub vcl_hash {
    #Default Hash
    hash_data(req.url);
   if (req.http.host) {
        hash_data(req.http.host);
    } else {
        hash_data(server.ip);
    }

    #hash based on device type
    if (req.http.X-UA-Device ~ "^mobile") {
        hash_data(req.http.host+req.http.X-UA-Device);
    }

    //return (hash);
}

**PHP code (written in module) which switch the theme is below -**

/**
 * Implements hook_custom_theme()
*/
function yt_switchtheme_custom_theme(){
  // Detect if this is a mobile device.

  if (isset($_SERVER['HTTP_X_UA_DEVICE']) && strstr($_SERVER['HTTP_X_UA_DEVICE'], 'mobile')) {

    // Bail if this is an admin page and we don't respect admin pages.
    if (path_is_admin(current_path()) && !variable_get('mobile_switch_varnish_use_on_admin_pages', FALSE)) {
      return;
    }
    // Fetch the device type from the server variable.
     $device_type = substr($_SERVER['HTTP_X_UA_DEVICE'], 7);
    // If the mobile theme for device is empty (unlikely) or set to 'default' then return the default mobile theme.
    if (!variable_get('mobile_switch_varnish_theme_' . $device_type, 'default') || variable_get('mobile_switch_varnish_theme_' . $device_type, 'default') == 'default') {
      return variable_get('mobile_switch_varnish_theme_default', 'mobile_jquery');
    }
    // Else it's been set specifically; use this theme setting instead.
    else {
      return variable_get('mobile_switch_varnish_theme_' . $device_type, 'default');
    }
  }
}

```

Now problem is usually it serves desktop theme and mobile theme right on desktop and mobile device respectively but sometime it serve the mobile theme on desktop and vice-versa.

How can I stop it from happening?

# Answer
> -1 votes
I have the same problem, I'm going to try using this: https://www.drupal.org/project/mobile\_switch\_varnish hope it works...

---
Tags: caching, proxies
---


# Question
Title: Content View to sort results to match the users Profile 2 taxonomy term
I have a taxonomy term that gets assigned to a content type via entity reference, and the Drupal user, via Profile 2.

I want to add a filter to a content view that matches the 2 up, so if you filled in your user profile saying you only interested in x, have a view that only show content that was assigned with the same term.

I have tried adding author, profile2, taxonomy term relationships etc without any luck. Any pointers would be greatly appreciated.

# Answer
I managed to solve this: The key is to start with an **User View**.
**Add Relationship -\> User: Profile**
Pick the profile where the taxonomy was assigned.
**Add Relationship -\> Content: Taxonomy terms on node**
Pick your vocabulary.
**Add Relationship -\> User: Content authored**
**Add Contextual filter -\> Content: Has taxonomy term ID**
Choose PHP as a Provide default value option:

```
global $user;
$profiles = profile2_load_by_user($user);
    foreach ($profiles as $profile) {
      if ($items = field_get_items('profile2', $profile, 'field_your_interests')) {
        break;
      }
    }
$tids = array();
foreach ($items as $item) {
  $tids[] = $item['tid'];
}
return implode('+', $tids);

```

Then add the fields and additional filters as needed.

Resources:
http://blog.ampli.fi/filtering-a-drupal-7-view-based-on-multiple-user-profile-fields/
https://www.drupal.org/node/1111722#comment-4315620
Drupal terms and arrays \- thanks Aaron!
> 1 votes

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


title: Send email from template file

text:
# Question
Title: Send email from template file
I am making a return request page for my website the user will enter in his/her information about their order and it will pull up a list of their order. The information is pulled from the views then submitted to the confirmation page.

I already have the form validation working but I need the validation code written in the **page--node--nodeid.tpl.php** to send an email to 2 people, the customer and me, using the information from the form.

I've seen drupal\_mail(), but this seems like it needs to be used in a module.

Is this even possible?

On a side note it would be helpful to be able to use a template later.

# Answer
> 2 votes
Doing all of this within templates really shouldn't be the way to go. Write a custom module. And then do the following:

1. Use `hook_menu()` to create a page. Page callback would be `drupal_get_form`. Page argument would be `YOURMODULE_form`.
2. Inside `YOURMODULE_form()` you'll create your form. Check Form API for detailed info.
3. Finally you have to add a submit function `YOURMODULE_form_submit()` where you do your processing and use `drupal_mail()` to build and send your emails.

Maybe look at a little module I once wrote myself that follows a similar approach, form to mail, only it doesn't happen on a page but in a block instead. So that it can be placed on every page you want.

---
Tags: 7, theming
---


# Question
Title: How to programmatically create new file/folder in Drupal 7 files directory?
I tried to create new file/folder programmatically inside Drupal's sites/default/files. But I'm getting this error: "Can't Open file".

Here is what I'm doing: When my registered user visits a certain page, I will be generating a new file and I will provide them with the download link. When I tried to create a new file I am getting "can't open file" message. I'm in localhost in MS Windows.

Are there any other writable folder other than sites/default/files for doing this stuff?

Below is my code:

```
$ourFileName = base_path()."/sites/default/files/members-pdf/testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);

```

Above code is written inside a views's template file.

I want to use PHP file API and not Drupal 7 file API.

# Answer
> 8 votes
To create folders you can use file\_prepare\_directory and pass FILE\_CREATE\_DIRECTORY as second parameter like so:

```
$new_folder = 'public://newfolder/';
file_prepare_directory($new_folder, FILE_CREATE_DIRECTORY);

```

---
Tags: 7, files
---


title: Alternate modules/themes directory

text:
# Question
Title: Alternate modules/themes directory
I'm trying to setup an alternate modules and themes directory which I can track with GIT separate from the contributed modules directory.

Following this question, I created a directory in the following structure:

```
/var/www/Mysite
       -sites/samplesite/modules/mymodule

```

**mymodule** was working just fine when it was based in *sites/all/modules/custom/mymodule* but once moved it was no longer listing on the modules page, nor the features page - mymodule is features generated.

I attempted the following directory structure:

```
/var/www/samplesite
       -sites/samplesite/modules/mymodule

```

But it's still not working.

Can anyone please help me with this problem?

# Answer
> 0 votes
Putting modules in sites/samplesite/modules/mymodule is specifically for a multi-site setup.

Drupal won't just load all modules in all sites directories all the time, it will only load modules in the samplesite directory if you are hitting the samplesite domain (or you have an entry in the sites/sites.php file to tell Drupal which domains map to samplesite.

The other option from the page you link to is to make a directory in sites/all/modules that is a symlink to your custom module directory. Then (assuming you're using Apache), make sure your server is configured to enable the FollowSymLinks option.

There are also a couple of other options:

* Add a directory for your modules, eg. sites/all/modules/samplesite or whatever is logical to call it. Exclude that directory in your main .gitignore file. make that new directory a clone of your other modules repository. Alternatively you could not have the sub directory and have separate repositories for each module.
* Using a similar directory structure as above, use git subtree to have a repository in a repository (or many individual module repositories if that is your requirement). This seems like a decent post to give you more information on git subtree: http://getlevelten.com/blog/tom-mccracken/smarter-drupal-projects-projects-management-git-subtree

Either method may be preferable depending on your situation however I would probably recommend the subtree method over the completely separate repositories. It would be easier to manage things like deployments, since with the subtree method the main repo still contains everything, even though the source repos are different.

---
Tags: 7
---


# Question
Title: Create picture module responsive styles programmatically
I could not find any documentation anywhere on how to programmatically create a new picture module responsive style set so am adding what I've discovered here.

# Answer
First step is to create the image styles:

```
// 1. Create image styles
$multipliers = array(
  '1x' => 1,
  '1_5x' => 1.5,
  '2x' => 2,
);
foreach($multipliers as $label => $multiplier) {
  $style = image_style_save(array('name' => 'tile_image_' . $label));
  $effect = array(
    'name' => 'image_scale_and_crop',
    'data' => array(
      'width' => 390 * $multiplier,
      'height' => 194 * $multiplier,
      'upscale' => TRUE,
    ),
    'isid' => $style['isid'],
  );
  image_effect_save($effect);
}

```

Then create a group for the image styles:

```
// 2. Create image group
$new_group = breakpoints_breakpoint_group_empty_object();
$new_group->machine_name = 'tile_image';
$new_group->name = 'Tile image group';
$new_group->type = BREAKPOINTS_SOURCE_TYPE_CUSTOM;
$new_group->breakpoints = array('breakpoints.theme.armi_embl_theme.desktop', 'breakpoints.theme.armi_embl_theme.mobile');
breakpoints_breakpoint_group_save($new_group);
menu_rebuild();

```

And then finally define the mapping between the image styles and your set of breakpoints:

```
// 3. Add picture mapping
$mapping = picture_mapping_create(TRUE);
$mapping->table = 'picture_mapping';
$mapping->type = 'Normal';
$mapping->export_type = 1;

$mapping->label = 'Tile image mapping';
$mapping->machine_name = 'tile_image_mapping';
$mapping->breakpoint_group = 'tile_image';
$mapping->mapping = array(
  'breakpoints.theme.armi_embl_theme.desktop' => array(
    '1x' => array(
      'mapping_type' => 'image_style',
      'image_style' => 'tile_image_1x',
    ),
  ),
  'breakpoints.theme.armi_embl_theme.mobile' => array(
    '1x' => array(
      'mapping_type' => 'image_style',
      'image_style' => 'tile_image_1x',
    ),
    '1.5x' => array(
      'mapping_type' => 'image_style',
      'image_style' => 'tile_image_1_5x',
    ),
    '2x' => array(
      'mapping_type' => 'image_style',
      'image_style' => 'tile_image_2x',
    ),
  ),
);

picture_mapping_save($mapping);

```
> 1 votes

---
Tags: 7, media
---


# Question
Title: Reload page after applying commerce coupon
I'm quite obsessed on one page checkout using drupal commerce kickstart. I'm using commerce coupon(wonderful module) and we all know that there's a possibility that the order total price could be zero if you we apply a 100% coupon module. I see this post Commerce - how to set no payment for free orders when 100% coupon applied and I guess we are having the same problem. I did not see any way to ajax refresh the payment method pane, and my last work around is to reload the entire page after applying coupons.

Is there a way to reload the entire page after applying coupons?

Thanks.

# Answer
> 0 votes
One solution here is to add a custom JS behavior to your module that looks for the AJAX callback context of applying a coupon. Upon such context, you can refresh the page or update the DOM as you see fit.

```
(function ($) {
Drupal.behaviors.mymodule = {
  attach: function (context, settings) {

    //Look for the context of a coupon form AJAX callback
    //If there's no error message, assume successful coupon application
    if($(context[0]).attr('id') == 'commerce-checkout-coupon-ajax-wrapper' && !$(context[0]).find('.messages').hasClass('error')) {
      //@TODO: Reload page or other JS to refresh coupon usage
    }
  }
};
}(jQuery));

```

---
Tags: commerce
---


# Question
Title: rewrite with nginx conf result 502 bad gateway
My code is based on http://wiki.nginx.org/Drupal and the result is 502 bad gateway. I have tried so many ways but dont work.... how i can solve this? thanks

```
server {
        listen 8093;
        server_name localhost;
        root /home/ITEP;

        # Enable compression, this will help if you have for instance advagg module
        # by serving Gzip versions of the files.
        #gzip_static on;

        location = /favicon.ico {
                log_not_found off;
                access_log off;
        }

        location = /robots.txt {
                allow all;
                log_not_found off;
                access_log off;
        }

        # This matters if you use drush prior to 5.x
        # After 5.x backups are stored outside the Drupal install.
        #location = /backup {
        #        deny all;
        #}

        # Very rarely should these ever be accessed outside of your lan
        location ~* \.(txt|log)$ {
                allow 192.168.0.0/16;
                deny all;
        }

        location ~ \..*/.*\.php$ {
                return 403;
        }

        # No no for private
        location ~ ^/sites/.*/private/ {
                return 403;
        }

        # Block access to "hidden" files and directories whose names begin with a
        # period. This includes directories used by version control systems such
        # as Subversion or Git to store control files.
        location ~ (^|/)\. {
                return 403;
        }

        location / {
                # This is cool because no php is touched for static content
                try_files $uri @rewrite;
        }

        location @rewrite {
                # You have 2 options here
                # For D7 and above:
                # Clean URLs are handled in drupal_environment_initialize().
                rewrite ^ /index.php;
                # For Drupal 6 and bwlow:
                # Some modules enforce no slash (/) at the end of the URL
                # Else this rewrite block wouldn't be needed (GlobalRedirect)
                #rewrite ^/(.*)$ /index.php?q=$1;
        }

        location ~ \.php$ {
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                #NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
                include fastcgi_params;
                fastcgi_param SCRIPT_FILENAME $request_filename;
                fastcgi_intercept_errors on;
                fastcgi_pass unix:/tmp/phpfpm.sock;
        }

        # Fighting with Styles? This little gem is amazing.
        # This is for D6
        #location ~ ^/sites/.*/files/imagecache/ {
        # This is for D7 and D8
        location ~ ^/sites/.*/files/styles/ {
                try_files $uri @rewrite;
        }

        location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
                expires max;
                log_not_found off;
        }
}

```

I'm using drupal 7.... fresh install

# Answer
> 1 votes
The location of file `phpfpm.sock` may vary depending on Operating System:

Try find the `phpfpm.sock` file on your server: `find / -name php*fpm.sock`

and then change the following line `fastcgi_pass unix:/tmp/phpfpm.sock;`

to reference `phpfpm.sock` from the correct location.

Example (Ubuntu 14): `fastcgi_pass unix:/var/run/php5-fpm.sock;`

---
Tags: 7
---


# Question
Title: 7 - access callback get currently checked path
In my module I have lots of different pages. All pages, as defined in `mymodule_menu`, access the same access callback function `mymodule_user_access` and perform different things based on the parameters passed. Now as far as I understand drupal calls that function for all the menu items that may be rendered on the page, which means that if there are 10 menu items visible, it will call the function for each one of them separately. What I would like to have is some way of seeing what path drupal is currently checking when the function is accessed. So if I have

```
$items['mymodule'] = array(
    //some stuff here
    'access callback' => 'mymodule_user_access',
    //some more stuff
);

$items['mymodule/path1'] = array(
    //some stuff here
    'access callback' => 'mymodule_user_access',
    //some more stuff
    'type' => MENU_LOCAL_ACTION,
);

$items['mymodule/path2'] = array(
    //some stuff here
    'access callback' => 'mymodule_user_access',
    //some more stuff
    'type' => MENU_LOCAL_ACTION,
);

```

which means that when I access mymodule page the `mymodule_user_access` page is accessed 3 times (for mymodule, mymodule/path1, mymodule/path2). What I would love to do is:

```
function mymodule_user_access() {
    drupal_set_message($path); //This should output 3 different messages: mymodule, mymodule/path1, mymodule/path2
}

```

Is it possible without explicitly sending the path as a parameter in `access arguments`?

UPD: I tried `current_path` but it returns the path I am trying to access. Same with `arg()`

# Answer
Based on my research, I checked first the current\_path() function and in it's code it gets the path by `$_GET['q']` w/c indicates only getting the values fro the URL so this wouldn't work.

I also checked the access callback and access arguments' functionality and initially I noticed that access arguments are meant for the actual use that you are trying to bypass where links needs to be checked to let Drupal know if it will display a link. The only way is does this is by specifying the access arguments.

In my opinion, the access arguments array standardizes where the "access specifications" would come from like this menu's access specs are basing on the second and third arguments. So developers would know what they're dealing with by looking at the access arguments array and user the access callback just to do mostly logic.

I hope this could help.
> 0 votes

---
Tags: 7, users
---


title: Drupal 6 exposing fields in views

text:
# Question
Title: Drupal 6 exposing fields in views
So I have a product content type with a title field and a file upload field and I created a bulk operation to enable the user to upload a single file, selecting which titles to upload that file for.

But what my client really wants is a page (instead of modifying each individual node) with a list of the product titles and a file upload next to each since most of the products use different files. My view is defined with a table style instead of the bulk operations style and has the title field and the file upload field displayed but in the preview, the file upload field column only shows the file names for the titles which already have a file uploaded and the rest of the rows blank.

Is there a way to expose this file upload field like you do a filter so the user can upload a different file for each title ??

# Answer
Based on some research, I was able to find Editview for Drupal 6. I'm not quite sure if it's like how Editable views work for Drupal 7.

It states in the Editview's module page that,

> It allows you to create a view in which the nodes are editable, and new nodes can be created.

Hope this helps.
> 0 votes

---
Tags: entities, views
---


# Question
Title: Remove header and footer of the page when export node to pdf using print module
When I use the print module for export node to the pdf file are facing a problem that I could not handle that it automatically generates header and footer for my page pdf. I want to remove the header and footer of the page. Can someone guide me how to deal with it. Thank you very much.

# Answer
> 1 votes
Go to

**Home » Administration » Configuration » User interface » Printer, email and PDF versions**

then in **SETTINGS** page, check option **none** in **FOOTER OPTIONS** tab.

---
Tags: nodes, files
---


# Question
Title: how to show node title when mouseover on image in the node by drupal views?
I have a content type in which there is a cck image field and now I have listed the images with the node title as a block by views.

Now I want to show the node title when user mouseovers the image. I think I can implement it by views itself but I don't know how to do it?.

Can anyone help?

# Answer
I don't think you can do that using views. However you can "hack" a way to add title element to a div, for instance.

go to your view config page

add a node: title field.

edit the node: title field.

tick "Exclude from display" and "strip HTML tags"

click save

move the title node to top of the fields.

edit your image field and tick "Rewrite the output of this field"

a textarea appears. write this code in the textarea

```
<div title="[title]">[image]</span>

```

Note: the \[fields\] are tokens. If you already have a title field, you don't need to exlude it, you can re-use it.

if the image displays another title its because the module automatically sets a title tag to the image. You can either change this tag with javascript:

```
document.getElementById("idElement").setAttribute("Title", "title");

```

or edit your image module and set the page title to be your title tag.
> 2 votes

# Answer
Use a `<span>` tag on your views like so:

```
<span title="[title]">[image]</span>

```
> 0 votes

---
Tags: views, entities
---


# Question
Title: Finding all nodes not referenced by a menu entry or another node
In the course of creating the content for a site, we've ended up with orphaned content nodes that are not linked to from anywhere. I'd like to find and examine these. Surprisingly, I can't find a module for this.

Tiny hypothetical example: I'm building a brochureware site. Someone wrote a "Contact" page, someone else wrote an "About Us", and someone else wrote "Directions". The person writing "Directions" forgot to put it in a menu link or add a link from "About Us" to "Directions". So "Directions" is orphaned: there are no links to it. I'd like to find all such nodes so I can figure out what to do with them.

# Answer
> 3 votes
**For links from the menu system:**

Menu Node Views comes very close to what you request but needs some coding.

**For links from the body (fields) of nodes:**

The Search module saves references between nodes. This can be used by views to create a "backlinks" view. For Drupal 5 there was a seperate module for this with some aditional explenation, since D6 (Views 2/3) this functionallity is baked into Views Module.

**Summary**

views \+ vbo \+ Menu Node API \+ Menu Node Views ( + custom filter/patch or View with custom query )

# Answer
> 5 votes
I needed this for a clients request, so i decided to try and do it without any additional modules, and push my MySQL a bit. This is what i ended up with.

For clarity, this will only provide a list of NID's that DO NOT have an associated menu item.

I've also added a WHERE clause to limit content types, as some content types will naturally be excluded because of the way they was architected.

```
SELECT n.nid, n.type, n.title, n.status
FROM node AS n
WHERE (n.type = 'article' OR n.type = 'page')
AND n.nid NOT IN (
  SELECT REPLACE(link_path, "node/", "") AS nid
  FROM menu_links
  WHERE SUBSTRING(link_path, 6, LENGTH(link_path)) REGEXP "^[0-9]+$"
);

```

# Answer
> 2 votes
Have you tried Views? You'll need to create a view for the orphaned nodes, which would depend on your taxonomy and fields.

# Answer
> 2 votes
You can accomplish the menu portion pretty easily with a custom query.

```
SELECT *
FROM node
WHERE node.type = 'page'
AND node.nid NOT IN (
 SELECT nid
 FROM menu_node
)

```

---
Tags: nodes
---


title: Nested AJAX calls to a site

text:
# Question
Title: Nested AJAX calls to a site
I've been making this cordova app against this casting agency website, and I've come across this nasty situation where I need to list each user's created nodes. For this purpose, I have created a view with the contextual filter `uid` and it's taking the uid from the logged user. I also have this fiddle where I am trying to list each user's nodes. However, it's returning empty (2nd ajax call). The weird thing is, it lists the nodes by the logged in user on this URL username is `tolga` and password is `111222`.

The steps I have taken to debug:

* Hardcode the username and password.
* Hardcode the uid in the 2nd ajax call without deleting the 1st one.
* Delete the 1st ajax call.
* After deleting the 1st call, hardcode the uid in the 2nd call.
* After deleting the 1st call, not pass the uid at all because I have configured the contextual filter to take the uid from the logged in user.

Nothing worked. Am I missing something? Do I need to use something like Services Views?

UPDATE: I tried using Services Views, and I ended up a whole lot of `404: Resource not found` messages. Docs for the module and views say different things for path; docs say `http://www.example.com/<endpoint-path>/views/<view-name>` while the view says to put the path name after the endpoint path (in my case, `services`)

# Answer
> 1 votes
I found out the hard way that what was not working on jsfiddle.net was actually working on mobile. I wasted my own evening on this issue :S Thanks for all the comments though guys.

---
Tags: ajax, services
---


# Question
Title: How to integrate an exported Rules component in a custom module?
i have created list of component fields in a Drupal 7 module, copied the exported Rules code and then pasted it into our custom module

But it is not working. Any ideas how to get it to work?

This is my exported Rule:

```
$rule = '{ "rules_faircent_rules" : {
"LABEL" : "Faircent Rules",
"PLUGIN" : "rule set",
"OWNER" : "rules",
"TAGS" : [ "Faircent Rules" ],
"REQUIRES" : [ "rules" ],
"USES VARIABLES" : {
  "fc_home_city" : { "label" : "Home city ", "type" : "integer" },
  "fc_pin" : { "label" : "Pin Code", "type" : "integer" },
  "fc_loan" : { "label" : "Loan Type", "type" : "integer" }
},
"RULES" : [
  { "RULE" : {
      "PROVIDE" : { "result" : { "result1" : "Calculation result", "result" : "Calculation result" } },
      "IF" : [
        { "data_is" : { "data" : [ "fc-home-city" ], "value" : "10" } },
        { "data_is" : { "data" : [ "fc-pin" ], "value" : "5" } },
        { "data_is" : { "data" : [ "fc-loan" ], "value" : "12" } }
      ],
      "DO" : [
        { "data_set" : { "data" : [ "fc-loan" ], "value" : "35" } },
        { "data_set" : { "data" : [ "fc-home-city" ], "value" : "15" } },
        { "data_set" : { "data" : [ "fc-pin" ], "value" : "25" } },
        { "data_calc" : {
            "USING" : { "input_1" : [ "fc-home-city" ], "op" : "+", "input_2" : [ "fc-pin" ] },
            "PROVIDE" : { "result" : { "result1" : "Calculation result" } }
          }
        },
        { "data_calc" : {
            "USING" : { "input_1" : [ "result1" ], "op" : "+", "input_2" : [ "fc-loan" ] },
            "PROVIDE" : { "result" : { "result" : "Calculation result" } }
          }
        }
      ],
      "LABEL" : "Calculate over all "
    }
  }
]

```

} }';

```
$configs['commerce_checkout_order_email'] = rules_import($rule);
echo '<pre>';
print_r($configs['commerce_checkout_order_email'] );

```

Above code is not working for me. What will be exact solution?

# Answer
Here is what's needed to integrate your exported Rules component in a custom module:

```
<?php
function MY_MODULE_NAME_default_rules_configuration() {
  $configs = array();
  $rule = '{ "my_exported_rule" : {
    "LABEL" : "My Exported Rule",
    ...,
  }
}';
  $configs['my_exported_rule'] = rules_import($rule);
  return $configs;
}
?>

```

So to use such exported Rule, you need to run it through the function `rules_import()`. This will change the exported Rule in a format that is usable for the Rules module.

To reuse this example:

* Replace MY\_MODULE\_NAME with the machine name of your module.
* Replace the value used for `$rule` by the content of your exported rule.
* Make sure to use the machine name of your rule (= `my_exported_rule` in my sample) as the key in `$configs`.

In the sample contained in the question, the machine name of the rule is `rules_faircent_rules`, though that is NOT what is used in the `$configs` ... Therefor I think you should correct your code like so:

```
$configs['rules_faircent_rules'] = rules_import($rule);
echo '<pre>';
print_r($configs['rules_faircent_rules'] );

```

Refer to the articled "Drupal 7 - Defining rules within a module using PHP" for some more details.
> 3 votes

# Answer
In drupal 7 the best way to export drupal / modules(contributor) configurations is feature. Feature allows ability to export few configurations (rules by exemple) into files instead of custom modules. @see https://www.drupal.org/project/features

Good chance :)
> 1 votes

---
Tags: 7, rules
---


# Question
Title: How to get a form field to allow additional values?
I need to have a way to allow for multiple values to be used for a field.

For example,

Someone has school name(s), and the form description says, "Add your schools here."

I add a school, press a button for an additional, another text field appears, etc.

I know I have seen this before, but I cannot seem to find it anywhere. How do I do this?

I thought it might be this module(s):

https://www.drupal.org/project/field\_collection

https://www.drupal.org/project/webform\_addmore

How to add additional "items" on a webform in Drupal 7

But I'm not sure. I thought it was built into Drupal webforms.

# Answer
If you want to allow a field to get multiple values.you need to edit the field and allow the numbers of values to unlimited. Suppose you want to allow multiple images to upload in Article content type.

1)Go to Administration » Structure » Content types » Article » Manage fields 2)Edit the field and under field settings,choose the values to unlimited or number of values you want a user can upload. See the similar in screenshot url below. https://www.evernote.com/shard/s496/sh/15655bf1-104c-40ed-ab26-bc6da6ebe7a5/bd1bce151edec9956746845474f3ba95
> 2 votes

# Answer
There have been a number of attempts at this using the webform module, ex:

Webform Multiple https://www.drupal.org/project/wfm

but these are a little buggy and unstable at the moment, primarily because of the bespoke way that webform handles its data.

An alternative you should consider is switching to entityform:

https://www.drupal.org/project/entityform

which leverages the robust Entity API for handling data and creating fields. You will then have hundreds of Drupal field types to choose from, most of which could be made to 'add multiple' as you would for a normal content type.
> 1 votes

# Answer
The way we have done this is to replicate the fields, or even the fieldset, and then use Webform Conditional statements (this is now in core webform module, you don't need the extra module)

You then make a field that says 'add extra' and if they set it to 'yes' you make the next set of fields visible via the condition

Hope that helps
> 1 votes

# Answer
The Select (or other) module provides the functionality similar (or identical?) to what you are looking for. Here is an excerpt about it from its project page.

> Provides a new Forms API element which is a select/radios/checkboxes element that has an 'other' option. When 'other' is selected a textfield appears for the user to provide a custom value.

You could "start" from a few schools (school 1, school 2, school 3), and whenever somebody needs another one (not in the list yet), they just enter "school 4". Here is a sample about it (just replace "Option" by "school" to get the idea):
> 1 votes

---
Tags: 7, entities, webforms
---


title: Views: nodes grouped by taxonomy term

text:
# Question
Title: Views: nodes grouped by taxonomy term
I would like to show nodes grouped (aggregated?) by taxonomy term like this:

term 1

* node1
* node43
* node34

term 2

* node23

etc. but I am not seeing such grouping when I enable aggregation. I can get sg similar with table style and group by column but this only works for the current page, not if I have a paged view.

Any tips? What would be the steps to achieve this with aggregation?

Similar question but for D6

# Answer
> 1 votes
You may want to check out Views Tree module which provides a view style plugin for that. It couples two views by means of an argument, one view would be your term listing, the other - node listing. I have tried to achieve that by aggregation or grouping field, but to no avail - Views is apparently designed so that it can list only one kind of a bundle at a time.

Although, if you don't need to represent entire tree, you could try trying out field style, with taxonomy term field added, and then used as grouping field.

# Answer
> 2 votes
For future reference, I think this recipe is pretty awsome: http://www.drupalgardens.com/documentation/taxonomy/views

# Answer
> 0 votes
if you choose **Force using fields** under *display settings*, you are able to add fields and then group by them, still using rendered entity as display !

---
Tags: 7, taxonomy-terms, views, css-js-aggregation
---


title: how can I show the node create date

text:
# Question
Title: how can I show the node create date
I have used the `format_date()` in my template files to try and output the date created.

I followed this tutorial http://webwash.net/tutorials/handling-date-and-time-drupal-7

I created a date format 'd, j M y' and date type 'article' and called it through the code:

```
<?php print format_date($node->changed, 'article') ?>

```

however **the date that it shows is the date it was updated not the date it was created.**

How do I show the creation date of the node ?

# Answer
> 18 votes
There is a property on the node object called "created". This is what you are after and can be used in the exact same way you have used "changed".

```
<?php print format_date($node->created, 'article'); ?>

```

# Answer
> 2 votes
**First Steps**

The first step is to enable "Display author and date information" on your content type edit page at:

> /admin/structure/types/manage/\[your\_custom\_content\_type\]

...as shown below:

**Get the Data**

We can now go retrieve this data in the node.tpl.php file and alter the theming of the post date. Ideally this will be for a custom node template and not the main node.tpl.php file. In my case, I have a content type called blog and I only want the post date to look this way for blog posts. I take node.tpl.php (located in my theme folder) and copy and rename it to node--blog.tpl.php. Note the "double dashes", that's new in Drupal

**Find the Code to Replace**

Now looking in my new node--blog.tpl.php file, I see the PHP code I am after that I will then alter:

```
<?php if ($display_submitted): ?>
  <div class="submitted"><?php print $date; ?> -- <?php print $name; ?></div>
  <?php endif; ?>

```

I want to replace this with some custom PHP code essentially breaking the date up into parts, and getting rid of the author name (though you could easily add this back in and theme it).

**Code it**

Here is our new code:

```
<?php if ($submitted) { ?>

   <div class="date-in-parts">
       <span class="day"><?php  echo date("j", $node->created); ?></span>
       <span class="month"><?php echo date("M", $node->created); ?></span>
       <span class="year"><?php echo date("Y", $node->created); ?></span>
    </div><!--//date-in-parts -->

  <?php } ?>

```

---
Tags: 7, datetime
---


# Question
Title: How to add additional "items" on a webform in Drupal 7
I would like to provide the option of creating additional text fields under the same Label, if necessary. In the form of an "Add another" button. So when this button is pressed, an additional textfield will appear underneath. So, much like adding unlimited attachments to a node for example.

Is this possible using the Webform module?

# Answer
> 1 votes
The module Webform Add More does similar thing,

> Webform Add More enables selected fieldsets to be initially hidden and progressively shown with an Add more button, mimicking CCK multiple fields. The approach was proposed by Bartezz, and code originally implemented by span and kranklin . This module adds a checkbox setting to webform fieldset components to select which should have Add more functionality, as well as an advanced setting to override the button label per Webform.

# Answer
> 0 votes
The Select (or other) module provides the functionality similar (or identical?) to what you are looking for. Here is an excerpt about it from its project page.

> Provides a new Forms API element which is a select/radios/checkboxes element that has an 'other' option. When 'other' is selected a textfield appears for the user to provide a custom value.

Here is a sample about it:

---
Tags: webforms
---


title: Display the field filename in the node

text:
# Question
Title: Display the field filename in the node
I have a content type with an image field; the number of files is unlimited. I need to extract, filter using regex, and display the filename for each image in the particular node type using a view.

I tried with field--field-images--content-type.tpl.php and every other overwriting theme hook's trick and nothing even started working.

I think I miss something important on the way.

# Answer
Checkout this using `hook_preprocess_node()`

```
function MYTHEME_preprocess_node(&$vars) {
  $node = $vars['node'];

  if ($node->type == 'the_type' && $vars['view_mode'] == 'full') {
    $field_items = field_get_items('node', $node, 'field_name');

    if (!empty($field_items)) {
      $filenames = array();
      foreach ($field_items as $item) {
        $filenames[] = $item['filename'];
      }

      $vars['filenames'] = theme('item_list', array('items' => $filenames));
    }
  }
}

```
> 1 votes

# Answer
If you're using views to output the display of this node and want to modify it using a complex regex, your best option is to do this is to add your logic in a views template file. However, views doesn't have the filename of the file as a field option but you can load the managed file from the file id (fid) value, ex, following this example:

```
$file = file_load($node->field_YOUR_IMAGE_FIELD['und'][0]['fid']);

// Filename
print $file->filename;

// URI e.g. public://image.jpg
print $file->uri;

// URL e.g. /sites/default/files/image.jpg
print file_create_url($file->uri);

```
> 0 votes

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


# Question
Title: How can I clear the Menu cache after saving some configuration?
I'm in the process of creating my first D7 module, partly based on the tutorial found here. My module creates (among other things) a public page to show some content, and it also has a configuration page (in the Drupal admin) that allows the user to choose the path at which this page must be displayed (e.g. "mypage" or "content/mymodule" etc).

My problem is that saving this value through the configuration form is not enough: you also have to clear the Menu cache, otherwise the old path remains active, and the new one gives you a "page not found" error.

I need that to occur automatically every time this value is changed (or every time the form is submitted). I tried using `menu_rebuild()` in my validation function, but it's obviously not the right place, because it is triggered before the new data is saved, and so the menu is rebuilt with the obsolete data.

How should I proceed if I want the Menu cache to be automatically cleared **after** the data has been validated and saved?

Here's my implementation of the pages, via hook\_menu:

```
<?php

/**
 * Implements hook_menu().
 */
function mymodule_menu() {
  $items = array();

  // config page
  $items['admin/config/services/mymodule'] = array(
    'title' => 'mymodule',
    'description' => 'Configuration for the mymodule module',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_form'),
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
  );

  // public page
  $m_title = variable_get('mymodule_title', 'Mymodule');
  $m_title = $m_title ? $m_title : 'Mymodule';

  $m_path = variable_get('mymodule_path', 'mymodule');
  $m_path = $m_path ? $m_path : 'mymodule';

  $items[$m_path] = array(
      'title' => $m_title,
      'page callback' => '_mymodule_page',
      'access arguments' => array('access mymodule content'),
      'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

/**
 * Page callback: mymodule settings
 *
 * @see mymodule_menu()
 */
function mymodule_form($form, &$form_state) {
  $form['mymodule_title'] = array(
    '#type' => 'textfield',
    '#title' => t('Title displayed on the mymodule public page'),
    '#default_value' => variable_get('mymodule_title', 'Mymodule'),
    '#required' => TRUE,
  );
  $form['mymodule_path'] = array(
    '#type' => 'textfield',
    '#title' => t('Path for the mymodule public page'),
    '#default_value' => variable_get('mymodule_path', 'mymodule'),
    '#required' => TRUE,
  );
  $form['#submit'][] = 'mymodule_form_submit';

  return system_settings_form($form);
}

/**
 * Add a submit handler/function to the form.
 */
function mymodule_form_submit($form, &$form_state) {
  drupal_set_message(t('TEST: The form has been submitted.'));
  menu_rebuild();
}

/**
 * Implements validation from the Form API.
 *
 * @param $form
 *   A structured array containing the elements and properties of the form.
 * @param $form_state
 *   An array that stores information about the form's current state
 *   during processing.
 */
function mymodule_form_validate($form, &$form_state) {
  // page path validation
  $m_path = $form_state['values']['mymodule_path'];
  $m_path_db = variable_get('mymodule_path', '');
  if ($m_path_db != $m_path) {

    if (drupal_lookup_path('source', $m_path) || menu_get_item($m_path)) {
      form_set_error('mymodule_path', t('This path is already used.'));
    } else {

      // attempting to validate path value
      // see: http://drupal.stackexchange.com/questions/167923
      $m_path_parts = explode('/', $m_path);
      $has_invalid_chars = false;
      foreach ($m_path_parts as $key => $part) {
        if (urlencode($part) != $part) {
          $has_invalid_chars = true;
        }
      }
      if ($has_invalid_chars) {
        form_set_error('mymodule_path', t('This path contains invalid characters.'));
      }
    }
  }
}

?>

```

**Edit**: more code provided.

# Answer
This is to do with the order of execution.

`mymodule_form_submit` is being called earlier than `system_settings_form_submit` because you're adding your own submit handler into the form array before calling `system_settings_form` which will add it's own submit handler (system\_settings\_form\_submit) after your submit handler.

Essentially, your submit handler does a menu rebuild with the old variables, and then the new variables get saved to the database.

There's couple ways you can fix it as far as I know. These aren't tested.

First method is using a variable in your submit handler instead of directly rebuilding the menu:

```
/**
 * Add a submit handler/function to the form.
 */
function mymodule_form_submit($form, &$form_state) {
  drupal_set_message(t('TEST: The form has been submitted.'));
  // Set a variable to let menu_execute_active_handler() know that menu rebuild is required
  variable_set('menu_rebuild_needed', TRUE);
}

```

Or alternatively, you can add your own submit handler after `system_settings_form` has done its thing:

```
/**
 * Page callback: mymodule settings
 *
 * @see mymodule_menu()
 */
function mymodule_form($form, &$form_state) {
  $form['mymodule_title'] = array(
    '#type' => 'textfield',
    '#title' => t('Title displayed on the mymodule public page'),
    '#default_value' => variable_get('mymodule_title', 'Mymodule'),
    '#required' => TRUE,
  );
  $form['mymodule_path'] = array(
    '#type' => 'textfield',
    '#title' => t('Path for the mymodule public page'),
    '#default_value' => variable_get('mymodule_path', 'mymodule'),
    '#required' => TRUE,
  );

  $form = system_settings_form($form);
  // Add custom submit handler after system_settings_form_submit
  $form['#submit'][] = 'mymodule_form_submit';

  return $form;
}

```

Hope this helps.
> 1 votes

# Answer
Your form code would be helpful to see here to determine if you are using a system\_settings\_form() function (which seems likely since you are creating a module configuration form) or just a simple form. Regardless, the answer for both is to add a submit\_handler to your form.

Basic Form with Submit Handler: https://www.drupal.org/node/717740

If you are not using system\_settings\_form, than you can add your post-submit actions to a function named after your form definition function, or

```
/**
 * Add a submit handler/function to the form.
 */
function my_form_submit($form, &$form_state) {
  <YOUR menu_rebuild STUFF HERE>
}

```

and Form API will automatically find it. If you are using system\_settings\_form() for your admin form, than you can add your submit handler by adding this before calling system\_settings\_form()

```
$form['#submit'][] = 'my_form_submit';

```
> 1 votes

# Answer
**Drupal 7**

for Drush using

```
drush eval 'menu_rebuild();'

```

**memcached**

If you are using memcached, you have to restart it.

```
On Linux: /etc/init.d/memcached restart

On OS X: killall memcached

```
> 0 votes

---
Tags: 7, caching
---


title: Drupal Join Query with entityCondition

text:
# Question
Title: Drupal Join Query with entityCondition
I have two content type A and B in which B content type node is reference in A content type node. In B content type node there is status field. I want to fetch the A content type node in which the status of B content type node is something.

Can you please guide me how can I use this?

Thanks

# Answer
> 0 votes
This is the best solution for you ==\> https://www.drupal.org/node/1343708

EFQ an beautifull tools for manipulate the entities in drupal.

Do not hesitate if you need precision but this doc is verry good.

In the Entity Reference case

The column name for an entity reference field is target\_id, so your code should be:

```
$query = new EntityFieldQuery();

$query
  ->entityCondition('entity_type', 'node', '=')
  ->propertyCondition('type', 'custom_node_type', '=')
  ->fieldCondition('field_reference_name', 'target_id', $id, '=');

$entities = $query->execute();

```

For follow the relation of your entities you need to reference the A into B or B into A with a reference field. When you use EFQ to search the relation in node A with B you need to use fieldCondition in this reference field in my example is field\_reference\_name. If you list the content B (ids) into an array and you user this

```
$query = new EntityFieldQuery();

$query
  ->entityCondition('entity_type', 'node', '=')
  ->propertyCondition('type', 'a', '=')

$entities_a = $query->execute();

```

For search the relation A to B into A you need to use this :

```
$query = new EntityFieldQuery();

$query
  ->entityCondition('entity_type', 'node', '=')
  ->propertyCondition('type', 'b', '=')
  ->fieldCondition('field_reference', 'target_id', $entities_a, 'IN');

$entities_b_refered_into_a = $query->execute();

```

Good chance.

---
Tags: hooks
---


# Question
Title: In-place editor buttons in footer missing
I installed the Panels in-place editor which, in principle, should allow me to edit page layouts on the front-end.

But the two big buttons "Customize this Page” and “Change Layout” which should show up at the bottom of the page in the footer, are simply missing; I have a blank footer bar. I have already set the default renderer to IPE as well as given appropriate permissions. Any ideas on how to fix this - get the IPE buttons?? There are no missing dependencies AFAIK, but the evidence suggests I am probably wrong..

# Answer
> 0 votes
Did you enable Node template in page manager? -\> /admin/structure/pages That should make the toolbar appear.

---
Tags: panels, theming
---


title: Drupal Multi Site Folder structure

text:
# Question
Title: Drupal Multi Site Folder structure
I have a simple question.

I am trying to create a folder inside the Drupal installation that will not be shared to all the multi-sites.

For example:

> www.mydomain.com/xxx
>
> www.anotherdomain.com/xxx

I need this two folders of *xxx* should go to different path.

How can I achieve that?

I tried to create a new folder in Drupal root folder, but like this all the domains familiar with the same contents.

Thanks for the help.

# Answer
To extend @Pierre.Vriens answer , you could then add a rewrite rule to make the urls a bit nicer

assumptions

1. you've got public files set up
2. you've got a url 'normalisation' (either symlinks in files directory or 301s) `RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /sites/%{HTTP_HOST}/files/$1 [L]`

in your host will take

```
http://www.example.com/filename.pdf

```

and rewrite it to

```
http://www.example.com/sites/www.example.com/files/filename.pdf

```

what do i mean by url normalisation ? well, if you can get example.com - then you'll get a 404 - as the folder in the sites directory is www.example.com

an easy solution is to use symlinks in the sites directory, or to use 301 redirects

to use symlinks, assume you have

```
sites/www.example.com

```

you could then create a symlink to it as follows

```
ln -s www.example.com example.com

```

this would create a symbolic link from

```
sites/example.com

```

to the www.example.com folder. this means that both www.example.com, and example.com would be found when the rewrite rule runs
> 1 votes

# Answer
Do not create such folder in the Drupal root folder. But instead create an `xxx` subfolder in both of these subdirs:

* `sites/mydomain` (assuming `mydomain` is what maps to your `www.mydomain.com`).
* `sites/anotherdomain` (assuming `anotherdomain` is what maps to your `www.anotherdomain.com`).

By doing so, the 2 folders `sites/mydomain/xxx` and `sites/anotherdomain/xxx` for sure will not be shared between those 2 sites within a multi-site construction.
> 0 votes

---
Tags: multi-sites
---


# Question
Title: register.json does not login the user or return the user's session/token/password
I have tried far too many variations to list here, but the basic point is I cannot get the user logged in immediately after registration via Services. I have tried a fresh Drupal 7.33 install with only Services 7.x.3.11 enabled and the default resource settings provided by drupalgap 7.x.1.9

When I register using the Drupal interface, the user is created, the session opened, and I land on my profile page logged in.

vs.

When I call the Services endpoint `/services/user/register.json`, Drupal creates the account but the session does not persist. See my screenshots below.

**How can I either A. get the session to persist for subsequent Service resource calls OR B. hook to add the user's or auto-generated password back into the json response so I can programmatically resubmit the /login.json form client-side (which does persist) ?**

This question how could the global $user be different between the Drupal interface and Services module? describes my same problem using LoginToboggan.

In my screenshot you'll see a debug line called "login debug". It comes from line 333 of "/sites/all/modules/logintoboggan/logintoboggan.module" where I've tried all of this to no avail...

```
function logintoboggan_process_login($account, &$edit, $redirect = array()){
  global $user;

  $user = user_load($account->uid);

//watchdog('login debug', json_encode($account));
watchdog('login debug', json_encode($edit));

  //user_login_submit(array(), array('uid' => $account->uid));
  user_login_finalize($edit);

//  $user = user_load($account->uid);
//  $user->token = drupal_get_token('services'); // WE HAVE A TOKEN ALTHOUGH I DOUBT THIS WOULD WORK IN TERMS OF SESSION PERSISTANCE
//  user_login_finalize($edit);
//  module_invoke_all('hook_user_login');
//  module_invoke_all('tripchi_user_login');
//  module_invoke_all('logintoboggan_user_login');

```

# Answer
Not sure if you need an answer at this point (or if this is even one), but it looks like you have "Require e-mail verification when a visitor creates an account" turned on?

In your image, in the second window (where you see the message from drupal\_set\_message()), it says that an email was sent and you will need to follow instructions to gain full message.

To turn this off, navigate to **/admin/config/people/accounts** and uncheck Require e-mail verification when a visitor creates an account.

If you look at the user table in the database, the status column should show a 1 for enabled, 0 for disabled (meaning he hasn't clicked on the link in the email).

Hope it helps!
> 1 votes

# Answer
It's working fine for me you can use following code

```
global $user;
$username=$data['email'];
$password=$data['pass'];
if ($user->uid) {
    // user is already logged in
    return services_error(t('Already logged in as @user.', array('@user' => $user->name)), 406);
}

// Check if account is active.
if (user_is_blocked($username)) {
    return services_error(t('The username %name has not been activated or is blocked.', array('%name' => $username)), 403);
}

// Emulate drupal native flood control: check for flood condition.
$flood_state = array();
if (variable_get('services_flood_control_enabled', TRUE)) {
    $flood_state = _user_resource_flood_control_precheck($username);
}

// Only authenticate if a flood condition was not detected.
if (empty($flood_state['flood_control_triggered'])) {
    $uid = user_authenticate($username, $password);
}
else {
    $uid = FALSE;
}

// Emulate drupal native flood control: register flood event, and throw error
// if a flood condition was previously detected
if (variable_get('services_flood_control_enabled', TRUE)) {
    $flood_state['uid'] = $uid;
    _user_resource_flood_control_postcheck($flood_state);
}

if ($uid) {
    $user = user_load($uid);
    if ($user->uid) {
        user_login_finalize();

        $return = new stdClass();
        $return->sessid = session_id();
        $return->session_name = session_name();
        $return->token = drupal_get_token('services');
        $account = clone $user;
        services_remove_user_data($account);
        $return->user = $account;

        return $return;
    }
}
watchdog('user', 'Invalid login attempt for %username.', array('%username' => $username));
return services_error(t('Wrong username or password.'), 401);

```

pass user email id and password then it will returns all the required value like **session id ,session name ,token , user uid**
> 0 votes

---
Tags: 7, users, services, sessions, javascript
---


# Question
Title: New Drupal installation not working beyond front page (not accessing database)
I just installed a new drupal 7.39 using drush. From the browser, I can only goes as far as the front page(welcome page) and no further. I cannot log-in, suggesting that drupal is not accessing the database. The installation went smoothly. Below is my drush commands. Anything wrong with it?

```
$ drush site-install standard --db-url="mysql://root@localhost/mydrupal1" --site-name=MyDrupal1 --account-name=my_username --account-pass=my_password

```

# Answer
I figured out the solution: I just realized that the `rewrite_module` on WAMP Server was not enabled(My WAMP Server too is a new install. And Drupal uses this module via `.htaccess` for url resolution), so I simply enabled it. Problem solved.

My thinking is that with `rewrite_module` disabled(default), the drupal site couldn't move beyond front page (which is default page) because it couldn't resolve any further urls requested, including urls that access the database.

Thanks for your attention.
> 0 votes

# Answer
Check if you get the same problem using another browser. If with another browser it works, then it might be a cookie problem, The remedy in that case is to delete the cookie in the browser where you have the problem, and try again. Otherwise read on for other typical reasons (options) ...

# Option 1 - RewriteRule and RewriteBase

Check if you can use an URL containing `?q=user` or `?q=admin`. Refer to my answer to the question "7.26 /admin, /user not found on Localhost" (which is about `RewriteRule`) for more details on that.

In that answer there is a link to the question about "drupal /?q=user is working but /user not working", for which the accepted answer of that question provides more details about tuning `RewriteBase` in your .htaccess.

# Option 2 - Admin option 'Clean URLs'

I you can use the `?q=admin`URL, then try to navigate to `/index.php?q=admin/config/search/clean-urls` to check the current status of **clean urls** (if it is enabled or disabled). Make sure "clean urls" is enabled.

Refer to "Clean URL leads to duplicate URL after migration to another hosting" for more details on that.

# Option 3 - base\_url

Make sure the value of "base\_url" is set correctly (in your settings.php).

# Option 4 - .htaccess file

Verify if the .htaccess file is present in the directory where Drupal resides (and/or that it is not incomplete or corrupt). If it is missing, then upload it. If needed copy it again from the "Drupal" archive file (.zip or .tar) from Drupal.org again, and just use that new .htaccess file.
> 4 votes

# Answer
In addition to the suggestions made by Pierre, you should also check the value of $cookie\_domain in your settings.php file. If this is set incorrectly (e.g. to mylivesitedomain.com when you are accessing your site via localhost), then you will be unable to log in. Drupal will log you in correctly (presuming you entered the correct username and password), but the login cookie will not be sent back by your browser, so the login will not "stick".

Also, to reinforce what Pierre said about $base\_url -- if this is not set correctly, the symptoms will be very similar. For example, if you log in to your site via localhost, it is common for your local web server to report 127.0.0.1 instead. Again, your login cookie will not be attached to the right domain, and you will not be logged in. In this instance, setting $base\_url to localhost is the right answer. I like to do this:

`$base_url = str_replace('127.0.0.1', 'localhost', $base_url);`

That way, the port in $base\_url will match whatever I happen to use when running the site via `drush runserver`.
> 2 votes

# Answer
My answer may sound too simple, but I had the similar problem after fresh install. What helped was deleting all cookies in Firefox. After that I could login.
> 1 votes

---
Tags: 7, drush, installation
---


# Question
Title: How do I remove "active" css class from breadcrumbs?
I am trying to include Structured Data in my breadcrumbs. The google validator throws an error on my final breadcrumb. When I remove class="active" from the code in the code validator window the code passes without error.

I used the theme\_breadcrumb hook to add the Structured Data Markup to the breadcrumbs, but there is no mention of the css active class.

```
function MYTHEME_breadcrumb($variables) {
    $breadcrumb = $variables['breadcrumb'];
    $breadcrumb = substr_replace($breadcrumb, 'http://mywebsiteexample.com/', 9, 1);
    $rich_snippet = 'rel="v:url" property="v:title" ';
    $breadcrumb = substr_replace($breadcrumb, $rich_snippet, 3, 0);
    if (!empty($breadcrumb)) {
        $breadcrumb[] = '<a rel="v:url" property="v:title" href="'.current_path().'" >'.drupal_get_title().'</a>';
        //Added this line  to avoid displaying node title twice
        unset($breadcrumb[count($breadcrumb) - 1]);
        $output = '<span class="element-invisible">' . t('You are here') . '</span>';
        $output .= '<div class="breadcrumb" xmlns:v="http://rdf.data-vocabulary.org/#"><span typeof="v:Breadcrumb">' . implode(' » </span><span typeof="v:Breadcrumb">', $breadcrumb) . '</span></div>';
        return $output;
      }
    }

```

Is there another hook I can use to remove the active class exclusively for breadcrumbs? Ideally I would like to do it without inserting Javascript into any templates.

# Answer
> 0 votes
The active class is added by the l() function:

```
  // Append active class.
  if (($path == $_GET ['q'] || ($path == '<front>' && drupal_is_front_page())) &&
    (empty($options ['language']) || $options ['language']->language == $language_url->language)) {
    $options ['attributes']['class'][] = 'active';
  }

```

It may be difficult to override this behavior. In your code replacing theme\_breadcrumb it seems like you've hit upon this problem since you are not using the `l` function. You could loop over the values in `$variables['breadcrumb']` and run a `str_replace` to get rid of the active class.

# Answer
> 0 votes
Why not use jQuery .removeclass() on document load so that it removes 'active' from breadcrumb for each page.

More information here.

jQuery remove class

---
Tags: hooks, breadcrumbs, routes, rdf, theming
---


title: Permission page broken

text:
# Question
Title: Permission page broken
All other pages are being loaded fine but when I go to permissions page it comes like this. What may be the reason for this ? Please help.

# Answer
> 3 votes
I had exactly the same problem few days ago. Do you have the **devel module** install?

For me it was the problem, i can't explain why but when i desintalled it, all worked fine.

So maybe, try to desactivate and unistall it and maybe your page permission will work again.

PS: *i just re-install the devel module to make a test and i have exatly the same permission page than you. For me it's the devel module the problem. (I'm new in Drupal so i had certainly make a mistake somewhere)*

# Answer
> 0 votes
This could probably be a PHP Memory Limit issue. Is this only happening on your local / dev or also on your remote server?

# Answer
> 0 votes
I have the exact problem noted above, but after checking my modules, I do not have devel installed. Are there any other solutions to this issue out there?

# Answer
> -2 votes
May be the permission listing makes the memory problem.You have to update the permission listing page to a simple one.

Try the Filter permissions module

---
Tags: 7, theming
---


# Question
Title: How to know if a specific role can access a page?
I have Drupal set up and some module enabled. Specifically I have the translation\_overview module installed.

Now I want to give a specific role access to those pages so they can see what needs to be translated. So I gave them access to 'View translation overview assignments' but when I ask a person with this role if she can see it, she tells me she cannot.

I am an administrator, so I can obviously see everything in there. But how can I see what other roles see?

# Answer
> 3 votes
You can make use of Masquerade module to switch users who belongs to different roles. This will help you see what other role users see.

# Answer
> 2 votes
In general I think people test permissions by going to the permissions page and tweaking it until it works. That's an OK process, but can have unintended consequences (you may grant more or less than you wanted).

So, first, I suggest setting up test users that you can use to log in to your site with various different combinations of permissions. That's an effective way to test out your changes.

Second, set up a test site for this kind of experiment. Doing that kind of change on a test site will help you be more confident when you tell a user that you've fixed their permissions.

Often the README.txt or project page or documentation (if it exists) will tell you what permissions to use.

My final suggestion is that the one way to be really confident that a user can access a page is to look at the code. The `hook_menu` of translation\_overview.module and the `hook_permission` together shows that users with "View translation overview assigments" should be able to see the path at `admin/content/translation-overview-assignments`. However, there is also a permission for `'manage ' . check_plain($lang_code) . ' translation overview priorities'` which is relevant. Note that there is a typo in the permission where it is missing the letter "n" in assinments.

It's possible that there is a bug in the module's permissions enforcement. The module's bug queue has a few issues that could be related.

Also, it's possible that the menu is broken and the person **can** access the page, but the link isn't presented. I would try visiting the page directly rather than using a link to see if access is the problem or navigation.

# Answer
> 2 votes
Unfortunately, permissions are a complex topic and contrib documentation (where it exists) will rarely be able to fully address all situations.

When documentation doesn't provide the info you need you have 2 options:

1. Play around with it. Create a test account with the same role(s) as the user you're trying to solve the problem for and play with granting various permissions. Unfortunately it's not always obvious what permissions are going to have which effects as there are some permissions (like "administer content") that have far-reaching consequences.
2. Look at the code. For page-based permissions you can typically look at the implementation of hook\_menu and look at two array elements in particular: `access callback` and `access arguments`. Looking at translation\_overview\_menu I see several callbacks defined: To access admin/content/translation-overview-manage you can look at the `access callback` function and see that your user needs the `manage x translation overview priorities` permission, where x is any language on your site. For all of the other pages provided by the module you will notice that no `access callback` is defined, so they inherit the `user_access` value for this from their parents. So the string set in `access arguments` is passed directly to the `user_access()` function meaning that your user needs the `translation overview assigments` permission to see any of those pages.

If you want to learn more about how access callbacks or arguments work, read the hook\_menu documentation.

This is not specific to translation\_overview as it seems like a pretty simple module, but for future reference it's also worth noting that not all permissions are enforced in the menu system. Sometimes (often) code that is rendering the page itself will make calls to user\_access() or node\_access() or any of the other access-related functions to determine if the user has access to something and will change what's shown on the page as a result of those calls. In that case, if you don't feel too comfortable with code, you will almost certainly be reduced to using the "play around with it" method to determine the impact of various permissions.

# Answer
> 1 votes
Please create a test user with the permissions.Login with the test user account and check above case so that you get to know what other users can see.

# Answer
> 1 votes
Go to `admin/people/permissions` and set the permissions `Translate content` , `Administer content translations` and `View translation overview assigments` and you must enable too this permissions for the content type:

```
My content type: Create new content
My content type: Edit any content

```

---
Tags: users, i18n-l10n
---


title: what does {node} node mean

text:
# Question
Title: what does {node} node mean
**Background**

I'm trying to understand the SQL queries that Drupal generates when I select different content to be displayed on my site so I can write my own php filters.

**Issue**

I see this in the query every time

```
SELECT...
FROM
{node} node
WHERE...

```

**Question**

What does the `{node}` mean does it refer to the content type I'm using?

# Answer
> 3 votes
It's the abstract way of referring to the node table in the database. This notation is converted by Drupal to the real name of the table right before the query is executed (in most cases, for most configurations, {node} will simply become `node` at execution time). Using this notation allows an instance of Drupal to use table prefixes without the code generating the queries having to know anything about those details.

The table name has the appearance of being repeated (`{node} node`) so that the table name `{node}` gets mapped to an alias `node` that can be used elsewhere in the query. Consider if you have configured your site to use a table prefix of "dev\_" then `SELECT node.status FROM {node} node...` would get translated to `SELECT node.status FROM dev_node node...`, thus allowing your node.status field to refer to the correct table without the code generating the query having to know anything about the fact that there's a table prefix configured for the site. For this simple example it's silly because you could just write {node}.status, but for more complex examples, particularly with multiple joins it can be useful to set up the alias.

---
Tags: nodes, database
---