# Question
Title: explicit "switch to mobile theme" link with Theme Key
I'm using Theme Key https://www.drupal.org/project/themekey to switch automatically between themes dependent on browser and/or OS id. Now I would like to allow the user to explicitly switch to or from to one or the other theme by clicking a link too. The`Persistant URL` https://www.drupal.org/project/purl module might be helpful for this but how exactly can I go about implementing this?

**EDIT 1**

I followed **Answer 1**, added `drupal_add_library('system', 'jquery.cookie');` into the already existing `function marinelli_preprocess_page(&$vars)` in my `template.php`.

I setup two `ThemeKey` rules like:

```
system:cookie = "theme=marinelli" THEME [Marinelli]

```

and

```
system:cookie = "theme=skeleton" THEME [Skeleton]

```

and added following html to my page:

```
<p><a href="#" onclick="$.cookie('theme', 'marinelli')">Switch to Marinelli</a> <a href="#" onclick="$.cookie('theme', 'skeleton')">Switch to Skeleton</a></p>

```

But clicking the links, doesn't do anything, seems like I might be missing something or it might not quite work this way because `href="#"` doesn't actually reload the page if that was the actual idea...?

# Answer
> 1 votes
To make it to work with cache you can use the Mobile Cache module, at least as inspiration to make your own module using the library Mobile Detect.

https://www.drupal.org/sandbox/acy76/1962696

But you need to modify this line in the module and must look like this

```
_mobile_cache_add_query_string('device=' . $data['device'] . '&theme=' . $_COOKIE['theme']);

```

Notice that the idea is add the theme name to the cache

I'm using Authcache and Filecache

Thanks @PatrickRyan

# Answer
> 1 votes
One way would be to nest each theme switching rule inside another rule using

`system:cookie` `=` `theme=theme1`

```
     Theme switching rule here

```

`system:cookie` `=` `theme=theme2`

```
     Another theme switching rule here

```

You will need to set up your theme switching links to create a cookie using your method of choice, PHP or jquery.cookie

An example using jquery.cookie could be something like:

**template.php**:

```
function THEMENAME_preprocess_page(&$vars) {
  drupal_add_library('system', 'jquery.cookie');
}

```

**Your theme switching links**:

```
<a href="#" onclick="jQuery.cookie('theme', 'theme1'); location.reload(); return false;">Switch to Theme1</a>
<a href="#" onclick="jQuery.cookie('theme', 'theme2'); location.reload(); return false;">Switch to Theme2</a>

```

Keep in mind that this is not page caching friendly. If you want this to work for anonymous users, you will need to disable page caching.

---
Tags: theming, uri, navigation, theme-negotiation
---


title: Process Array contents

text:
# Question
Title: Process Array contents
I've done a database query which returns the results in the following array:

```
Array ( [0] => stdClass Object ( [field_latitude_value] => 25.2000000000 ) [1] => stdClass Object ( [field_latitude_value] => 51.9456801568 ) [2] => stdClass Object ( [field_latitude_value] => 51.9471747475 ) [3] => stdClass Object ( [field_latitude_value] => 51.9471218425 ) )

```

How do I process this information so I get just the values instead of the added keys? I.e a list of said values.

I'm currently using the following code, which gives me a recoverable fatal error:

```
<?php

$query = db_query('SELECT field_latitude_value FROM {field_data_field_latitude}')->fetchAll();

print_r($query);
foreach($query as $value){
    echo $value;
};?>

```

# Answer
Instead of fetchAll(), try fetchCol(), like this:

`$latitude_values = db_query("SELECT field_latitude_value FROM {field_data_field_latitude}")->fetchCol();`
> 1 votes

---
Tags: 7, database
---


# Question
Title: how to overide prvatemsg url 'messages' to 'something'?
function \_MY\_MODULE\_custom\_submit($form, &$form\_state) { $form\_state\['redirect'\] = url('thank-you', array('absolute' =\> true)); }

# Answer
> 0 votes
If what you want is to do a redirect to a thank you page after you handle your form posted data then just add to your function a redirect via a call drupal\_goto().

Something like this:

```
function _MY_MODULE_custom_submit($form, &$form_state) {
  // process your form stuff...
  drupal_goto('thank-you');  // redirect to page 'thank-you' providing this is one of your drupal pages
}

```

---
Tags: uri, redirection, privatemsg
---


# Question
Title: Some of node links of content types are corrupted
There are about `5000` nodes in my website of different content types. After a while (updating the Drupal to `7.34` and configuring the Server by server administrator) some of node links are corrupted and they are redirected to the front page. They are not too many but I don't know why some links that were working, are not working now. As an example the link `/node/286` is redirected to the front page.

Is there any problem with the update that causes such thing?

The host server was victim of an attack and a few guest websites on it were hacked. So I guess (not sure!) the administrator may blocked some PHP functions, could this be the reason for such misbehavior of the links ? If it is right then why only a few of them are broken?

# Answer
I've hit redirecting-to-front-page nodes in the past when I've stripped out use of the PHP filter input format. Turns out there was conditional logic that sometimes printed javascript redirect code.

Does the pages in question use the PHP filter format? If the admin blocked **eval()** perhaps it could stop execution of PHP and just render redirect code?

You can check **disable\_functions** value in /admin/reports/status/php to confirm your suspicion about disabled functions.
> 0 votes

---
Tags: nodes, uri, navigation
---


# Question
Title: Need to automatically rotate the result of a view once a week (Sunday night)
The view (block) displays content (field collection items) on my home page. I had it set so the client could choose what to display by checking a boolean field. The view works fine, but now the client has decided they would like the content to be chosen randomly and for it to be automated (to change on a weekly basis). I need every user to see the same content displayed and I need the same content to stay up a whole week.

What is the best way to accomplish this? I've tried setting the display to show only 1 and sort on random with the view cache set to 6 days/6 days. I'm just not sure how reliable this will be.

# Answer
Maybe you could use rules module with rules scheduler to toggle the "Promoted to front page" flag on content of that type? So every Sunday a rule would fire that demotes the current one, promotes the next one, and schedules the next few of these cycles? You should be able to get something neat working with this approach.
> 2 votes

# Answer
The problem with that solution is it relies on the view's cache lifetime which might not sync up to Sunday (e.g. a manual cache clear it will reset the lifetime clock on the view cache and expire it 6 days from the manual cache clear).

A better solution would rely on `hook_cron()` and do the following:

* Trigger every Sunday
* Set all node fields to false
* Randomly select a node and update its field to true.

This could be accomplished with a custom module hook\_cron or, I think, the Elysia Cron module.
> 2 votes

---
Tags: views, rules, entities, flags
---


# Question
Title: Make a Search view have the same options as a Content view
I have created a *Content view* that works perfectly, believing I would later add facets to it once Solr is up and running.

Now that Solr works together with Search API, I realize that to use facets I need my view to be a *Search view*.

Unfortunately now with the view being a *Search view* I can no longer use:
**Contextual filter** \- Content: Has taxonomy term ID (with depth)
**Relationship** \- Flags: my flag (by any user)
**Field** \- Flags: Flag link
**Field** \- Computed fields: (values are all 0)
**Field** \- Content: Path (Found a work around for this one)

Is there a way to make my *Search view* behave like a *Content view* and therefore have access to all needed functionalities?
Or may be could I use facets on my *Content view*? None of my tests worked though.

# Answer
> 0 votes
H,

This is something I'm still searching for an authoritative solution to/answer on.

This is apparently known issue with Flag and Views, with most people taking programmatic approaches to solve their particular problem.

There's a patch to that should address at least some of your problems here. https://www.drupal.org/node/1362298. This seems to be the closest anyone is to a solution at the moment.

---
Tags: 7, views, panels, search
---


# Question
Title: How to remain logged in when switching languages via domain?
I am using Drupal 7 to configure a new single Drupal site that uses two languages (English and French), using Locale with the "Language domain" setting enabled. This site requires both the display and the admin language to be switchable, and almost have it working! I have just one last issue.

When I visit "en.dev.example.com" I can log in everything seems to be working great; when I switch to "fr.dev.example.com" while logged in, I am no longer logged in. I can actually have two different users logged in at once, using the same browser, on each domain.

This is not desired! This Drupal site is not a multi-site, and I don't want it to behave like that. When someone logs in, I need them to stay logged in also when they switch languages. This is because many users will be totally bilingual and need to see the site content in both the languages. This is important, since the content is membership based.

I started out setting the "Path prefix language code" in my language settings which was working well; you could switch languages without problems and stay logged in while doing so. Perfect! Except…

I had to change the method of handling languages to "Language domain" because the URLs created by some modules (namely the Advanced Forum module, but I am sure it will come up in other places) were not respecting the path language prefixes, and giving many 404s. I really need to use the subdomain method!

I created two subdomains via my hosting account, one is "en.dev.example.com" and the other is "fr.dev.example.com" (both using subdomains to give each language equal significance). I changed the "Language domain" for each language, and am now able to see both language versions by using the subdomains I created, as expected.

What can I do to make sure users stay logged in when they switch language after starting their session, while using the "Language domain" option?

I cannot locate any info or forum posts for Drupal 7 on this particular issue... Do I need to make some changes to my settings.php file? I also couldn't find D7 documentation on setting this up (only for path prefixes), so it's possible that I have missed a step.

I have been at the languages settings for a few days now, and I have made real progress, but I feel totally stuck at this point, the last problem! I would absolutely love some advice at this point.

# Answer
Try adding this to settings.php

```
$cookie_domain = '.dev.example.com';

```
> 1 votes

# Answer
Clive's solution is normally all you need to do. I had a similar problem on a multilingual site, and this settings.php change resolved this.

Besides what MPD suggested, you can simply wait for the sessions table to clear (generally is set to about 6 hours by default), and also clear the caches and history from your Web browser.

Even if the fix works, if your browser is relying on cached data, you may not see the change.
> 0 votes

---
Tags: i18n-l10n
---


# Question
Title: How to display the survey results created with the Webform module?
Does anybody know how to display the survey results created with the Webform module?

I have created a survey using the grid field and it works great. I want to be able to display the accumulated results (using my CSS styling) on the same page the survey question appears. Is there a way to do this?

# Answer
If you want to create **charts** from the survey results of the Webform module, there are 2 alternatives to pick from:

* **Webform Charts** (used in about 400 sites), to display Webform results in a graphical manner using a charting library.
* **Webform Chart** (used in about 220 sites), which integrates with the "Analysis" tab of a Webform (created with the Webform module) to provide charts for each individual component's analytical data.

The Drupal 7 version of both modules, requires the Charts module (dependency).
> 1 votes

---
Tags: webforms
---


title: How To Print Out a Webform Results?

text:
# Question
Title: How To Print Out a Webform Results?
Using webform I have created a questionnaire and now I need to be able to print the results on paper. My first solution was going to the result page print out from the browser. Unfortunately, this does not look good on a print when print out.

Here is how it looks like browser.

And I think this looks very decent and acceptable, but when I print this out it will looks like this.

The print out cut most of my webform results and without all my results this is useless for me.

My second solution was to try it out the Webform2PDF module. However, every time I try to used it does not work for me.

I have try to print out the e-mail I get from webforms but the results are on plain text and the results from the e-mail does not looks very professional. These results are have to be very presentable on paper.

So my question is what is the good approach of printing out the webform results.

# Answer
> 0 votes
I was able to have the Webform2PDF working (I was using the wrong version) but the output of the pdf did not looks very appealing to me. So I decide to use the print module because it allows me to print out my webform result the same way it looks on my administration page.

# Answer
> 1 votes
You should be able to expose webforms results/submissions activating a complex (but effective) combination of Webform Mysql Views module, Data and Schema modules ... as stated here for instance: https://www.drupal.org/node/1658784. It works .. and you can just print your views results.

However, next time if I were you, would have assessed possibile alternatives to webforms. Have you ever heard about Entity Forms Module? It rocks, because it overcomes the above mentioned limitations, and also for other very good reasons, as mentioned here under:

# Answer
> 0 votes
Another approach might be to create **charts** from the survey results of the Webform module, there are 2 alternatives to pick from:

* **Webform Charts** (used in about 400 sites), to display Webform results in a graphical manner using a charting library.
* **Webform Chart** (used in about 220 sites), which integrates with the "Analysis" tab of a Webform (created with the Webform module) to provide charts for each individual component's analytical data.

The Drupal 7 version of both modules, requires the Charts module (dependency).

---
Tags: webforms
---


# Question
Title: What can I use for something like Google web analytics for a Drupal website?
I'm looking for my site to use web analytics so I will be able to track inside my backend on whats going on inside my web.

I am looking for something like Google Analytics but just on Drupal.

# Answer
Drupal have the Google Analytics too

> Adds the Google Analytics web statistics tracking system to your website.

also install the Google Analytics Reports module to track within the site itself.

> Google Analytics Reports provides graphical reporting of your site's tracking data. Graphical reports include a dashboard widget for admins, a small path-based report in blocks, and a full path-based report.
> 4 votes

# Answer
For info related to visitors of a website (registered users is a subset of them), consider the visitors module as a possible alternative. Refer to its community docu for some more details.

It also support charting of those data (a typical related requirement ...).

**Be aware**: I'm the new maintainer of it.
> 1 votes

---
Tags: google-analytics
---


# Question
Title: How to count the number of anonymous users that are currently using the site?
I want to either use a module or write a module which allows me to count the number of Anonymous Users that are currently using the site.

What is the best method for this to be achieved? I looked at the statistics module but this does not enable me to count the data. I discovered views is capable of this with this setting, "Content statistics: Most recent views". But, there was no option for anonymous data.

# Answer
The admin\_menu module does this, and provides this function:

```
/**
 * Counts how many users are active on the site.
 *
 * Counts how many users have sessions which have been active since the
 * specified time. Can count either anonymous sessions or authenticated
 * sessions.
 *
 * @param $timestamp
 *   A Unix timestamp. Users who have been active since this time will be
 *   counted. The default is 0, which counts all existing sessions.
 * @param $anonymous
 *   TRUE counts only anonymous users. FALSE counts only authenticated users.
 *
 * @return
 *   The number of users with sessions.
 *
 * @todo There are mostly no anonymous sessions anymore. Split this into a
 *   separate module providing proper user statistics.
 */
function admin_menu_session_count($timestamp = 0, $anonymous = TRUE) {
  $query = db_select('sessions');
  $query->addExpression('COUNT(sid)', 'count');
  $query->condition('timestamp', $timestamp, '>=');
  $query->condition('uid', 0, $anonymous ? '=' : '>');
  return $query->execute()->fetchField();
}

```

It returns the count of users who have been active in the past (default) 15 minutes like this:

```
    function admin_menu_get_user_count() {
      $interval   = REQUEST_TIME - variable_get('user_block_seconds_online', 900);
      $count_anon = admin_menu_session_count($interval, TRUE);
      $count_auth = admin_menu_session_count($interval, FALSE);

      return t('@count-anon / @count-auth', array('@count-anon' => $count_anon, '@count-auth' => $count_auth));
}

```
> 8 votes

# Answer
Depending on what you want to know the google analytics module could help you. It counts the number of unique users. This is only helpfull if you don't have to many registered users.
> 3 votes

# Answer
For info related to visitors of a website, consider the visitors module as an alternative.
One of the things you get from it is a **Visitors Block**, which includes, among others, data about:

* Total Visitors.
* Unique Visitor.
* Registered Users.
* ...

Combining these 3 numbers is a possible estimate to "calculate" the number of unique not-registered (anonymous) users.

This module also comes with some reports & charts (a typical related requirement ...).

Its community docu and/or project page contains some more details. However its documentation pages still need quite some work to get completed. Refer to issue #2432369, for various topics that still need to be included somehow. The child issues of this issue already contain some pointers to documentation contained in existing issues. Testing the module in your own environment is a possible approach to find out what the module's capabilities really are.

Disclosure: I'm the new maintainer of this module,
I hope this does not violate the site's policy on self-promotion.
> 1 votes

---
Tags: 7, users, nodes
---


title: Want two discussion Forum

text:
# Question
Title: Want two discussion Forum
Hello Hiii Again Everyone I Am Creating A drupal website i want to create 2 forum for different topics Mean I want to create a business discussion forum and business ideas forum so in drupal there is only one forum so how can i make 2 different forms in one website

# Answer
> 2 votes
You need to add Forum Containers, and then place the Forums in the appropriate container. Topics are then added into the Forums from the add content or Forums page. So basically you need to plan the hierarchical structure that your forums will take beforehand.

For more forum features look at Adding functionality to your forum with contribs

Tutorial : 203: Creating and Managing Forums in Drupal 7

---
Tags: nodes
---


# Question
Title: Send old Simplenews to newly registered users?
I have sent a Simplenews newsletter.

Added some new users since this mailing, and would like to resend it to some newly subscribed users. How can I do that?

# Answer
> 1 votes
This functionality isn't built into simplenews but some of its functions can get you close:

```
module_load_include('inc', 'simplenews', 'includes/simplenews.mail');

//The node id of the newsletter to send
$nid = 123;

//The array of emails to receive the newsletter
$users = array('user@example.com','user2@example.com');

simplenews_send_test(node_load($nid), $users);

```

That should send out a newsletter to all users.

The one caveat is it will be marked as a test email with Simplenews's test footer at the bottom. This can be overridden via a custom simplenews-newsletter-footer.tpl.php to remove "This is a test version of the newsletter." from the footer.

# Answer
> 2 votes
I also found a brute way.

Set newsletter sending status to 0 which will allow a resend to the entire userbase.

Install https://www.drupal.org/project/simplenews\_filter

Select only the users that were missed the last time via Views, and send.

(One could also select to send all and delete the subscriber ids from the spool table where you dont want to send)

---
Tags: emails
---


# Question
Title: Print User Registration Block Through template.php file
I just want to print the user registration block through my template.php file without using the Form Block or Enabling php on my site to use this code:

```
<?php

if(user_is_anonymous()) {
  $form = drupal_get_form('user_register_form');
  print drupal_render($form);
}

?>

```

I have tried the following:

```
function my_template_form_alter {

      $form = drupal_get_form('user_register_form');
      print drupal_render($form);
}

```

I want this block to appear on my blocks administration page just like the user login block, so I can place it anywhere I like. Any help as per how to achieve this? Thanks

# Answer
You won't need any alters. Just go to the template in which you want to place the registration form and add,

```
$form = drupal_get_form('user_register_form');
print drupal_render($form);

```

This will print the user registration form. It's always good to have a check for anonymous users as a wrapper of this output.

Edit #1 (After question update and comments) I suppose you want to create a block that will appear in your "admin/structure/block" page and you can assign the block in any desired region? - Right? I don't think your question says the same but this can be done in the following way,

* Create a hook\_block\_info() & hook\_block\_view()
* In the hook\_block\_view() assign the "content" the following,

```

$form = drupal_get_form('user_register_form');
$block['content'] = drupal_render($form);

```

I hope this can solve your problem. I haven't tested this yet!
> 0 votes

---
Tags: blocks, users
---


# Question
Title: Drupal forum post not showing on forum index
I posted a new topic in the Drupal "Post installation" forum. When I clicked "Save", I got a new page with my post at the URL

https://www.drupal.org/node/2465665

The post is in a red box on that page. When I go back to the forum index, the post is not listed there. It's also not listed when I go to my profile and click on "Your posts".

I don't see any message that the post is awaiting approval nor anything in my dashboard saying that my account needs anything.

What's going on? I'm not likely to get a response if people can't see my post!

Thanks for your help.

# Answer
The red box means the post has been unpublished. You are still able to see the post, but everyone who is not a webmaster gets a 403.

Drupal.org uses a number of automated tools to detect and unpublish unwanted posts (e.g. suspected spam). The most likely explanation is that your post tripped up one of these automated tools.

If you believe your post was unpublished in error, request it to be republished in the Drupal.org webmasters issue queue.
> 1 votes

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


# Question
Title: Acquia installation is up-to-date but requests update and reports errors
I have installed Acquia Dev Desktop in order to have a local Drupal development environment. My computer is running Windows 7. The prototype site provided with the installation appears to run fine, but there are two problems in the dashboard.

(1) Under "Reports \> Status report", the section on "Drupal core update status" is in red and says, "See the available updates page for more information and to install your missing updates." The words, "available updates" in that are linked. When I click that, I get "All of your projects are up to date" plus a link for "Check manually". When I click that, it works for a while and then says, "Checked available update data for 5 projects. ... All of your projects are up to date."

So Drupal both reports being up-to-date and says that there are "missing updates."

(2) Under "Reports \> Available updates", there is a red box at the top of the page with four bullets: • Notice: Undefined index: reason in theme\_update\_report() (line 86 of C:...\local\DrupalDev\DrupalTest\modules\update\update.report.inc). • Notice: Undefined index: in theme\_update\_report() (line 137 of C:...\local\DrupalDev\DrupalTest\modules\update\update.report.inc). • Warning: date\_timezone\_set() expects parameter 1 to be DateTime, boolean given in format\_date() (line 2040 of C:...\local\DrupalDev\DrupalTest\includes\common.inc). • Warning: date\_format() expects parameter 1 to be DateTimeInterface, boolean given in format\_date() (line 2050 of C:...\local\DrupalDev\DrupalTest\includes\common.inc).

Below that, under the heading, "Drupal core", there is a yellow text box. In the top right corner is a warning icon (dark yellow triangle with exclamation mark) and the box has the following text: "Acquia Drupal 7.34.40 (Drupal 7.34 core) Recommended version: () Includes: Acquia Connector, Bartik, Block, Color, Comment, Contextual links, Dashboard, Database logging, Drupal 7 driver for SQL Server and SQL Azure, Field, Field SQL storage, Field UI, File, Filter, Help, Image, List, Menu, Node, Number, Options, Overlay, Path, Pathauto, RDF, Search, Seven, Shortcut, System, Taxonomy, Text, Toolbar, Update manager, User"

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

I found the recommendation to use Acquia Dev Desktop in three places:

www.drupal.org/node/1248034

www.drupal.org/node/263

www.drupal.org/node/1065212

which are the links in the first, second, and sixth bullets in "Local server setup" at www.drupal.org/node/157602 .

So it comes highly recommended. But the above behavior looks pretty flaky. Have I done something wrong with the installation?

Thanks for your help.

# Answer
> 0 votes
For the errors, I think you could continue developing your Drupal site with it but for me I wouldn't like those in my site. I myself don't know the cause of it thought but I found a recent issue in the Acquia forum: Errors on Clean Acquia Drupal Install which still has no reply on a fix.

**Option 1: Use Acquia**

Try uninstalling and reinstalling the whole Acquia Dev software and see if the issue still persists.

**Option 2: Use XAMPP(I use)/WAMPP**

I've been using this since I started web and its straight forward. You don't need to change any settings too. What you need to do is:

1. Download the .exe from the XAMPP page
2. Install the application
3. Download Drupal Core that can be downloaded here
4. Extract Drupal Core into C:/xampp/htdocs/\[your drupal root folder\] (if you just chose the default settings of XAMPP on installation)
5. Go to http://localhost/phpmyadmin and create your database there, just use the defaults too
6. Start the installation of your Drupal site by going to http://localhost/your-drupal-root-folder-name\]

---
Tags: acquia-dev-desktop
---


title: response grid view and adaptive themes

text:
# Question
Title: response grid view and adaptive themes
I have:

* a view which displays three pictures of 300 * 200 each
* it should be responsive at breaks of 300 and 600
* adaptive themes

1) I installed responsive grid view. In here I need to add a wrapper – but I don't know which one or what to create. Is there already a wrapper in the adaptive theme for this?

2) Also I generated a css file at gridpack.com. This css file I added to the theme and I replaced:

* .col with the views-responsive-grid label (css is in the page)
* .col with .views-column (the css is in the page)
* .row with .views-row (I can't see this back in the page)

It still doesn't work. Still on the big screen all images are display vertically. Is this the way it *should* work or there any other suggestions?

# Answer
> 2 votes
I don't know if you mean adaptive theme as the theme on drupals repository or adaptive theme as a general behavior. Either way, you don't need a module to handle it. You just need the proper media queries, regardless if they're served by AdaptiveThemes or you insert them directly into your CSS files, somewhere at the end.

Once again, displaying three elements as a grid doesnt require a grid regulation. Is just a view, could be unformatted or html list or whatever. You need to declare responsive widths in your CSS for each row of the view, like so:

> Consider using .gridimg as your row class in unformatted format for example

**HTML**

```
            <div class="gridimg">
                <img src="some-path/image1.jpg">
            </div>
            <div class="gridimg">
                <img src="some-path/image2.jpg">
            </div>
            <div class="gridimg">
                <img src="some-path/image3.jpg">
            </div>

```

**CSS**

```
            .gridimg {
                width: 33.333333%;
                float: left;
            }

```

**Then the media query where needed**

```
            @media all and (max-width: 600px) {
                gridimg {
                    width: 100%;
                    float: none;
                    margin-bottom: 10px;
                }
            }

```

Do not display elements for the sake of your media queries, display elements for the sake of your content. Replace 600px with whatever resolution you want your rows to adjust.

Your classes could be named differently. Also the wrapper of your three generated rows should be set to 100%. Rows within should be position: relative;. They're like this by default, unless specified in a different manner.

Maybe your image element should have some css applied to them, for responsive purposes, if they're not set already:

```
            .gridimg img {
                width: 100%;
                height: auto;
                display: block;
            }

```

---
Tags: theming
---


title: How to add Modal in Bootstrap Sub Theme

text:
# Question
Title: How to add Modal in Bootstrap Sub Theme
I am trying to make a sub theme based on Bootstrap 3 Drupal theme.

I want to add a modal markup in every page. I can see in the base Bootstrap theme template files, there is a file called modal.tpl.php with corresponding HTML markup but I do not know how to include it into my page. Anyone can help?

# Answer
> 1 votes
First refer to the bootstrap documentation on modals http://getbootstrap.com/javascript/ to construct a working modal with the content you want. Use bootply or whatever to get it working the way you want.

You then have two options that come to mind: You could just create a standard block using the Drupal UI, place the markup in the body of the block, and configure the block to "display on every page except" ... `<front>`. Then assign the block to a region.

Alternatively, you can override tpl files in your subtheme and place the modal markup in those. You do this by placing a copy of the Bootstrap theme's `page.tpl.php` in your subtheme. First create a copy of it called `page--front.tpl.php` then add your modal markup to `page.tpl.php`.

---
Tags: theming
---


title: How to theme main menu in three columns

text:
# Question
Title: How to theme main menu in three columns
I have a main menu block which i am showing at top-navigation. I need to theme main menu but not sure how to apply classes to the root level menu items and sub menus.

i tried below snippet but not getting result. Can anybody tell me how to achieve this.

$main\_menu, 'attributes' =\> array( 'id' =\> 'main-menu', 'class' =\> array('links', 'navlist1', 'clearfix'), ), )); ?\>

Below is the screenshot image which output i want to show in main-menu

# Answer
> 0 votes
1. For a quick non-programmatic solution, you can consider using the Menu blocks module to render 2nd level menu items in 6 separate blocks, then render the blocks in the regions you want. On top of this you can also add customer classes on menu items with Menu attributes module.
2. If you don't mind a javascript approach, you can manipulate dom to move the sub menus around.
3. If you are familiar with the theme layer, you can create your custom theme function for main menu by implementing themename\_links\__system\_main\_menu.

---
Tags: routes, theming
---


# Question
Title: In Drupal 7 how do I check if a node author has a certain role?
Specifically, I have custom node.tpl.php called node--directory.tpl.php works great. Now how do find out if the node author has the role 'premium\_user', so that node will have premium style features. I have seen a post about checking the current user for a role:

```
global $user;

if (in_array('authenticated user', $user->roles)) {
     //do fancy style stuff here
}

```

I want to do the same for $uid (in node.tpl.php it says that is variable for the user id of the node author). Any help appreciated. Thanks Frank

# Answer
> 0 votes
`global $user` will give you the information about currently logged in user not about the node author.

To get the node author, you should use the $uid variable which is available in the node template. Below is the sample code(untested) for checking the author's role,

```
$author = user_load($uid);
if (in_array('premium_user', $author->roles)) {
  //do fancy style stuff here
}

```

# Answer
> 0 votes
You can use this custom function. Just place this it in a custom module, or in your **template.php** file :

```
function user_has_role($role, $user = null) {
  if ($user == NULL) {
    global $user;
  }

  if (is_array($user->roles) && in_array($role, array_values($user->roles))) {
    return true;
  }

  return false;
}

```

You can use like this :

```
// How to use it for current logged in user
$role = 'myrole';
if (user_has_role($role)) {
  // Do something
}

// How to use it for x user
$role = 'myrole';
$user = user_load($uid);
if (user_has_role($role, $user)) {
  // Do something
}

```

# Answer
> 0 votes
For a more granular approach, recommend checking for permissions using user\_access() instead of roles.

You'll have to implement your own permissions but it's much flexible to control which role has which permissions in the future.

---
Tags: nodes, theming
---


# Question
Title: Alternate ways to call a function inside a .module file of a module
I have installed quickdraw module and it needs some additional functions to be executed using drush commands. For that, I used the following drush commands:

```
drush php-eval "quickdraw_xx_xx_additionalfunction();"

```

But it returns an error

```
Fatal error: Call to undefined function quickdraw_facet_navmenu_materialize() in /usr/local/Cellar/drush/6.3.0/libexec/commands/core/core.drush.inc(1100) : eval()'d code on line 1
Drush command terminated abnormally due to an unrecoverable error.                                                                [error]
Error: Call to undefined function quickdraw_facet_navmenu_materialize() in
/usr/local/Cellar/drush/6.3.0/libexec/commands/core/core.drush.inc(1100) : eval()'d code, line 1

```

As discussed in this post. I have tried module\_load\_include(), which returns the same `Fatal error`.

Also tried `drush eval 'quickdraw_xx_xx_cron();'` \- Didn't work!!!

Is there any alternate ways to execute the function or how can I resolve the issue. Any ideas??

**NOTE:** The additional function is defined in `quickdraw_xx_xx.module` file, I assume it is not being recognized.

# Answer
You should make a drush command. It's not very hard:

```
function quickdraw_xx_xx_drush_command() {
  $items = array();
  // Name of the drush command.
  $items['quickdraw_xx_xx_additionalfunction'] = array(
    'description' => 'A quickdraw additional function.',
    'callback' => 'quickdraw_xx_xx_additionalfunction',
  );
  return $items;
}

```

This way, Drupal will bootstrap and everything you need will be there, including dependencies to other files.
> 1 votes

---
Tags: drush
---


# Question
Title: How can I theme the Views Exposed Filter?
I create a view in drupal 7 display a collection of books, and taxonomy for book types .. then I call book type taxonomy in my view and it displayed good .. But because book types taxonomy menu have about 10 items and maybe increased at any time, I want to display 3 items of book types and when click More link display a list of the others, I can't do it in css only, and I can't add a div to group the other part of the list .. so how can I do that?

thank you

when I try to print my exposed filter array

```
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
     $view = $form_state['view'];

    if ($view->name == 'taxonomybooktype' && $view->current_display == 'taxobooktype') {

        $form['field_book_type_tid']['#options']['All'] = "All";

              echo "<pre>";
      print_r($form['field_book_type_tid']);
      exit;
            }
    }

```

}

output:

```
Array
(
  [#type] => select
  [#options] => Array
    (
        [All] => All
        [0] => stdClass Object
            (
                [option] => Array
                    (
                        [7] => Chemical
                    )

            )

        [1] => stdClass Object
            (
                [option] => Array
                    (
                        [1] => computer
                    )

            )

        [2] => stdClass Object
            (
                [option] => Array
                    (
                        [6] => History
                    )

            )
    )
[#size] =>
[#default_value] => All
[#theme] => select_as_links

```

)

but now how can I group first tow options in a div and remain options in another div or group?

# Answer
> 0 votes
Agreed with MPD, but basically if you want you can also go with `$form['#id']`

What you can do is, first try to get your `$form['#id']` using `form_alter`

```
function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
    echo "<pre>";
    print_r($form['#id']);
    exit;
}

```

Once you get your `$form['#id']` you can add a condition, something like this

```
function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
    if ($form['#id'] == 'YOUR_FORM_HASH_ID') {
        // Your magic code goes here...
    }
}

```

Let me know, if I can help you in any other way :-)

# Answer
> 4 votes
Exposed filters use the form API, so you can implement a `hook_form_FORM_ID_alter()`:

```
function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  $view = $form_state['view'];

  if ($view->name == 'my_view' && $view->display == 'my_display') {
    // do something awesome
  }
}

```

Normal Form API procedures then apply.

# Answer
> 3 votes
Views exposed form layout module helps with Views exposed form theming.

# Answer
> 1 votes
I usually recommend to use the Better Exposed Filters (BEF) module for anything styling related. It gives you a great deal of flexibility concerning UI controlled styling.

But if I understand your question right, then you're neither finished with the suggested solutions (form\_alter) nor with BEF. The reason is that your exposed taxonomy term filter is probably rendering the filter as a single form element that you can't easily be split into several divs.

You could try to do the following, assuming you have, say, 3 "promoted" filters that you always want to show. Then you could add one filter of type taxonomy term, display the filter as checkboxes and limit the valid options to those 3 three "promoted" terms and expose the filter. Then add this same filter again, expose it, but this time limit the valid options to all other terms except the three "promoted" ones. You could then use BEF for example to put this second filter inside the secondary options form (this is a BEF setting) or simply make the filter collapsible (also possible so set in the BEF settings).

Another solution to reduce clutter in search interfaces that I recently needed to build for one of my projects uses a javascript based "reducing" approach (no idea how to call that really). I have published it on github if you want to have a look at it: jQuery-UI-reduceOptions-Plugin. It will initially show all checkboxes, but provides ways of interacting that allow to hide unselected options once the form has been submitted (and is reloaded with the new defaults set, or using ajax submission). It's probably not a real drop-in solution but it works pretty neat, see the screenshots:

---
Tags: views
---


# Question
Title: How to theme each field of exposed filter from Views?
I have found the theme template for exposed filter form of view. Template name: `views-exposed-form.tpl.php`

Inside the template I found the `$widgets array` and `for loop` for each `$widget` display in form.

But it is rendered HTML widget How can I get only values array for each combo box to render output for my combo box as I want?

for instance:

I have one combo called Country: Country has hierarchy level of list

```
Asia
- India
- Sri lanka
- thailand
- Indonesia

```

etc...

So, I would like to make my combo just like this

```
http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_optgroup

<select>
  <optgroup label="Swedish Cars">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
  </optgroup>
  <optgroup label="German Cars">
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </optgroup>
</select>

```

This will identify the parent / child category in combo? can we do this directly in drupal 7 Views for Expoesd Filters Combo ? or How can I theme myself to override its HTML?

# Answer
> 1 votes
You can try to catch it with `hook_form_alter()`: `$form_id` is views\_exposed\_form, and `$form` contains all the values.

```
$form['field_custom']['#options'] = array(
  'group1' => array('key11' => 'value11', 'key12' => 'value12'),
  'group2' => array('key21' => 'value21', 'key22' => 'value22' ),
);

```

# Answer
> 0 votes
You can control everything at different levels, with the "views-exposed-form" template, and editing the widgets' HTML code in the "theme\_preprocess\_views\_exposed\_form".

I wrote a post on how to do this in my blog:  ~~http://danyalejandro.com/portafolio/content/theming-exposed-filters-drupal-7-views~~

Theming exposed filters in Drupal 7 Views (Web Archive Retrieved)

# Answer
> 0 votes
Maybe Views exposed form layout module may help you.

---
Tags: theming, views
---


# Question
Title: Add view with contextual filter to XML sitemap
I setup a view with the following path www.example.com/profile/% (the user contextual filter i added is the username of the). These displays the profile of each user.

Please is there a way to add the view to the XML sitemap?

# Answer
> 1 votes
There is an XML Sitemap Custom submodule in the XML Sitemap module

You can use this to set Page Views' paths for inclusion in the XML Sitemap

You might also check this module out: https://www.drupal.org/project/xmlsitemap\_aliases From the project page: "Anything with a path in the aliases table can now be included in your XMLsitemap by the click of a button! (This is particularly useful when you have too many to enter manually as custom links, for example: views with arguments!)"

---
Tags: xml-sitemap
---


title: Custom subdomains with htaccess

text:
# Question
Title: Custom subdomains with htaccess
I have page structures like:

* example.com/aaa
* example.com/aaa/a1
* example.com/aaa/a2
* example.com/bbb
* example.com/bbb/b1
* example.com/bbb/b2
* example/com/ccc
* ........

What I need is instead **example.com/xxx/x1**, I want users to see **xxx.example.com/x1**

How can I achieve this with a rewrite rule? Or any other suggestions?

Subdomains module does not work for me because it doesnt allow custom subdomains.

# Answer
I ended up creating a multisite structure.

1. Under sites folder I created a folder for each subdomain like: "aaa", "bbb",...
2. I created a settings.php inside each folder (starting with php tags, do not close it though):

> ```
> include_once(dirname(dirname(__FILE__)) . "/default/settings.php");
> $conf['site_frontpage'] = "aaa";
>
> ```

(It inherits the general settings.php file since I dont need very different settings per domain)

3. Created a sites.php file inside sites folder (again starting with php tags):

> $sites\['aaa.example.com'\] = 'aaa';
>
> $sites\['bbb.example.com'\] = 'bbb';
>
> .......
> 1 votes

# Answer
**xxx.example.com** IS a subdomain. It could be set as example.com/xxx/, or xxx.example.com, doesn't really matter. The point is, you are trying to achieve a subdomain structure. And you should be able to set subdomains.
> -1 votes

---
Tags: 7, subsites
---


# Question
Title: search block form not accepting special characters in drupal 7
If I search with any special character in drupal default search block form it returns error message like "You must include at least one positive keyword with characters or more.".after i do search with letters or numbers it does not bring results.shows same error.the form has been submitted but value does not change. Any help appreciated..

# Answer
The error has nothing to do with special characters (e.g. "$", "@"). It pertains to the **length of your keywords**. By default, Drupal core search restricts minimum keyword size to 3; any query less than 3 characters will trigger the error (e.g. "$9").

If you really need search to include 2/1 character queries, the search settings in **/admin/config/search/settings** under the **Minimum word length to index** option will allow you to do this.

**Note:** This will expand out the size of your search index (catching common words like "an" & "a"). If you have a large site with thousands of nodes you shouldn't do this.
> 0 votes

---
Tags: forms, search
---


# Question
Title: Assign Multiple roles to Ubercart Product
I am using ubercart and Roles module to sell some roles on my drupal 7 site. I wonder whether I can sell multiple roles with a single product, I tried to add multiple roles to a single product under features, but after purchasing a product I found only one role is assigned to the purchaser, Is there any way I can assign multiple roles.

# Answer
> 0 votes
Yes, the UC Roles module can assign multiple roles on purchase. All you need to do is add each role assignment you want at **/node/XXX/edit/features**.

If the roles aren't being assigned after purchase, you might want to check the SKU options you have for each feature. It could be that your product purchase is a SKU that isn't configured for role assignment. If that isn't it, you should check to make sure that your checkout rules are configured to set the right order status to trigger role assignment.

---
Tags: ubercart
---


title: Rewriting paths

text:
# Question
Title: Rewriting paths
By default, pages on our site look like:

```
http://www.example.com/items/item-1-name

```

First, I need them to have ".html' on the end:

```
http://www.example.com/items/item-1-name.html

```

Second, I need any reference to ".print.html" (below) to redirect to .html:

```
http://www.example.com/items/item-1-name.print.html

```

This seems like an .htaccess thing to me, but a few things prompted me to write this question:

1. I don't want to put these in .htaccess (that belongs to Drupal, correct?)
2. I didn't have any success putting them inside my vhost file (following this post)
3. I'm not sure if there is another recommended way to do this routing in drupal

**Update**: Here's a bit more info on my specific situation:

* I'm only dealing with a single content type here - all 'items' are nodes of the same type.
* Paths are currently generated via Pathauto
* All 'items' are multi-lingual; pathauto creates urls from the title in each language

# Answer
> 1 votes
Your intuition is correct. It looks like a couple of simple htaccess rewrites:

```
  RewriteRule ^(.*)\\.print\\.html$ /$1 [NC,L,R=301]
  RewriteRule ^(.*)\\.html$ /$1 [NC,L,R=301]

```

To address your #1 concern, there's no problem altering .htaccess. It contains a few customizations that were designed to be altered depending on your needs (e.g. prepending "www." to your host name). It's required for some modules like boost.

The only caveat is you have to make sure to copy over customizations when you need to update core. If that's a problem there's the .htaccess module dedicated for keeping track of your custom rules.

---
Tags: 7, redirection, .htaccess, uri
---


# Question
Title: Can't successfully Checkout using Braintree v.zero
I'm integrating Braintree's v.zero drop-in ui as a payment method and on the checkout form.

I fill-up the credit card details and click "Continue to next step", the ajax submit and Braintree loads simultaneously. After a couple of seconds, Braintree finishes and returns the payment nonce. However, the form doesn't continue it's submission.

**How can I process Braintree first before the form so that I can get the payment nonce value?**

Module code

```
/**
 * Initializes the Braintree client library for use.
 *
 * @param $payment_method
 *   The payment method instance containing the Braintree credentials to use to
 *   submit API requests to Braintree.
 */
function commerce_braintree_vzero_initialize($payment_method) {
  require_once drupal_get_path('module', 'commerce_braintree_vzero') . '/braintree-php-2.37.0/lib/Braintree.php';

  Braintree_Configuration::merchantId($payment_method['settings']['merchant_id']);
  Braintree_Configuration::publicKey($payment_method['settings']['public_key']);
  Braintree_Configuration::privateKey($payment_method['settings']['private_key']);
  Braintree_Configuration::environment($payment_method['settings']['environment']);
}

/**
 * Implements hook_commerce_payment_method_info().
 */
function commerce_braintree_vzero_commerce_payment_method_info() {
  $payment_methods = array();

  $payment_methods['commerce_braintree_vzero'] = array(
    'title' => t('Braintree v.zero'),
    'description' => t('Payment method using Braintree v.zero.'),
    'active' => TRUE,
  );

  return $payment_methods;
}

/**
 * Returns the default settings for Braintree v.zero.
 */
function commerce_braintree_vzero_default_settings() {
  return array(
    'merchant_id' => '',
    'public_key' => '',
    'private_key' => '',
    'environment' => 'sandbox',
  );
}

/**
 * Payment method settings form.
 *
 * @param $settings
 *   Default settings provided from rules
 *
 * @return array
 *   Settings form array
 */
function commerce_braintree_vzero_settings_form($settings) {
  $form = array();

  // Merge default settings into the stored settings array.
  $settings = (array) $settings + commerce_braintree_vzero_default_settings();

  $form['merchant_id'] = array(
    '#type' => 'textfield',
    '#title' => t('Merchant ID'),
    '#default_value' => $settings['merchant_id'],
    '#required' => TRUE,
  );
  $form['public_key'] = array(
    '#type' => 'textfield',
    '#title' => t('Public key'),
    '#default_value' => $settings['public_key'],
    '#required' => TRUE,
  );
  $form['private_key'] = array(
    '#type' => 'textfield',
    '#title' => t('Private key'),
    '#default_value' => $settings['private_key'],
    '#required' => TRUE,
  );
  $form['environment'] = array(
    '#type' => 'radios',
    '#title' => t('Braintree server'),
    '#options' => array(
      'sandbox' => ('Sandbox - use for testing, requires a Braintree Sandbox account'),
      'production' => ('Production - use for processing real transactions'),
    ),
    '#default_value' => $settings['environment'],
  );

  return $form;
}

/**
 * Payment method callback: checkout form.
 */
function commerce_braintree_vzero_submit_form($payment_method, $pane_values, $checkout_pane, $order) {
  // Load Braintree vzero php library
  commerce_braintree_vzero_initialize($payment_method);

  $clientToken = Braintree_ClientToken::generate();

  $form['test'] = array(
    '#markup' => '<div id="asd"></div>' .
    '<script src="https://js.braintreegateway.com/v2/braintree.js"></script><input type="submit">',
  );

  $form['testt'] = array(
    '#type' => 'textfield',
    '#title' => t('Test'),
  );

  drupal_add_js(array('vzero' => array('clientToken' => $clientToken)), 'setting');

  // Load vzero.js.
  $form['#attached']['js'] = array(
    drupal_get_path('module', 'commerce_braintree_vzero') . '/vzero.js',
  );

  return $form;
}

/**
 * Payment method callback: checkout form submission.
 */
function commerce_braintree_vzero_submit_form_submit($payment_method, $pane_form, $pane_values, $order, $charge) {
  commerce_braintree_vzero_transaction($payment_method, $order, $charge);
  drupal_set_message('success');
}

/**
 * Creates an example payment transaction for the specified charge amount.
 *
 * @param $payment_method
 *   The payment method instance object used to charge this payment.
 * @param $order
 *   The order object the payment applies to.
 * @param $charge
 *   An array indicating the amount and currency code to charge.
 */
function commerce_braintree_vzero_transaction($payment_method, $order, $charge) {
  $transaction = commerce_payment_transaction_new('commerce_braintree_vzero', $order->order_id);
  $transaction->instance_id = $payment_method['instance_id'];
  $transaction->amount = $charge['amount'];
  $transaction->currency_code = $charge['currency_code'];
  $transaction->status = COMMERCE_PAYMENT_STATUS_SUCCESS;

  $transaction->message = 'Test message';

  commerce_payment_transaction_save($transaction);
  return $transaction;
}

```

JS code

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

      if ($('#edit-commerce-payment-payment-method-commerce-braintree-vzerocommerce-payment-commerce-braintree-vzero', context).is(':checked')) {
        console.log("LOADED " + $('#asd').length);
        braintree.setup(settings.vzero.clientToken, "dropin", {
          container: "asd",
          paymentMethodNonceReceived: function (event, nonce) {
            console.log('nonce received ' + nonce);
            $('.form-item-commerce-payment-payment-details-testt input').val(nonce);

            $('body').delegate('#edit-continue', 'click', function(event) {
              event.preventDefault();
              console.log('prevent submit');
              return false;
            });
          }
        });
      }
      else {
        console.log("NOT CHECKED");
      }
    }
  }
})(jQuery);

```

**Note:** This here is the complete module if you would like to test. https://github.com/leolandotan/commerce\_braintree\_vzero

# Answer
this patch successfully adds support for Vzero https://www.drupal.org/node/2449881.
> 1 votes

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


title: Views filter count

text:
# Question
Title: Views filter count
I'm trying to set up a block that will allow me to show 6 items in it, 2 that are checked yes and 4 that are checked no. They are sorted by date so I have a pager set up to take the first 6 values. What I would like is if for example the first 5 items are checked no and the next two are checked yes, then my block should show the first 4 no items and the first two yes items.

Thanks!

# Answer
> 1 votes
Create one block.

Then for the same view create an attachment and add it to the block (after).

Set the pager for the block to display specified number of items : 2 , and set the sort to checked yes and then by date.

Set the pager for the attachment to display specified number of items : 4 , and set offset to 2. Set the sort to not checked yes and then by date.

To swap the order around set the attachment to attach before the block.

# Answer
> 0 votes
This can't be done by simple view as per my knowledge. You need to change the output of view's `$result` array in hook\_views\_pre\_render

---
Tags: views
---


# Question
Title: Drupal theme IMG folder rewrite rule from vhosts conf file?
I am wondering if it is possible to create a rewrite rule in my vhosts config file for a site to remap the location of the images folder in the theme directory.

The scenario is that I don't want to create a whole new theme for on region of a multilingual site but given that the URL is different for this region I would like to remap for example:

sites/all/themes/theme/img/(.\*) to sites/all/themes/theme/img\_other/$1

I have tried some variations ion what I have just put there as the example but nothing is working as yet.

Any help would be much appreciated.

Thanks

# Answer
> 0 votes
I would add a RewriteRule to the .htaccess file rather than a vhosts config; it's portable in the event of a server change and it doesn't require an Apache reload if you need to update redirect rules.

For your scenario this line is all you need in your .htaccess file:

```
RewriteRule ^sites/all/themes/theme/img/(.*)$ /sites/all/themes/theme/img_other/$1 [NC,L,R=301]

```

If you're using a vhosts conf because it's a multi-domain site (e.g. en.example.com, de.example.com, etc.) then you can add a RewriteCond in front of it to match the domain you need to apply it to:

```
RewriteCond %{HTTP_HOST} ^de.example.com$ [NC]
RewriteRule ^sites/all/themes/theme/img/(.*)$ /sites/all/themes/theme/img_other/$1 [NC,L,R=301]

```

---
Tags: uri
---


title: Show cart block in pop up

text:
# Question
Title: Show cart block in pop up
I've installed Drupal Commerce module, I got show cart block in header. If I click on it takes to cart page. I need a pop up of cart page on clicking show cart.

# Answer
> 1 votes
Try the Commerce Ajax Add to Cart module.

> Using this module you can ajaxify the add to cart operation. The updated cart will be displayed without page refresh and a popup message will be shown after you add an item to cart. You can customize the look of the blocks using its template files.

# Answer
> 0 votes
Along with Krishna Mohan suggestion you can try Commerce Ajax Cart.

This module adds a pop up cart that is AJAX handled.

---
Tags: commerce, blocks, javascript
---


# Question
Title: How to recover drupal password in localhost?
I have a complete Drupal website on localhost. I forgot the password and username for my account. I found the username in the database, but the password is hashed.

I can't send emails from localhost, so recovering the password using the email is not possible.

How can I recover the password?

# Answer
You can update the password via mysql. You can run the following query in mysql to update password. The given hashed value is the hashed value of password: NewPassword

```
UPDATE users SET pass = '$S$DRSUIz9NFfxOXKPveQ00UTGMzsJe62LjYvVHfYJ8I8wuy4zRqVBK' WHERE uid = 1;

```

For detailed instructions go through these article Resetting the administrator password with sql-query (Drupal 7)
> 7 votes

# Answer
If you are using Gnu/Linux or compatible, the simplest method with *drush* is this:

Install drush (if you haven't done so yet).

Go to your `drupal-root/sites/mysite` folder.

Type in the Gnu/Linux CLI:

```
sudo drush upwd --password="newpassword" admin

```

(where "admin" is the user name of user #1).

The password will now be "newpassword".

Alternatively, you can type in the Gnu/Linux CLI:

```
sudo drush uli

```

and use the URL it gives you to log in.
> 4 votes

# Answer
If you are using Linux:

1. Install drush
2. Go to your `drupal-root/sites/mysite` folder
3. Type `sudo drush uli` and use the URL it gives you to log in.
> 0 votes

# Answer
If you don't have Drush you could do:

1. Edit your index.php in your Drupal site root
2. Insert the code below between "drupal\_bootstrap(DRUPAL\_BOOTSTRAP\_FULL);" and "menu\_execute\_active\_handler();":

require\_once 'includes/password.inc';
echo user\_hash\_password('CHANGE\_THIS\_TO\_DESIRED\_PASSWORD');
die();
3. Copy the hashed string
4. Go to your database administration UI or phpmyadmin
5. Go to the users table
6. Find the admin user (mostly is the user with 1 as the uid)
7. Update the admin's password field using the hashed string you just copied.
8. Comment or delete the code in step 2
9. Refresh your site and login
> 0 votes

# Answer
The easiest way is to open the `users` table in *phpmyadmin*, in the password column, delete the content of the row of the admin username. In this way the password is deleted.

Open the database of another website in your localhost that you know the admin password, open the `users` table, in the password column, select the row of the admin user and copy its content to the admin row of `users` table of database of the website that you forget its password.

Notice that the passwords are saved in hash format in the database.
> 0 votes

# Answer
Just create a file "new\_password.php" (or with any other name) inside your drupal folder and access it using browser. It will generate one way encrypted hash password for you.

```
<?php
  define("DRUPAL_ROOT", getcwd());
  require_once DRUPAL_ROOT . "/includes/bootstrap.inc";
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
  require_once "includes/password.inc";
  echo user_hash_password("123456");
  die();
  menu_execute_active_handler();
?>
```

When you run this code in browser it will show you hash password like

```
$S$D95YW4EejaUDPq5nZ7Z2Ljx1Ud4wlN1iTMQdAKton70JcQpCZmrG
```

Now you need to update your database table using above hash. Open your database using PHPMyAdmin or Workbench and run the below query.

```
UPDATE users SET pass = '$S$D95YW4EejaUDPq5nZ7Z2Ljx1Ud4wlN1iTMQdAKton70JcQpCZmrG' WHERE uid = 1;
```

Now you can access drupal using username as "admin" and password as "123456". Make sure you update password after login to the admin.
> 0 votes

---
Tags: 7, users
---


title: nid for custom form module

text:
# Question
Title: nid for custom form module
I have created a custom module(a simple form) in `drupal 7` using https://www.drupal.org/node/717722 , i have successfully installed newly created module and able to save the form data. But i need an `nid` for this module which is being use by other module to perform series of tasks, i have been searching a lot about how can i found the `nid` of custom module ,but none of solution worked , also i have searched in the database table , other contents like `webform` , `basic page` and `articles` are there in database with there nid's but the newly created module's nid is not there ,can any one please help how can i find the `nid` of custom module and if there is no such `nid` then how can i set and `nid` for newly created module.

thanks in advance

# Answer
> 0 votes
Forms don't have nid. Only nodes are having nid (node\_id) in drupal. If you are displaying the form on any node page, suppose on `http://example.com/node/123`. Here 123 would be the node id and you can fetch it in form by

```
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
}

```

And if you want this `$nid` to be passed through different form states, add this as form field

```
$form['nid'] = array('#type' => 'value', '#value' => $nid);

```

# Answer
> 0 votes
As Himanshu-Pathak said `nid` is for node not a module. You have to let us know what you are going to do, but when you said you want to get the id of nodes, so you want to do some processing on nodes. I recommend you to do this action using hook\_node\_load or hook\_node\_view\_alter or hook\_node\_view . These functions are called when a node is loaded, so you can get its ID and do anything you want in there (like displaying your form)

---
Tags: 7, nodes
---


title: User register and login test

text:
# Question
Title: User register and login test
I am trying to register and log in users via the Services module 7.0-3.11 on Drupal 7.36.

The endpoints are declared from the following code.

```
$endpoint = new stdClass();
$endpoint->disabled = FALSE; /* Edit this to true to make a default endpoint disabled initially */
$endpoint->api_version = 3;
$endpoint->name = 'user_service';
$endpoint->server = 'rest_server';
$endpoint->path = 'user_api';
$endpoint->authentication = array(
  'services' => 'services',
);
$endpoint->server_settings = array(
  'formatters' => array(
    'json' => TRUE,
    'bencode' => FALSE,
    'jsonp' => FALSE,
    'php' => FALSE,
    'xml' => FALSE,
  ),
  'parsers' => array(
    'application/json' => TRUE,
    'application/vnd.php.serialized' => FALSE,
    'application/x-www-form-urlencoded' => FALSE,
    'application/xml' => FALSE,
    'multipart/form-data' => FALSE,
    'text/xml' => FALSE,
  ),
);
$endpoint->resources = array(
  'user' => array(
    'operations' => array(
      'retrieve' => array(
        'enabled' => '1',
      ),
      'index' => array(
        'enabled' => '1',
      ),
    ),
    'actions' => array(
      'login' => array(
        'enabled' => '1',
      ),
      'logout' => array(
        'enabled' => '1',
      ),
      'token' => array(
        'enabled' => '1',
      ),
      'request_new_password' => array(
        'enabled' => '1',
      ),
      'register' => array(
        'enabled' => '1',
      ),
    ),
    'targeted_actions' => array(
      'password_reset' => array(
        'enabled' => '1',
      ),
    ),
  ),
);
$endpoint->debug = 1;

```

I am using basic PHP code for the testing purpose. Please have a look at the GIST.

The problem is that, while I run the test page, I can see it registers a new user and outputs the following.

```
stdClass Object
(
    [uid] => 14
    [uri] => http://vote-app.dd:8083/user_api/user/14
)

```

But while I try to log in with the same user (as per the code) it outputs the following error.

> Error
> \["Wrong username or password."\]

I need some help on this. Am I missing something?

I also checked https://www.drupal.org/node/1491754 and other Drupal pages for this too.

# Answer
> 1 votes
Found the solution. Just for future references for others and me as well :-)

There is an issue in Services module Wrong username and password, just after a creation of a user where someone faced the same problem. User login just registration. So as it stated,

> If you are anonymous user and register a user your register form does not have password field at all. It has only username and email fields. All instructions are sent by email (with token to log in and set the password). So register call actually does not set the password.

This is actually true. If I go to the admin and change the password again then it's working. So the solution is to alter two variables,

```
variable_set('user_email_verification', FALSE);
variable_set('user_register', TRUE);

```

This will now allow the users to register by themselves.

---
Tags: 7, users, services
---


title: Load and submit user profile form

text:
# Question
Title: Load and submit user profile form
I want to programmatically load the user profile form for a specific user and submit it ( in order to trigger hook\_form\_submit() in another module ). So far I have :

```
module_load_include('inc', 'user', 'user.pages');
$account = user_load($uid);
$form = drupal_get_form('user_profile_form', $account);

```

but how do I submit the form ?

Thanks

# Answer
If oyu want to get and submit a form programatically you must use the function drupal\_form\_submit

> Retrieves, populates, and processes a form.
>
> This function allows you to supply values for form elements and submit a form for processing. Compare to drupal\_get\_form(), which also builds and processes a form, but does not allow you to supply values.

Check this function's documentation page and its comments for some examples.
> 0 votes

---
Tags: forms
---


# Question
Title: Is there any example for real project where field of deciamal type been used?
Drupal has several types of numeric fields:

* integer
* float
* decimal

I know, that decimal field is used to store numeric data with high accuracy. But when it may be necessary in real project? Are there any good examples?

# Answer
Here's a link to an explanation of Drupal's different number types (integer vs. decimal vs. float) with some examples. Basically, it breaks down as follows:

* **Integer:** You're storing numbers *without fractional digits* (e.g. a field that stores a product stock quantity, *XX units*)
* **Decimal:** You're storing numbers *with a **fixed amount** of fractional digits*. (e.g. a field that stores a price, *$XXX.YY*)
* **Float:** You're storing numbers *with a **variable amount** of fractional digits*. (e.g. a field that stores latitude/longitude coordinates, *XX.XXXXXXX..., YY.YYYYY...*)

Also of note is the underlying data structures of integer/decimal/float that gets stored in the database. See Fixed point vs. Floating point for some discussion on the differences.
> 1 votes

---
Tags: entities
---


# Question
Title: How to add a value to a field via custom button
I was wondering how do you add a value to a field on a form(node/add) via a custom button on views?

The scenario: On the form(node/add) a user can see and search a list of venues(view block) and on each venue there is a 'more' when clicked the user will be able to see a pop-up of the details of that certain venue. Inside the popup there is the 'Select this venue' button when clicked should be able to add that certain venue to the field 'field\_choose\_venue'.

I've been trying this all day but no luck. Any help will be much appreciated.

# Answer
The problem is complex. I think one way to address what you want is to code a JS behavior that is attachted to your block view that when user click each venue the venue value is added to the field and add more elements button is clciked, so Drupal reconstructs the form adding a new element.

Steps:

* Add the venue nid to your View but hide it using CSS. This is a quick-and.dirty way to have the Venu nid available for your JS code. A better way is to alter the views output and add the nid in some other way.
* Add a JS file for your module that will be added in that add form (use form alter and the $form\['#attached'\] key.
* Your JS file should be a Drupal behavior JS that will attach a click listener to your venues elems in the block. When clicked, the listener will have to locate the last empty venue form field element, put clicked venue nid in that field elem and click the 'Add more' button of that multiple value field to trigger and AJAX call that will make Drupal to reconstruct the form and add a new empty value for the venue form element.

But the easy way is to use Entity Reference View Widget. The behavior is not exactly what you want but I think it can fit your needs.

This module allows to open a popup with a View where you can select the values of the field. As the popup is filled woth a View you have all the power if Views to modify what user sees in the view.
> 0 votes

---
Tags: views, nodes, forms
---


# Question
Title: How to create a chart about the number of nodes by content type?
I am trying to make a chart with 1 column for each content type. Values are the addition of each total.

I have created a view (using the Views module) with two content-type fields. One of them is configured to Count Distinct in aggregation.

In a graph, however, only one column named Type appears, and not a column for each content type.

I am trying both with Views Dataviz and Google Charts Tools.

Any help on this would be appreciated.

# Answer
> 1 votes
Let me try to answer this if I am getting you clearly. There are several contributed modules available for creating charts in Drupal. Refer to the comparison of charting modules for more details. You are not specifying the Drupal version, let me assume a use case for 7. Also know that there are various types of licenses (commercial, open source, ...) for each of the charting libraries, so your choices may be limited by your license needs (each module typically requires at least 1 such charting library as its charting engine).

The solution I am giving has a lot to do with the Google Charts API implemented via the Google Chart Tools module. The module provides a simple API that allows you to build your graphs on that.The module ships with an example that gives a nice pointer to writing your own custom module.

A simple module to get the content types.

```
function example_block_info(){
  //lets display this in a block. You can do a page if you like.
  $blocks['example_chart'] = array(
     'info' => t('Example Line Bar Showing Content Types'),
     'cache' => DRUPAL_CACHE_PER_ROLE //This is a Drupal default.You can set your own.
   );
 return $blocks;
}

function example_block_view($delta = ''){
    //Create a display for the block.
    switch ($delta) {
      case 'example_chart':
       $block['content'] = example_block_contents()
      break;
    }
  return $block;
}

function example_block_contents(){
  //This is a function specific to the block that lets you prepare the content for the chart.
    //Google Chart Tools integration begins here.
    //First empty the array that is to be passed to draw_chart().
    $settings = array();
    //We then populate the array.
    $settings['chart']['Chart for Nodes'] = array(
      //I am using just one content type. You can loop to get the other node types.
      'header' => array('My Node'),
      //This is the array to be presented to draw().
      'rows' => array(array(
                example_node_count(),
               )
           ),
      'chartType' => 'ColumnChart',
      'containerId' => 'example_chart',
      'options' => array(
            'forceIFrame' = FALSE,
            'title' => 'A column chart for nodes',
            'width' => 800,
            'height' => 600
        )
    );
    draw_chart($settings);
    //Return the DIV containing the chart.
    return '<div id="example_chart"></div>';
}

function example_node_count(){
  //Custom function to count the nodes available.
  //Put to use Entity Field Query.
  $query = new EntityFieldQuery;
  $query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'my_node_type');
    //Count your node type.Introduce a loop to count your other nodes as needed.
    $my_node_type_count = $query->count()->execute();
    return $my_node_type_count;
}

```

This is just a shell of a working module. Get some education of the charts at Google Visualization API docs. Warning: There might be some typos in there. Just trying to give an alternative.

# Answer
> 1 votes
I seem to understand that this question is exactly what the purpose is of one of the Out-of-the-box examples that you get by simply installing (and enabling) the Charts module, and without any additional configuration.

By doing so, a new view is added to your site. Here are some more details about it, quoted from the linked page above (to which I added some formatting here):

> You can see the charts created via this new view in your own site by navigating to charts/examples or by using a menu link with a title like Charts examples. After doing so, a page is shown with 2 sub-menu tabs:
>
> * the first tab is titled **Built-in examples** (this example is used to showcase Using the Charts API).
> * the second tab is titled **Views example**, and is what is created from the new view created during the installation of the charts module. As an alternative to using this tab, just navigate to charts/examples/views in your site. You should then see a column chart and a pie chart, which are followed by a tabular display also. ***Both charts and the table display contain data about the total number of nodes for each of the available content types.***

Visit the Charts demo site for an online preview of these out-of-the-box examples.

Disclosure: I'm the maintainer of this module.

---
Tags: views, charts
---


# Question
Title: Can't find location of files after running drush make
I am creating a drush .make file for a site. I have generated the drush.make file using `drush make-generate` and then updated the file as necessary. I am now trying to use the .make file to create a new site.

To do this I first change to the directory where I wish to install the new site. I then run the command `drush make qmlc.make`. Drush asks me if I want to "Make new site in the current directory? (y/n)". I reply "y" and then drush begins building the site.

The problem is that after the build has finished, the current directory is empty, except for the qmlc.make file.

Why are the files not appearing in the directory? If they are not here, then where are they?

# Answer
Look for errors and warnings in the output of the make command. An empty directory is often the result of an error. This leaves your install directory in the drush temp location (usually `/tmp/drush-xxxx`).

You can add the `--force-complete` argument ignore errors and to copy the directory in to place anyway. But it's probably worth figuring out what the errors are.

`drush make --force-complete qmlc.make`

https://github.com/drush-ops/drush/blob/master/commands/make/make.drush.inc#L58
> 1 votes

---
Tags: drush
---


title: Import xml data

text:
# Question
Title: Import xml data
I am new to drupal. To import xml data into drupal, i followed these steps given in this website which i mentioned it below.

http://www.drupalprogrammer.co.uk/2012/12/use-feeds-module-to-import-xml-data-in.html

After doing all these things, it shows **"There are no new nodes."**

Can any one pls give me an idea or solution to import xml data into drupal 7.26?

# Answer
> 0 votes
Feeds is a very old way to import contents into Drupal. You must use the Migrate module (with Migrate extras) for import all type of contents from some different sources. Read the base migrate documentation (https://drupal.org/migrate) and after that try this: https://drupal.org/node/1152156 This is the better approach for import somethings (the module is integrated in Drupal 8 for its power)

# Answer
> 0 votes
The problem is with the Context, it will be "/Orders/Order", change it and nodes will be imported. This will solve the problem.

---
Tags: nodes, importing-exporting
---


title: Can't create/update resources

text:
# Question
Title: Can't create/update resources
I can't create/update nodes, taxonomy, users, etc., with Drupal Services. I can log in, retrieve system connection info and log out. Also, I can retrieve a node, user (all details), taxonomy term, index, etc. I have read a lot of internet pages like this, and this, but It doesn't work for me. I have used firefox httprequester, firefox restclient, but nothing changed.

Thouse are the problems I have:

* If I send a GET to **http:\< my path \>/node** I get all nodes in `json` format. Good.
* If I send a GET to **http:\< my\_path \>/node/23** I get Status 200 Ok but "\[false\]" returned. The same with .../23.json. But it I put the same url on a browser I get the node in json format.
* If I send a GET to **http:\< my\_path \>/node?parameters\[nid\]=23** Then, I get the full json node.
* If I send a POST to **http:\< my\_path \>/node** with `X-CSRF-token` and with the `json` right data to create a page, I always get 404 error: could not find the controller.
* If I send a PUT to **http:\< my\_path \>/node/23** with `X-CSRF-token` and with the body data to node\[title\]=Prueba, I get 401 unauthorized: Missing required argument entity (but I'm logued in as admin as system/connec.json said).

I have checked all items when I configured the resources page of the service configuration. I'm using Drupal Commerce Kickstart installation.

What could I do? Thanks.

# Answer
> 0 votes
After lot of search and test I have discovered where was the problem. If I enable Universally Unique ID module, I can't create/update entities. If I disable this module, all works good again. So the problem is with this module.

There is another open question about this issue in this link. So I think I should close this. Thanks.

---
Tags: services
---


# Question
Title: additional Social icons in ShareThis module
I am using ShareThis module for social icons. Can anybody please tell me how to add a new social icon not provided by this module? `Flickr`,`Feed` and `Email` icons are not present in the list.

# Answer
> 0 votes
You can do this by using Social Media Links Block module.

> The modules provides a configurable block that display links (icons) to your profiles on various popular networking sites.

For Flicker, use Flicker module.

---
Tags: social-network
---


title: add booking feature in drupal commerce

text:
# Question
Title: add booking feature in drupal commerce
In drupal commerce, I would like to add booking feature if the product is not available for now. If the product is not available for now, I want to allow user to make booking of this product, I also want to reply email to user as soon as the product is available. Does drupal commerce support for booking? Any suggestion, pls!

Thanks

# Answer
> 0 votes
You can try these modules : Commerce Waitlist or Commerce Stock Notifications They allow send notifications if product available again. As for possibility for user to reserve product in stock: without custom module such feature,I think, cannot be realized.

---
Tags: commerce, bookings
---


# Question
Title: Contextual filter by taxonomy term not using language
We have a site with 3 different languages and each language is detected by sub-domain. One of the taxonomies we use is representing types of products and have terms in all 3 languages inside:

```
CategoryQ (se)
   CategoryW (se)

CategoryE (no)
   CategoryR (no)

CategoryT (da)
   CategoryY (da)

```

I faced with problem regarding contextual filters and taxonomy terms. I have view with contextual filter accepting term name and displaying nodes related to this term:

```
Content: Has taxonomy term ID (with depth)

```

Also added validation and "Filter value type" set to "Term name converted to Term ID".

All worked fine until we discovered that we have couple of terms that have same names in all languages (we are not translating terms, all terms are added separately for each language - BL requirement):

```
CategoryG (se)
   CategoryY (se)

CategoryG (no)
   CategoryX (no)

CategoryG (da)
   CategoryZ (da)

```

Processing contextual filter Drupal takes first term tid he found in database (with lowest tid) and use that constructing view's query. In our case Drupal takes SE term instead of NO. So basically there is no language control in contextual filter at all. Is it possible to somehow add this control with hooks or some modules maybe?

# Answer
Temporary solution for was to create patch file to override views module functionality a little bit. Patch can be found under issue on drupal.org https://www.drupal.org/node/2466001#comment-9795191.
> 1 votes

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


# Question
Title: Using a template for a custom admin page made with hook_menu
I have developed a module in Drupal 7.

Now, I want to add a custom themed-page in the admin panel of Drupal.

I have added a page using `admin_menu()`:

```
function newsletter_menu()
{
    $info = array();

    $info['admin/reports/newsletter'] = array(
        "title" => "Number of Registered Users for Newsletter",
        "description" => "",
        "page callback" => "newsletter_admin_content_block",
        'page arguments' => array('newsletter_admin'),
        'access arguments' => array('administer newsletter settings'),
        'type' => MENU_NORMAL_ITEM
    );

    return $info;
}

```

It works all well. But my problem is:

I have a template file `newsletter.admin.tpl.php` which I want to use a the template for this page. But I don't know how should I achieve it. Can anyone help?

# Answer
Have a look at this question on stackoverflow: https://stackoverflow.com/questions/5305114/drupal-7-how-to-load-a-template-file-from-a-module

It basically comes down to this:

1. Implement hook\_theme()
2. Create the template file
3. At the end of your `newsletter_admin_content_block` call `theme()` with your template key (as defined in `hook_theme()`) as first argument and any additional variables that you need in your template as an array.

Example:

```
function hook_theme($existing, $type, $theme, $path) {
  return array(
    'newsletter_admin_content_template' => array(
      'variables' => array('var1' => NULL, 'var2' => NULL, ...),
      'template' => 'newsletter-admin-content-template'
    ),
  ),
}

```

And at the end of your menu callback:

```
return theme('newsletter_admin_content_template', array(
  'var1' => $var1,
  'var2' => $var2,
  ...
));

```
> 2 votes

# Answer
you could try `page--admin--reports--newsletter.tpl.php` (refer to Template Suggestions and Arguments for some more details).

Or just use a `theme_hook_suggestion` (if really needed, with `hook_init()` and `menu_get_item()`).

In any case, be sure to place it in the templates folder of your theme and don't forget to clear the cache.
> 1 votes

---
Tags: 7, routes, theming
---


# Question
Title: How do I get clean output with indented structure
How can I create a clean theming markup so that the output uses the same indented structure as in my static html template? E.g. when I insert $head; Drupal uses it’s indenting format.

How can I control the ouput?

snippet from the html.tpl.php

```
<head>

  <title><?php print $head_title; ?></title>
  <?php print $head; ?>
  <?php print $styles; ?>

</head>

```

The output looks like this

```
<head>

  <title>Lorem Ipsum | mothership</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="Generator" content="Drupal Mothership" />
<link rel="canonical" href="/d7-demo/node/1" />
<link rel="shortlink" href="/d7-demo/node/1" />
  <style media="screen">
@import url("http://localhost/d7-demo/modules/shortcut/shortcut.css?nmdogy");
@import url("http://localhost/d7-demo/modules/toolbar/toolbar.css?nmdogy");
@import url("http://localhost/d7-demo/sites/all/themes/mothership/mothership/css/mothership.css?nmdogy");
@import url("http://localhost/d7-demo/sites/all/themes/itsgoodtobehere/bootstrap/css/bootstrap.min.css?nmdogy");
</style>

</head>

```

instead of

```
<head>

  <title>Lorem Ipsum | mothership</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta name="Generator" content="Drupal Mothership" />
  <link rel="canonical" href="/d7-demo/node/1" />
  <link rel="shortlink" href="/d7-demo/node/1" />
  <style media="screen">
    @import url("http://localhost/d7-demo/modules/shortcut/shortcut.css?nmdogy");
    @import url("http://localhost/d7-demo/modules/toolbar/toolbar.css?nmdogy");
    @import url("http://localhost/d7-demo/sites/all/themes/mothership/mothership/css/mothership.css?nmdogy");
  </style>

</head>

```

# Answer
HTML Tidy can do what you're wanting, but this is designed as text format, Configuration » Content authoring » Text formats which are used in fields rather than the whole site.

Is should be possible with some work to pass the entire theme though HTML Tidy
> 0 votes

---
Tags: theming
---


# Question
Title: Newbie: Using css to style fields in a content type
I created a content type using html elements as fields and groups. The content type configuration page allows me to add classes (and id attributes) to the elements; however, they don't show up in the generated html when I view page source in a browser.

I gather from Add a CSS class to field in content type that I must modify php functions to actually include the classes in the output css; however, I'm a newbie and don't really understand the post. It refers to a blog post which is no longer available.

I can't find the function ( *theme\_*field ) in any of my template.php files. Can someone help clarify this for me. How can I get my own classes into drupal output.

Thanks.

# Answer
There is a much easier way, but is still complicated if you're a newbie. Install the Display Suite module and enable Display Suite & Display Suite UI

Go to Structure -\> Display Suite -\> CSS classes. Add as many CSS classes for fields as necessary. Go to Structure -\> Content types -\> \[xxx\] -\> Manage Display and you should be able to put the classes you have defined against each of the fields.
> 0 votes

# Answer
You can also define Theme Hook Suggestion. In this way, not only you can define css classes for the fields, but also display them in any html format. This is the way you should do it:

If the content type is for example `CT`, in `template.php` create `YourThemeName_preprocess_node(&$variables)` function.

check the following condition:

```
if($variables['node']->type == "CT"){
}

```

In this way you check what the content type is. Now define the theme hook suggestion, like this:

```
if($variables['node']->type == "CT"){
   $suggest = "page__node__CT";
   $variables['theme_hook_suggestions'][] = $suggest;
}

```

create a file in the your theme directory next to the `.info` file and rename it to `page--node--CT.tpl.php`. to see it works, open this file in an editor and put this code:

```
<?php print "hello world";?>

```

Clear the cache and open a node of `CT` content type to see if it prints `hello world` in the region of `$page['content']` of `page.tpl.php`

Now install entity module. Suppose the fields of `CT` content type is `field_CT_field1` and `field_CT_field2`, then write :

```
if($variables['node']->type == "CT"){
   $suggest = "page__node__CT";
   $variables['theme_hook_suggestions'][] = $suggest;
   $wrapper = entity_metadata_wrapper('node',$variables['node']);
   $variables['field1'] = $wrapper->field_CT_field1->value();
   $variables['field2'] = $wrapper->field_CT_field2->value();
}

```

Now in `page--node--CT.tpl.php` you can use `$field1` and `$field2` as the value of the node fields and put them in any html element and assign them any css class.
> 0 votes

---
Tags: entities, theming
---


# Question
Title: Why drupal need hidden option in comment settings of content types?
In content type setting in drupal, we have tab comment setting .The comment setting on future content of this type will default to:

* **Hidden:** No comments are allowed, and past comments are hidden.
* Closed: No comments are allowed, but any past comments remain visible.
* Open: Any future content of this type is open to new comments.

**Why do we need HIDDEN option?** It does not make sense in content type setting . If we set this option - in any new nodes that will be created next - comment will be closed.

This option has sense only in particular material, if it has comments.

Please explain me why this option need in content type settings?

Thanks...

# Answer
> 0 votes
> This option has sense only in particular material, if it has comments.

Precisely. So you should use this option when a content type has comments that you don't want to delete, but don't want to allow people to see either permanently or temporarily.

If you don't need that option, you don't need to use it. But its existence makes perfect sense.

# Answer
> 0 votes
This option(if it set in content type settings) work only for new materias. Only! So when a create node, in comment settings of this node, will be option CLOSE. Because no comments were added. And only if I add some comments for it, status HIde for comments were added. ( But in order to add this some comments, I will have to change the comment option to OPEN ) So this option does not make sense in content type setting

---
Tags: comments
---


# Question
Title: Copying multiple components from another webform?
I have a bunch of webforms, threre are a lot of repeating fields just in different order or with different conditionals / labels. I want some plugin that would allow me to copy elements from existing webform to new one.

Is there such thing?

# Answer
> 0 votes
You can use Webform Template:

This module allows to easily copy webform configuration from one node to another (including all webform fields). If I remember well it copies all fields, you can't select wich fields to copy.

I've used it and worked fine.

EDIT: Adding more info:

The module doesn't allow you select which fields are going to be copied. Anyway, the module's code not long and it may be easy to add this funcionality. The module also triggers some cusom hook to modify webform (hook\_webform\_template\_insert and hook\_webform\_template\_update).

I think this would be a good starting point.

The heavy lifting seems to be done in the webform\_template\_node\_update (hook\_node\_update).

```
// Insert the components into the database.
if (isset($node->webform['components']) && !empty($node->webform['components'])) {
  foreach ($node->webform['components'] as $cid => $component) {
    $component['nid'] = $node->nid;
    webform_component_insert($component);
  }
}

// Insert emails.
if (isset($node->webform['emails']) && !empty($node->webform['emails'])) {
  foreach ($node->webform['emails'] as $eid => $email) {
    $email['nid'] = $node->nid;
    webform_email_insert($email);
  }
}

```

# Answer
> 0 votes
You may want to try the Node clone module

> The clone module allows users to make a copy of an existing item of site content (a node) and then edit that copy. The authorship is set to the current user, the menu and url aliases are reset, and the words "Clone of" are inserted into the title to remind you that you are not editing the original content.

---
Tags: webforms
---


# Question
Title: Exposed form in block not found in block view drupal 7
I am facing an issue what I need is expose some fields for search criteria & put these search boxes/drop downs to my sidebar, I didn't find the option "expose from in block" in the Exposed Form section, I have a block view, It is showing on the view page but not on the block view why?

Is there any solution regarding? Thanks

# Answer
Have a look at the Views Block Exposed Filter Blocks module.

Views normally restricts exposed form blocks to page displays. So if you want an exposed form for a block display you either have to go with this module or you build your own block in code and embed the exposed form there.
> 2 votes

---
Tags: views, blocks
---


title: Editable message after registeration

text:
# Question
Title: Editable message after registeration
is there a way to make this message controllable from back end which appear after user registration.

```
   $message = t("Thank you for registering at $site_name. Your application for an account is currently pending approval.<br/> Once it has been approved, you will receive another e-mail containing information about how to log in, set your password, and other details.");

```

because it contains HTML it can't be done by string override.

# Answer
> 0 votes
Anything inside a t() function can be overridden, you need to paste the exact contents into String overrides in settings.php or use the String Overrides module

# Answer
> 0 votes
Use hook\_user\_insert in your custom module

```
function mymodule_user_insert(&$edit, $account, $category){
    drupal_set_message(t('Message'));
}

```

# Answer
> 0 votes
You didn't say what version of Drupal you're using; this answer pertains to 7.x =^)

go to `configuration -> people -> account settings`. There is a space at the bottom for customizing emails:

Edit -- unless you meant doing it programatically, in which case @Abdelouahed\_Siyagh's answer is, of course, more appropriate

# Answer
> 0 votes
I figured out the reason, because the message contains variable `$site_name`, so should replace it the value of it in the string override module like this:

> Thank you for registering at mySiteName. Your application for an account is currently pending approval.
> Once it has been approved, you will receive another e-mail containing information about how to log in, set your password, and other details.

---
Tags: users, string-overrides, authentication-authorization
---


title: Install drupal under subfolder

text:
# Question
Title: Install drupal under subfolder
I'm using a 3rd party hosting service for a Drupal 7 installation, and would like to put my Drupal site under the public\_html folder like this:

```
public_html
|
|
|---->mysite
       |
       |-->includes
       |-->misc
       |-->modules
       |-->profiles
       |-->scripts
       |-->sites

```

However, I'm not sure what settings.php values I need to set, nor what if any .htaccess settings need to be changed?

# Answer
> 2 votes
You should be fine. You will probably need to change the

```
$base_url = 'http://my-path/subdir';

```

in your settings.php so that drupal is aware of it. Also in your .htaccess you will see

```
RewriteBase /drupal

```

that is commented out. Uncomment this and add your path

---
Tags: installation
---