# Question
Title: How to show the body field in a custom template?
I'm stuck with this problem. In the following code, I want to replace the "field\_portfolio\_categories" by the "body field" in a custom tpl file.

```
<div class="portfolio-description">
    <h3 class="name"><?php print $title; ?></h3>
    <?php print render($content['field_portfolio_categories']); ?>
</div>

```

So I change it to:

```
   <div class="portfolio-description">
        <h3 class="name"><?php print $title; ?></h3>
        <div><?php print $body; ?></div>
    </div>

```

In the node, instead of body content, I see "Array"
And this is the error message:

*Notice : Array to string conversion in include() (ligne 41...*

Any idea what's wrong?

Here is the complete template code:

```
    <?php
// We hide the comments and links now so that we can render them later.
hide($content['comments']);
hide($content['links']);
hide($content['body']);
//$original_image = file_create_url($node->field_portfolio_images['und'][0]['uri']);
$lightboxrel = 'portfolio_' . $nid;
$portfolio_images = field_get_items('node', $node, 'field_image');
$first_image = '';
if ($portfolio_images) {
  foreach ($portfolio_images as $k => $portfolio_image) {
    if ($k == 0) {
      $first_image = file_create_url($portfolio_image['uri']);
    } else {
      $image_path = file_create_url($portfolio_image['uri']);
      print '<a href="' . $image_path . '" rel="prettyPhoto[' . $lightboxrel . ']" style="display:none"> </a>';
    }
  }
}
?>
<div id="node-<?php print $node->nid; ?>" class="portfolio-text <?php print $classes; ?> clearfix"<?php print $attributes; ?>>
<?php print render($title_prefix); ?>
<?php print render($title_suffix); ?>
<div class="ImageWrapper content"<?php print $content_attributes; ?>>
    <div class="portfolio-images">
        <?php print render($content['field_image']); ?>
    </div>
    <div class="ImageOverlayLi"></div>
    <div class="portfolio-overlay">
        <div class="portfolio-inner">
            <div class="portfolio-info">
                <div class="portfolio-tools">
                   <a href="<?php print $first_image;?>" rel="prettyPhoto[<?php print $lightboxrel;?>]" data-toggle="tooltip" data-original-title="<?php print t('View Image');?>" data-placement="bottom" class="zoom dtooltip"><span class="fa fa-expand"></span></a>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="portfolio-description">
    <h3 class="name"><?php print $title; ?></h3>
    <?php print_r($content['body']); ?>
    <?php //print render($content['body']); ?>
</div>
<?php //print render($content['links']); ?>
<?php //print render($content['comments']); ?>

```

# Answer
> -1 votes
The "problem" comes from manage display. Besides the default tab, there are 3 other tabs where I can click to show/hide fields. In order to see the body text, I had to click on *Teaser text* and show the body tag.

# Answer
> 3 votes
Your code should be:

```
    <?php
// We hide the comments and links now so that we can render them later.
hide($content['comments']);
hide($content['links']);
//$original_image = file_create_url($node->field_portfolio_images['und'][0]['uri']);
$lightboxrel = 'portfolio_' . $nid;
$portfolio_images = field_get_items('node', $node, 'field_image');
$first_image = '';
if ($portfolio_images) {
  foreach ($portfolio_images as $k => $portfolio_image) {
    if ($k == 0) {
      $first_image = file_create_url($portfolio_image['uri']);
    } else {
      $image_path = file_create_url($portfolio_image['uri']);
      print '<a href="' . $image_path . '" rel="prettyPhoto[' . $lightboxrel . ']" style="display:none"> </a>';
    }
  }
}
?>
<div id="node-<?php print $node->nid; ?>" class="portfolio-text <?php print $classes; ?> clearfix"<?php print $attributes; ?>>
<?php print render($title_prefix); ?>
<?php print render($title_suffix); ?>
<div class="ImageWrapper content"<?php print $content_attributes; ?>>
    <div class="portfolio-images">
        <?php print render($content['field_image']); ?>
    </div>
    <div class="ImageOverlayLi"></div>
    <div class="portfolio-overlay">
        <div class="portfolio-inner">
            <div class="portfolio-info">
                <div class="portfolio-tools">
                   <a href="<?php print $first_image;?>" rel="prettyPhoto[<?php print $lightboxrel;?>]" data-toggle="tooltip" data-original-title="<?php print t('View Image');?>" data-placement="bottom" class="zoom dtooltip"><span class="fa fa-expand"></span></a>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="portfolio-description">
    <h3 class="name"><?php print $title; ?></h3>
    <?php print render($content['body']); ?>
</div>
<?php //print render($content['links']); ?>
<?php //print render($content['comments']); ?>

```

---
Tags: theming
---


# Question
Title: got a Parse error webform.install in drupal 7
Hello guys i have got an parse error Parse error: syntax error, unexpected T\_FUNCTION in /sites/all/modules/webform.install on line 1917 what i suppose to do please help me out this trouble. Due to this i am hot able to install any module or access my site.

# Answer
It's a bug in eAccelerator, which has been (apparently) been fixed. Webform requires PHP 5.3. The affected version of eAccelerator doesn't support all of PHP 5.3 -- specifically anonymous functions.

eAccelerator is not a "default setting" of a server. It is add-on software (presumably added by a host company, and not kept up-to-date).

you can follow this link on drupal website which touch the same issue
> 1 votes

# Answer
Someone/something has inserted a syntax error in the webform.install file. If the webform module isn't installed, remove it and download a new version that doesn't have the syntax error.
> 0 votes

---
Tags: webforms
---


# Question
Title: Searching way to **not** send mail after user registration
I want user from a certain domain to be able to register without approval, while others need te be approved by a user manager.

I defined a rule that after a new user registers, through text comparison on the user's mail address, checking if it is from the "safe" domain, unblocks the user. This works very well, but Drupal will send both the mails: \- welcome, pending approval and \- your account has been approved.

Is there a way to achieve that the welcome, pending approval mail is not sent?

Is there a way using rules where you can rule out Drupal actions, like saying: "When this happens, do not take that action?"

# Answer
> 1 votes
Mailcontrol worked like a charm. If you are looking for the configuration it is right with the Drupal user configuration.

it provides the necessary UI additions for D7 (and D8) to enable site admins to enable/disable any standard Drupal mail

---
Tags: rules, users
---


# Question
Title: Cross browser Issue with Drupal Bootstrap Navigation
I have a website that I am created for my company (Drupal & Bootstrap 3) and am having some trouble making the navigation work in all browsers. Essentially, there are two menu's that I am using in order to make this work. The default Drupal menu is supposed to be shown in XS and SM screen sizes and the Superfish menu with dropdown/hover support is supposed to show on MD and LG screen sizes. I have been able to make this work through CSS (Display:none) in Chrome, Firefox, and Edge browsers. However, when I try to use the website in Internet Explorer both menu's are showing up and at the MD screen size and as the viewport shrinks.. something is happening that I cannot figure out.

Can someone please take a look and let me know what they think? I am desperate and after many hours cannot find a solution. The link to the website is www.collegebodybuilding.net/grazzini\_bootstrap. Any suggestions for the proper way of doing this would be greatly appreciated as well (I realize this is probably a mess and not the right way of doing things).

# Answer
Do you have html5shiv and respond.js included for IE8 as recommended???

There's a whole section of bootstrap's getting started docs for IE8

you can follow the link from here
> 0 votes

---
Tags: theming, navigation
---


title: Drupal csv file not readable

text:
# Question
Title: Drupal csv file not readable
I have a module which reads in csv file and adds records to the database. It is working properly on localhost. I am able to upload the file and read and then display the result. But, on my server, i am able to upload the file but this piece of code fails, while reading the file.

```
 $file_handle = fopen($file_url, "r");
 while (!feof($file_handle) ) {
 $line_of_text = fgetcsv($file_handle, 1024);
 print_r($line_of_text);
}

```

I realized that it might be a permission issue so , i checked that folder has got 0777 permission where as i am not able to give recursive permission to files, files have permission of 0664. and i get access denied when i try to give it different permission, i am on ubuntu server. After i checked

```
 $file_handle = fopen($file_url, "r");
 var_dump($file_handle);

```

On localhost i got: resource(90, stream), whereas on my server i got bool(false).

# Answer
Node Import, and Feeds are two solutions I've used recently to import content. they may work with while you maintion that your module read from csv and store in DB
> 0 votes

---
Tags: files
---


# Question
Title: What are the alternatives to print() and print_r() for debugging purposes?
I'm working on some code for a custom Drupal 7 module the problem is I'm dealing with many arrays and strings. I have tried to use `print()`, and `print_r()` to output values so I can see what I'm working with, but nothing is printed to the screen.

Is Drupal 7 preventing this from happening? How do other Drupal 7 module developers output values?

For example, in JavaScript I can use `console.log()`; in plain PHP, I would normally use `print()`, `print_r()`, and `echo`.

# Answer
> 5 votes
It's the same as in other PHP applications with separate V layer - `print` and `print_r`, being directly PHP functions, don't know about anything in View layer of Drupal application. They cannot pass their output to theming chain, cache systems in place and so on. That said, they often works, but that's more a coincidence.

For array inspection, you should either use xdebug or, if you don't have time, patience or skill to set it up, use Devel module. Specifically, `dpm`, `dvm`, `dpr` and `dvr` functions will be useful for you. See this helpful demo page for details of their use.

TL;DR: Install Devel, replace `print` and `print_r()` calls with `dvm()`. Profit.

# Answer
> 0 votes
print() and echo() are not good for debugging, they are like the document.write() equivalent.

print\_r() is like the console.log() equivalent. I prefer to use var\_dump() as the output formatting is much better, providing HTML Error Display is turned on in the php.ini file.

To test if the PHP execution is getting to the place where you are debugging put in a die() after the print\_r():

```
print_r($your_variable); die('123');

```

Now check if you see '123' on the screen. If the execution stops it's good because you know your debugging code is executing.

You can also install the devel module to use dvm() or dpm(), the difference between them is the formatting. dvm() is formatted similar to print\_r() and dpm uses krumo formatting (if that option is set in the Devel settings). These functions will print out in the $messages variable, so make sure the theme's page.tpl file is printing $messages.

If nothing is printed on the screen after a print\_r() it could be a number of reasons, here's 2 common reasons I have experienced.

1. There is a PHP error and your php.ini file is set so no errors are displayed. (blank white screen).
2. If the site renders but your debugging code is not displayed, it's possible your code is not included in the execution of the page you refreshed.

# Answer
> 0 votes
What I managed to get working was using: `drupal_set_message();` I couldn't get `dpm()`, `dvm()`, or `dpr()` to work after installing the `Devel contrib module`. I was able to print out a variable using `die()` but this also stops all execution and makes Drupal unusable during the test so is not desirable.

If anyone has a better solution please let me know and ill pick the better answer but so far `drupal_set_message();` is the only thing that is working.

I have some json data that i'm currently testing and found the best way to work with it is:

```
$data = json_decode($rawData,true);
foreach($data as $key => $val){
   drupal_set_message($key." = ".$val);
}

```

This way i was able to see each level of the json data and work on one part of it at a time. There must be a more effective way to see complex data as your building a module.

---
Tags: 7
---


# Question
Title: In which table in the database are the email messages stored?
I would like to know what the table the email messages (Emails section at admin/config/people/accounts) are stored in?

Config: Drupal 7

Any help is appreciated.

# Answer
> 2 votes
They are stored as system variables in the `{variable}` table, and normally accessed with `variable_get()` and `variable_set()`. The variable names are

* `user_mail_cancel_confirm_body`
* `user_mail_cancel_confirm_subject`
* `user_mail_password_reset_body`
* `user_mail_password_reset_subject`
* `user_mail_register_admin_created_body`
* `user_mail_register_admin_created_subject`
* `user_mail_register_no_approval_required_body`
* `user_mail_register_no_approval_required_subject`
* `user_mail_register_pending_approval_body`
* `user_mail_register_pending_approval_subject`
* `user_mail_status_activated_body`
* `user_mail_status_activated_notify`
* `user_mail_status_activated_subject`
* `user_mail_status_blocked_body`
* `user_mail_status_blocked_notify`
* `user_mail_status_blocked_subject`
* `user_mail_status_canceled_body`
* `user_mail_status_canceled_notify`
* `user_mail_status_canceled_subject`

Look at the code for `user_admin_settings()`, which is a standard system settings form and has the variable names in it, and `_user_mail_text()` which has all of the default text.

---
Tags: 7, emails
---


title: Do default emails support HTML?

text:
# Question
Title: Do default emails support HTML?
I haven't got around to sending user emails yet.

I wonder if we are able to send HTML emails by default from the Emails section (admin/config/people/accounts), or if we need to use modules for this.

# Answer
> 6 votes
Out of the box (w/ core modules only) default account emails (and any other emails) that Drupal generates do not support HTML. Drupal converts all html emails to plain text before sending. You can install and configure MimeMail module and its dependencies. Then you'll be able to insert html markup into the account email body field at 'admin/config/people/accounts' and have those emails sent properly in html.

---
Tags: 7, emails
---


title: Why is settings.php in the web folder?

text:
# Question
Title: Why is settings.php in the web folder?
In the default installation, settings.php is located at `sites/default/`. There are no recommendations in the official Drupal website about changing the location of this file. Doesn't it pose a potential problem of security? I have seen Apache webservers *eventually* failing to interpret PHP files, and serving the content of the PHP file in pure plain/text format, instead of the supposed HTML content. That would completely expose the database connection user and password, which is not even encrypted. Why does it work this way?

# Answer
You are absolutely correct. I know for a fact that many developers/sysadmins do not take the risk that the PHP interpreter might fail at some point, and include the db password (and other sensitive data like API keys) from a file outside the webserver's docroot.

I'm surprised that this is not documented as a best practice anywhere - at least I couldn't find it on drupal.org either. I have no information why it works the way it does.
> 6 votes

# Answer
On some providers this sensitive connection string is stored external to the web root (i.e., getpantheon.com) You can always create some symbolic links instead of storing directly in /sites/default folder.
> 0 votes

---
Tags: 7, database, security, configuration
---


title: In-place Views block field edits

text:
# Question
Title: In-place Views block field edits
I have a Views block showing the profile of a user. I would like to make it look like so:

where there is a button next to some of the changeable fields, when clicked will make the field value a textbox, where the user can update it.

How can I achieve this with Drupal?

Config: Drupal 7, Bartik theme.

Any help is appreciated.

# Answer
> 1 votes
It is difficult to have such functionality working with views generated fields. Solutions that are close to this functionality are available but may not provide acceptable UX.

For Views you can check out Editable Views and Edit Views modules.

You can also try Quick Edit module, but you will have to give up rendering your fields w/ Views, as it doesn't support fields generated by Views now and not sure if it will.

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


# Question
Title: Add new user via Commerce or Add User account
I am working with a community site where new members should be able become members by purchasing an annual membership using commerce\_license. I see 2 ways forward:

1. Members add an account application via the page .../?q=user/register and the user fills in all required fields. Via rules the appropriate membership is added, the user is redirected to the checkout, and when payment is complete the role is applied.
2. User buys the appropriate membership product, and when paid in full receives the correct role.

I have tested both these but cannot seem to get the second option working since I don't have a way to expose the custom fields added to the users, and let the user fill in those when applying for membership.

The first option seems more promising but there the user is not permitted access to the checkout page when redirected ( although I can see that the basket is created with the matching product in it).

Any pointers on how to move forward is much appreciated. I will not require an approval step, except that the membership fee must be paid in full to get access.

BR /bo

# Answer
> 0 votes
You can add all necessary profile fields to user register form, and disallow checkout to anonymous users. This way every time new user proceeds to checkout' they are redirected to register form where they fill in the info and then proceed with checkout as usual.

A good helper module for this is Commerce Checkout Redirect

> This module redirects anonymous users to a page where they can login or create a new account when they try to checkout.

---
Tags: commerce, users
---


title: Switching from Panopoly

text:
# Question
Title: Switching from Panopoly
I'm wondering if anyone has experience switching a Drupal installation away from Panopoly. I have a site built on Panopoly, but I'm finding the upgrade situation stifling. I'd rather have independent control of which modules are installed. So I'm looking to move to a vanilla core installation and do all the modules by hand. Anyone with firsthand experience doing this? I'm just going to give it a whirl and see how it goes, but any tips would be appreciated. Thanks!

# Answer
> 1 votes
You can use Profile Switcher

> Used to switch between install profiles found in /profile directory. This module is useful for moving an existing site to distribution.

I had the same problem last year you can check it out at - Changing from a Profile to Standard profile after the installation

---
Tags: distributions
---


# Question
Title: How do I include the main navigation block twice?
How can I put one block, for example the main navigation block, in two different regions. In Drupal 7 this was possible through the Menu Block module, but as this module won't be ported to Drupal 8, I guess there is an other method.

# Answer
> 6 votes
This functionality is present out of the box in Drupal 8. You can actually place the same block multiple times in different regions.

For adding a block multiple times:

1. Go to Admin -\> Structure -\> Block layout (/admin/structure/block).
2. Click on "Place block" button besides the region name.
3. Select any block you wish to add to that region.

Follow the same steps to add block to a different region.

---
Tags: 8, blocks
---


# Question
Title: Showing popup after user registration using the "Popup message" module
How do I show a popup to a user after he/she has registered, using the **Popup message** module?

# Answer
Not with Popup message but this will work:

Install Rules, then create a rule with the following settings:

* React on event: After saving a new user account
* Actions: Show a message on the site (your message)

Drupal will show your message as a system message.
> 3 votes

---
Tags: 7, users, javascript
---


# Question
Title: Attaching CKEditor to E-mails subject and body?
I have installed **Mime Mail** and am looking at formatting my emails (at admin/config/people/accounts) before sending them to users. How do I attach **CKEditor** to the E-mail subject and body sections?

Cheers

# Answer
> 0 votes
Looks like there is no any way to attach it. I used only html tags to format this notifications and their subjects.

---
Tags: wysiwyg, emails
---


# Question
Title: Making a block to show the status of the user account?
How do I use a Views block (or other means) to show the status of the user account, specifically awaiting approval, approved, and not approved ?

# Answer
Pending User Notification Block

> This module is for sites that allow users to create an account, but require administrator approval for account activation. This module creates a block that shows a list of unactivated user accounts, with links to their account pages. This block is visible for anyone with 'administer users' permission, and will not be shown to any other users.
> 1 votes

---
Tags: users
---


# Question
Title: Benefit of loading JavaScript in template.php rather than the theme info file?
The title says it all really. Whats the benefit of loading JavaScript files in the template.php file over the theme info file?

For the sake of simplicity lets assume there is no condition to them being loaded. As a themer my instinct is to want to load things with the info file, but this isnt the standard practice on my current project.

# Answer
No real advantages.

There are two reasons to add Javascript : to make some elements work, or to make them look cool.

# JS to make something work

These should be `#attached` to the element they make work. Preferably in the module that created said element. Or they may be written in unobtrusive way and put in info file of this module. Either way, they should **never be put in theme**, makes no sense to have them there. So these should be out of your question's scope.

# Eye candy

These belong to theme all right. And because they do, they shouldn't depend on any script that's in module. If you have a rare situation when they do, then you need to add them in PHP for conditionals that'll cache and not waste browser's resources. But you told no conditions, so this is moot. Or should be, if your theme just assumes presence of modules without checking you have serious bug there, problems waiting to happen.

Having them added in PHP allows some reordering etc. In my experience it was always easier to write my JS in a way that didn't require this. Drupal Behaviors are good for this. If for some reason you can't write your scripts in order independent way, ie you have to use external scripts or have no time for rewrite, then `#attached` is the way to go.

Other "advantage" would be to attach them only to elements that are supposed to get their cool effects. But this rarely is an advantage. If all you need is to make sure JS is included, include it always. Better for caching and it'll act only on elements with specific id or class anyway, no real harm for browser. **Exception here** is when you need to take some php variables and make them avaliable to Javascript. Then info file will obviously not suffice and you need to add it via php.

# TL;DR

Your intuition is generally good.
> 1 votes

# Answer
module.info loads it for all pages unlike template.php where you can specify when and to what page you want to display it.
> 0 votes

# Answer
The only benefits I can think of by using the drupal\_add\_js() function in template.php is you can set a weight/scope to load the file in a different order if you wanted to, or load it with a scope group or you can load the file from a different location outside of your theme if you wanted to. Other than that I don't see any other benefits.

More about drupal\_add\_js
> 0 votes

---
Tags: theming
---


title: Adding a tab to the login page

text:
# Question
Title: Adding a tab to the login page
On the Login page, there are 3 tabs i.e. "Create new account", "Log in", and "Request new password". Are there modules out there that let us add more? If not, how can I achieve this manually?

Cheers

# Answer
> 4 votes
You can use hook\_menu with type as 'MENU\_LOCAL\_TASK'. So that your menu path will be like 'user/your\_path'.

Ex:

`function my_module_menu($items) {
 $items['user/my-path] = array(
 'title' => 'Some title'
 'page callback => 'your callback',
 'type' => MENU_LOCAL_TASK,
 );
 return $items;
}`

If you are using views to print this page, you can set menu as Menu tab in path options.

---
Tags: 7
---


# Question
Title: How do you restrict specific content types per user role
I'm trying to restrict specific content types per user role so that some users can only edit certain content. I've tried configuring content access module but can't seem to restrict content types.

# Answer
> 1 votes
You can set the permissions for each content type and role with Drupals default permissions.

Go to */admin/people/permissions* there is a section called *Node* where you can set the individual permissions for each content type:

* Create new content
* Edit own content
* Edit any content
* Delete own content
* Delete any content

Keep in mind that the permission *Bypass content access control* overrides the access restrictions of the individual content types. So if a role has this permission, the user can view, edit and delete all content.

# Answer
> 0 votes
You do it by using Rules module:

1. Add a rule when user view nodes
2. Select content type where you want to view content for specific user role
3. In action add component or action to redirection i.e 301 user or show message Access denied

---
Tags: users
---


# Question
Title: In which template file is the create new account/log in/request new password page rendered?
I would like to not render the request new password tab (/user/password), when I am not the log in page (/user). In which template file does drupal get told to render the create new account/log in/request new password page? Drupal 7, Bartik.

# Answer
> 3 votes
They are just menus. You can find those menus and their page callback in drupal core user module at hook\_menu section.

---
Tags: theming
---


# Question
Title: Is there a way to inherit a Drupal installation profile?
I want to create a Drupal installation profile based on an existing one. Is there a way to inherit the parent profile so I don't need to duplicate modules, dependencies, libraries definitions ?

# Answer
Doing some research and testing I found a way to inherit Drupal installation profiles, using drush make (works in Drupal 7).

1) Apply Drupal patch #47 submitted in this topic

```
projects[drupal][type] = core
projects[drupal][version] = 7.32
projects[drupal][patch][] = https://www.drupal.org/files/issues/drupal-inheritable-profiles-2067229-47.patch

```

2) Set Drupal "base profile" in your **profile.info** file. My installation profile will be based in Guardr

```
name = MyProfile
description = MyProfile
version = 7.x-1.0
core = 7.x
base profile = guardr

```

3) Execute with Drush the make file of your base profile. Add it to your **profile.make**:

```
projects[guardr][type] = profile
projects[guardr][download][type] = git
projects[guardr][download][url] = "git://git.drupal.org/project/guardr.git"
projects[guardr][download][branch] = "7.x-1.14"

```

drush will download it and then recursively run the make file of the base profile

I found the reference in this blog post
> 8 votes

# Answer
To the best of my knowledge, core doesn't provide this functionality.

Profiler might be what you need.

> Profiler allows you to quickly and easily create new install profiles, as well as have 'Sub' Install Profiles, where one Install Profile inherits from and extends another Install Profile.
> 1 votes

# Answer
You might install https://www.drupal.org/project/protocol distribution because this allow your profile to inherit parent profile.
> 0 votes

---
Tags: installation-profiles
---


# Question
Title: How to filter content on a view page using cookies?
I'm developing a website where users access the content without registration but it still needs to have a favorites system for the elements on the web. Right now I have implemented a system where i can add items to a "favorites" and the node id for every item is saved on a cookie. Is there a way to filter the items that are shown by a view page using this node ids saved on the cookies?

I thought that it can be done by altering the query sent by the view or by aplying a filter in some point of the process where i check whether the element returned by the view corresponds with the node id saved in the cookie.

Is any of this options feasible? Is there a simpler way to focus this problem?

# Answer
A better way to tackle your problem might be the Flag module.

It also has a good views integration and is quite easy to set up.

Just add a "favorites" flag and set it as private flag, so every user can have its own favorites.

On your favorites-view set your filter criteria to match the flag and you are good to go.
> 0 votes

---
Tags: views, cookies
---


title: how to add mysqli driver to drupal 8?

text:
# Question
Title: how to add mysqli driver to drupal 8?
```
$databases['default']['default'] = array (
  'database' => 'baba',
  'username' => 'abab',
  'password' => 'abcbc@',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

$databases['abcb']['default'] = array (
  'database' => 'ababc',
  'username' => 'abcb',
  'password' => 'Sabbs',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'driver' => 'mysqli',
);

```

We have mysql, pgsql and sqlite driver but I wanted to integrate a mysqli driver in drupal ? How can I achieve it or fetch table from mysqli database in mysql database ?

# Answer
> 5 votes
Drupal 8 uses PDO, so I think mysqli is not supported.

From the documentation:

> Drupal's database abstraction layer provides a unified database query API that can query different underlying databases. It is built upon PHP's PDO (PHP Data Objects) database API, and inherits much of its syntax and semantics.

---
Tags: 8, configuration
---


# Question
Title: What is the difference between the various log messaging severity levels?
There are several types of log messaging severity levels - emergency, critical, error, alert, info, notice, warning, debug. What does each level mean? Example, emergency and critical sound similar, what's the difference? Also, info and notice sound similar.

# Answer
> 4 votes
The code is the best manual :)

```
/**
 * Log message severity -- Emergency: system is unusable.
 */
define('WATCHDOG_EMERGENCY', 0);
/**
 * Log message severity -- Alert: action must be taken immediately.
 */
define('WATCHDOG_ALERT', 1);
/**
 * Log message severity -- Critical conditions.
 */
define('WATCHDOG_CRITICAL', 2);
/**
 * Log message severity -- Error conditions.
 */
define('WATCHDOG_ERROR', 3);
/**
 * Log message severity -- Warning conditions.
 */
define('WATCHDOG_WARNING', 4);
/**
 * Log message severity -- Normal but significant conditions.
 */
define('WATCHDOG_NOTICE', 5);
/**
 * Log message severity -- Informational messages.
 */
define('WATCHDOG_INFO', 6);
/**
 * Log message severity -- Debug-level messages.
 */
define('WATCHDOG_DEBUG', 7);

```

# Answer
> 3 votes
The levels are mostly arbitrary below **alert**, and just represent a general priority of "badness".

In theory, a minimum log level could be set up in core, so that you could enable logging on a live site, but only have certain levels logged (say, emergency, critical, error, and alert) and the rest ignored. To my knowledge, this hasn't been implemented (I would *love* to be shown wrong about this).

The current usage has more to do with filtering on the recent log messages page (admin/reports/dblog).

---
Tags: 7, debugging
---


# Question
Title: Add an item among those displayed in a Views block that links to the item creation page
**The goal:**

How do I add the "Add new project" item as the first among the other projects shown in the Views block? The content would link to the project creation page (node/add/project) ?

Please suggest other methods/alternatives if this is not feasible.

# Answer
> 0 votes
Add a header to the view and style it to fit your needs.

You can chose between *rendered entity: custom menu link* or just add a *textarea* and enter your link. The first option might be better because it provides an access check.

You might need to customize some of the fields HTML within the fields style settings to make this work.

---
Tags: views
---


# Question
Title: Show the logged in user their account status
How do I make a Views block(or by other means) to let the user who is logged in know of their account status i.e. when it is awaiting approval, or was not approved?

# Answer
A user that has not been approved by the admin can not login as far as I know.
> 1 votes

---
Tags: views, users
---


# Question
Title: Add a class to all the blocks in a region
I'm theming a Drupal 7 site and I'd like to add a class to all the blocks in a given region using preprocess\_block().

I think this should work, but it doesn't seem to:

```
function MYTHEME_preprocess_block(&$variables) {
        // Other stuff in this function
        $variables['title_attributes_array']['class'][] = 'title';
        $variables['classes_array'][]='clearfix';

        // Now I want to add a 'col-md-4' class to all the blocks in the 'bottom-content' region
        if($variables['block']->region == 'bottom-content') {
                $variables['classes_array'][]='col-md-4';
        }
}

```

Any ideas why this isn't working?

# Answer
> 0 votes
As manikandan kannan is saying, you probably have the name of the region wrong. It probably is: `'content_bottom'`

So your if-statement would become:

```
if($variables['block']->region == 'content_bottom') { ...

```

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


title: Create path alias to a custom link

text:
# Question
Title: Create path alias to a custom link
I have a taxonomy term that has its own template, inside that template, there is custom links that just add a new argument to the URL for example the current path is `/taxonomy/term/%`, one of the custom links will send the user to `/taxonomy/term/%/%`

with pathauto the url alias changes only when I visit `/taxonomy/term/%` (vocab\_name/term\_name), but it won't changed when I vist `/taxonomy/term/%/%`. I want it like that : vocab\_name/term\_name/%.

Is that possible ? thanks in advance.

# Answer
> 0 votes
Check path\_alias\_xt and subpathauto, I have used *subpathauto* to achieve this for nodes and *path\_alias\_xt* documentation says it does for taxonomy terms too.

---
Tags: 7, taxonomy-terms, path-aliases
---


title: Render form with ajax submit

text:
# Question
Title: Render form with ajax submit
I have a custom form in a module, similar to this example:

```
function mymodule_form($form, &$form_state) {
   $radio_options = array(...);
   $form = array();
   $form["wrapper"] = array("#markup" => "<div id='test-ajax'></div>");
   $form['choice'] = array(
       '#title' => '',
       '#type' => 'radios',
       '#options' => $radio_options,
   );
   $form['submit'] = array(
       '#type' => 'submit',
       '#value' => t('Vote'),
       '#ajax' => array(
           'callback' => 'demo_form_ajax_submit',
           'wrapper' => "test-ajax",
           'method' => 'replace',
           'effect' => 'fade',
       ),
   );
   return $form;
}

function demo_form_ajax_submit($form, $form_state) {
   var_dump("something");
}

```

And I'm printing that form in template like this:

```
<div class='row'>
   <?php print render($form['choice']); ?>
   <?php print render($form['form_build_id']); ?>
   <?php print render($form['form_token']); ?>
   <?php print render($form['form_id']); ?>
   <?php print render($form['submit']) ?>
</div>

```

The form is printed correctly and even the button shows the ajax icon when clicked, but it does not work. When I check the logs it shows 2 errors:

* Notice: Undefined index: `form_build_id in ajax_get_form()` (line 325 of...
* Invalid form POST data.

It is similar to this issue Ajax not working for themed form but it does not work even adding `drupal_render_children($form);` at the bottom of the template.

Notes:

* I added `drupal_add_library('system', 'drupal.ajax');` in the module.
* I'm using jQuery 1.7
* I also tested `drupal_render()` instead of `render()`.

# Answer
Instead of print rendering the individual items, you can try to build your form using the drupal\_get\_form core function, which allows Drupal to add all the extra components to the form (including the Ajax call).

So in your template it would like like this:

```
$output = drupal_get_form('mymodule_form');
print drupal_render($output);

```
> 0 votes

---
Tags: ajax, forms
---


# Question
Title: How to export only content, strictly core content like articles, pages, users, taxonomy ect?
**How to export only content, strictly core content like articles, taxonomy ect?**

Is there a way to export content only, no data about modules, only content that will work with drupal core install.

Just data that is not affected by modules and configurations.

With Joomla I could do this via PHPmyadmin.

Any easy way to do this with Drupal 7, any module?

I see an exclude tables option in backup migrate.

```
You may omit specific tables, or specific table data from the backup
file. Only omit data that you know you will not need such as cache data, or tables from other applications. Excluding tables can break your Drupal
install, so do not change these settings unless you know what you're doing.

```

But I'm looking for an include only option, not exclude what you don't want.

# Answer
> 2 votes
There are several ways to achieve this

* Use migrate module
* Use Node Export Module
* Use Feed Module
* Or you can use web services to achieve this. For example expose data in services and import those data back in the other drupal site. (Very easy approach)
* You need to check the database structure a bit and write a custom php script to take data from one table and insert it into another.

# Answer
> 1 votes
If you want to export these data and import it to another drupal site, then you can use Migrate module.

> As given in the documentation
>
> The migrate module provides a flexible framework for migrating content into Drupal from other sources (e.g., when converting a web site from another CMS to Drupal). Out-of-the-box, support for creating core Drupal objects such as nodes, users, files, terms, and comments are included - it can easily be extended for migrating other kinds of content. Content is imported and rolled back using a bundled web interface (Migrate UI module) or included Drush commands (strongly recommended).

# Answer
> 1 votes
You can use **Node Export** Module, its the best and easiest way to Export content

you can download from here https://www.drupal.org/project/node\_export

you can find more about this module here http://drupal.org/node/1627916

---
Tags: importing-exporting
---


title: Commerce RRP translation

text:
# Question
Title: Commerce RRP translation
The special price attributes provided by Commerce Exra Price Formatters are not translatable. Especially RRP. I cannot change the translations of these fields. I can write the label in the display dialog but it is not changeable depending on the site's language. How can I solve this problem?

# Answer
For bugs like this, it's best to do a quick search of the module's issue queue. There are two issues, one with a patch that appears to do the job!

https://www.drupal.org/node/1804142
> 2 votes

---
Tags: commerce, i18n-l10n
---


title: Linking nodes using views

text:
# Question
Title: Linking nodes using views
I am having the hardest time figuring out how to display multiple content types in a page using views.

In my example I have a music studio.

I have a content type for user including basic personal info

I have a content type for studio including room capabilities

And finally I have a content type for computer including hardware specs.

I'd like to have all this viewable on a page together so that when a user views a studio they see the user (engineer) and the computer information.

I'm very slightly familiar with entity ref but it appears to only show the title of the node when viewing and I'd like to have a page with composite information containing fields I select from each node/content type

# Answer
This can be achieved with Entity reference and relationship

* Create a views of studio.
* Make a relationship of Entity reference with user and hardware information
* Now when you select fields all the fields from user, studio and hardware will be available in the list.
* Select those fields which you need. and that's it.
> 0 votes

---
Tags: views
---


# Question
Title: cloning a live drupal website (db) to a local / working mamp version
I have a drupal multi-site project, that I've inherited. I am stuck on the process of trying to clone or import the database from a live server to the local enviroment. Does anyone have any suggestions as to how I might be able to do this?

It would have to be done via the command line, as the I don't have access to `phpmyadmin` from the live server. I know this can be done, with a series of commands and scripts -- I'm just not sure how...

# Answer
> 0 votes
I use this command to dump my databases which are hosted on Ubuntu:

mysqldump -uusername -p --databases db\_name | gzip -f \> db\_name.sql.gz

---
Tags: database
---


title: Custom Form Block not displaying

text:
# Question
Title: Custom Form Block not displaying
I'm trying to create a custom form displayed inside of a block. \[edited\]

```
 <?php

function edit_node_block_info(){
    $blocks['edit_node'] = array(
        'info' => t('Custom Block to allow edit/delete/copy'),
        'status' => 1,
        'region' => 'Primary',
        'weight' => 0,
        'visibility' => BLOCK_VISIBILITY_LISTED,
    );

    return $blocks;
}
/*
 * Implements hook_block_view: sets how the block is displayed
 */
function edit_node_block_view($delta = ''){
    switch ($delta) {
        case 'edit_node' :
            $block['subject'] = t('Edit Nodes');
            $block['content'] = drupal_get_form('edit_node_form');
            break;
    }
    return $block;
}
/*
 * implements custom form/creating custom form for drupal_get_form named above.
 */

function edit_node_form($form, &$form_state) {
    $form['node-id'] = array(
        '#type' => 'textfield',
        '#title' => t('Enter the Node ID'),
        '#max-length' => 8,
        '#required' => TRUE,
    );
    $form['edit-node'] = array(
        '#type' => 'radios',
        '#title' => t('Select Action'),
        '#options' => array(t('edit'), t('delete'), t('copy')),
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );
    return $form;
}

function edit_node_form_validate($form, &$form_state, $node){
    if ($form_state['values']['node-id'] != $node->nid){
        form_set_error('node-id', 'Node-id must match a current nid.');
    }

```

I see my block in the blocks list. But, my form is not showing up. I am wondering if I need to run a `drupal_form_submit('edit_node_form', $form_state);` at the end, but shouldn't that be ran during a submit function?

I'm also wondering if I need to update the form\_state as I'm not creating a form\_id currently (eg https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_form\_alter/7)

```
if (isset($form['type']) && $form['type']['#value'] . '_node_settings' == $form_id) {
    $form['workflow']['upload_' . $form['type']['#value']] = array(
      '#type' => 'radios',
      '#title' => t('Attachments'),
      '#default_value' => variable_get('upload_' . $form['type']['#value'], 1),
      '#options' => array(t('Disabled'), t('Enabled')),

```

But I think that is related to hook\_form\_alter which I have not called.

# Answer
> 0 votes
I just got it working by changing the page's it was viewable on. Not really sure why that fixed the issue, but it did.

---
Tags: 7, forms, blocks, webforms
---


title: add amount to shipping cost per product

text:
# Question
Title: add amount to shipping cost per product
I have some products type , I want when a specify product type is in order add amount to shipping cost. my idea was create a rule with condition `Order contains products of particular product types` ,and select action `add a amount to unit price` but in `item identifier *
Specify an identifier of a commerce Line item` section I try everything but returned me error.

I try `commerce-order:commerce-line-items:` and `commerce-order:commerce-line-items:0`,`commerce-order:commerce-line-items:1` ,`commerce-order:commerce-order-total:`

but all of them return me **Data selector commerce-order:commerce-line-items: for parameter commerce\_line\_item is invalid.** error.

what I should input there ? is my idea correct way to add amount to shipping price when specify products are in order?

# Answer
You're probably wanting the basic solution explained in this video: https://commerceguys.com/blog/using-calculation-rules-add-item-shipping-commerce-shipping-screencast

With a little modification, it looks like this:

1. Add a new "Calculation rule" for your shipping service.
2. Add an action loop that loops through the line items in the order.
3. Add an action "Calculate a value" and multiply the quantity times a field which holds the shipping price you want to charge for that item and store it in a named variable.
4. Add an action "Add an amount to the unit price" that adds the named variable to the unit price of the shipping line item.
> 3 votes

# Answer
Why not just use the Commerce Flat Rate module to add a flat rate to each item. You can also specify a standard rate for the first item, and an additional cost per extra item.
> 0 votes

---
Tags: rules, commerce
---


# Question
Title: How to fix the Invoice module's total amount?
I recently started using the Invoice module. Everything seemed to work until the moment I was going to make some test invoices.

The total amount is wrong (see figure): 306.81 + 64.43 = 371.24, but on the invoice 371.25. Anyone have any idea how I can fix this?

It does show well in the back-end: The sum from there looks simple? 371.25 - 306.81 = 64.44, this is the only correct result (see figure).

# Answer
> 1 votes
It is not a mistake. That moduo do rounding. See the photo:

Subtotal: 134.50 VAT: 25.55 Total: 160.06

So, the real value of VAT is 134.50\*0.19=25.555 and real total is 160.055 but for invoices you need to do rounding at two decimal places. And you get total 160.06.

---
Tags: commerce
---


# Question
Title: Can admins create new accounts without passwords?
When an admin creates a new account (admin/people/create), they're prompted to enter a password for the account. My client wants it to be that when an account is created in the back end, the admin doesn't have to enter a password, but the user is sent a notification message with a one-time log-in link and can then set a password after logging in using that. What's the best way to achieve something like this?

I've thought of maybe altering the form to set the `#default_value` of the password fields to a random password and then setting `'#access' => FALSE`, but I'm not sure if that's the best way to go about it.

# Answer
> 4 votes
There is a module that does this.

Check out Generate Password.

It introduces this additional setting in *Configuration » People » Account settings*:

> Users may enter a password on registration. If left empty, a random password will be generated. This always applies when an administrator is creating the account.

Then, when creating the account, leave the password field empty, but make sure you also check this checkbox on the "Add user" page:

> Notify user of new account

The result of these two settings is that the module generates a random password when the administrator creates an account, and the user is sent an email with a notification about the account and prompted to set a password in the one-time login link that is included in the notification.

If you want to learn how it is done, read the source code.

# Answer
> 3 votes
If you don't fancy installing the "Generate Password" module and are comfortable using hooks, then here is an alternative:

```
/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Remove the password field when admin is creating an account.
 */
function HOOK_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  if ($form['administer_users']['#value']) {
    $form['account']['pass']['#access'] = FALSE;
    $form['account']['pass']['#value']['pass1'] = user_password();
    $form['account']['pass']['#value']['pass2'] = $form['account']['pass']['#value']['pass1'];
  }
}

```

You could make it more sophisticated to your taste. As it stands it always hides the password field and provides a value instead - the admin will have to edit the newly account to set a specific value. Also it leaves the "notify" default to off, whereas you might prefer on.

Updated as per @joe\_flash answer (but in a slightly more compact form): the password field will be expanded into two subfields ("pass1" and "pass2") when the element is processed.

# Answer
> 3 votes
AdamS's answer is *almost* there. Since the password field will be expanded into two subfields ("pass1" and "pass2") when the element is processed (`form_process_password_confirm()`), you need something like:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function acfo_common_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  // Do special for user admins.
  if ($form['administer_users']['#value']) {
    // Default to sending user an account creation notification.
    $form['account']['notify']['#default_value'] = 1;

    // We'll send a one-time login link in lieu of setting a password here.
    $pass = user_password();
    $form['account']['pass']['#value'] = array(
      'pass1' => $pass,
      'pass2' => $pass,
    );
    $form['account']['pass']['#access'] = FALSE;
  }
}

```

---
Tags: 7, users
---


title: Showing shipping costs in the cart page

text:
# Question
Title: Showing shipping costs in the cart page
Hi i'm using the Commerce Shipping Postal Code Weight module. It works fine but I just want to get shipping costs in the cart page.

# Answer
You are probably wanting something like Commerce Cart Estimate.
> 0 votes

---
Tags: commerce
---


# Question
Title: Second Contextual Filter on Calendar Module
I'm attempting to add a second contextual filter to a Calendar view generated by the Calendar module.

I'm using the entity reference module to reference all my 'Events' to 'Clients'. My desired outcome is to go to a url like `example.com/client/[client-nid]/calendar/month` and for the calendar to only display events that reference that client.

My Event content type has an entity reference field 'Client'. In my view, I have added a Contextual Filter for this field and set it to validate against 'Content', specifying 'Client' as the content type and Filter Value Format is Node Id.

When i use this view though `example.com/client/182/calendar/month` I only see a calendar with a single event on it, even though there are many nodes that reference node 182. What am i doing wrong?

# Answer
Entity reference field can not provide content id to your view through contextual filter by default. You'll need to define a relationship to your entity reference field so that view is able to pick up Client node id ( content:nid) as contextual filter.

Remove contextual filter that you have now and add relationship to the entity reference field 'Client'. Then add contextual filter to Content:nid. In relationship setting select the alias of relationship that you added previously. In the section " When filter value is not available" check 'Provide default value -\> raw value from url -\> path component = 2'. Also check "use path alias".
> 1 votes

---
Tags: 7, datetime
---


# Question
Title: How to sync one menu item into other menus?
I have a Drupal menu called Top-Nav which I use for my Top Navigation with the following 6 menu items(for example)

```
Home   a    b    c    d    e

```

Each of a, b, c, d and e have sub items. I also have 5 other menus let's say named "menu1", "menu2", "menu3", "menu4", "menu5" that have exactly the same structure/items as a, b, c, d, e Like "menu1" is the same as "a", "menu2" is the same as "b" ...

What I am trying to achieve is the following: When the admin adds a new item to "a" section of Top-Nav i want to replicated that item in "menu1" programmatically, I want to sync them once the new link is added.

# Answer
> 3 votes
My suggestion is to use `hook_form_FORM_ID_alter` to add a custom submit handler. In that submit handler, you will get the current menu item values. Use those values to create a new menu item for the other menu.

Functions to use:

1. hook\_form\_FORM\_ID\_alter. Here form id will be 'menu\_edit\_item'
2. Use form\['#submit'\]\[\] = "custom submit handler" in form alter.
3. Use menu\_link\_save in custom submit handler based on the values you get form the form\_state.

# Answer
> 2 votes
You can use the hook\_menu\_link\_insert in a custom module.

> This hook is used to notify modules that menu items have been created. Contributed modules may use the information to perform actions based on the information entered into the menu system.
>
> Parameters
>
> $link: Associative array defining a menu link as passed into menu\_link\_save().

I make a test and it's works fine.

---
Tags: 7, routes, hooks
---


# Question
Title: Make a field in a Views block visible ONLY to the acccount/profile owner
The profile owner (currently logged in) sees this (contextual filtered Views block):

**CURRENTLY**, the other logged in users who visit test\_user2's profile page see this:

What I want to **achieve**, is for the other logged in users who visit test\_user2's profile page to see this:

In other words, I want **only** the account/profile owner to see the Edit field (/user/\[nid\]/edit) on their own page and to be able to edit his/her profile info. How to do this?

# Answer
Create the block without the edit link. Then implement function hook\_views\_pre\_render in your theme.

> This hook is called right before the render process. The query has been executed, and the pre\_render() phase has already happened for handlers, so all data should be available.
>
> Adding output to the view can be accomplished by placing text on $view-\>attachment\_before and $view-\>attachment\_after. Altering the content can be achieved by editing the items of $view-\>result.
>
> This hook can be utilized by themes.

Within this you do a conditional check to see if currently logged in is the same as profile owner, then if so add the link to `$view->attachment_before`

I think you would get quite a lot of answers on this question as there are so many ways to do it.

If you want to do it without coding I think you might get it right with Views arguments in filters installed. You create the link field in an attachment to the block using the currently logged in user as contextual filter, then (via installed module referenced) do the conditional check in your filters section of views on this attachment.
> 1 votes

---
Tags: views
---


title: PDF viewer for Drupal

text:
# Question
Title: PDF viewer for Drupal
I'm searching for a PDF viewer for Drupal 7 which doesn't renders as a Mozilla Firefox PDF or a google's PDF.

Does someone know anything that I could use?

# Answer
> 0 votes
Seems you're looking for the PDF module

> Uses HTML5 to display PDF files if users don't have pdf plugin for their browsers.
>
> With this module you can use pdf.js to display PDF file all the time or only use pdf.js when visitors don't have pdf reader plugin.

---
Tags: 7, files
---


# Question
Title: Getting custom body class from node field
I would need to get a custom body class, so that admin can set the class. At the moment I have field on page node type where I try to get it. The code what I have is below but it doesn't seem to work that smoothly. Something it prints two body classes (like this `<body class="classes comes here" class="another set of classes">`) It's in template.php and preprocess\_html function.

```
$node = menu_get_object();
if ($node && isset($node->nid)) {

    $field_bClass = field_get_items('node', $node, 'field_bClass');

    if (!empty($field_bClass)) {
        $field_field_bClass_output = field_view_value('node', $node, 'field_bClass', $field_bClass[0], array(
            'type' => 'value'
        ));

        $vars['classes_array'][] = $field_field_bClass_output['#markup'];

    }
}

```

Is that corrrect and what should be done difrently?

# Answer
```
function TEMPLATE_preprocess_html(&$vars) {
    $node = menu_get_object();
    if ($node && isset($node->nid)) {
        $field_body_class = field_get_items('node', $node, 'field_body_class');

        if (isset($field_body_class[0]['value'])) {
            $vars['classes_array'][] = $field_body_class[0]['value'];
        }
    }
}

```

This is how it would look today in Drupal 7, assuming your field name is what it is in the example. (The difference with the other answer being instead of `$vars['attributes_array']['class'][]` using `$vars['classes_array'][]`)
> 2 votes

# Answer
```
function TEMPLATE_alpha_preprocess_html(&$vars) {
  $node = menu_get_object();
    if ($node && isset($node->nid)){
    $field_bclass = field_get_items('node', $node, 'field_bclass');
    if (!empty($field_bclass)) {
        $vars['attributes_array']['class'][] = $field_bclass[0]['value'];
    }
}
}

```

I'm terrible at stacks code formatting, sorry.
> 1 votes

---
Tags: theming
---


title: customize shopping cart

text:
# Question
Title: customize shopping cart
I'm just looking for a module in drupal to make a shopping cart customizable. I mean that there will be no products, I just need that people put the amount of money they need to pay and just click proceed to checkout and goes directly to the payment gateway with the amount written. I've been looking to Commerce and Ubercart but I couldn't figure out if there is this option. Can you help?

# Answer
It looks like you need Donation functionality, may entitled as something else.

Following modules might help you.

Or a custom form which interacts with https://www.drupal.org/project/pay
> 0 votes

---
Tags: commerce
---


# Question
Title: What is the equivalent of hook_menu_alter() to change a menu item type?
I want to change the menu type in Drupal 8. In Drupal 7 we can achieve this using hook\_menu\_alter

```
function module_menu_alter(&$items) {
  $items['admin/config/people/ip-blocking/default'] = array(
    'title' => 'Block IP Address',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
}

```

Similarly I want to change the menu type in Drupal 8. How can I do it. Thank You.

# Answer
While the answer from Linus is great, it doesn't provide feedback on your specific question:

> Similarly I want to change the menu type in Drupal 8

There is no such thing as a menu type in Drupal 8. Everything that used to be a type is now a completely different thing. Routes, Menu Links, Local Tasks, Local Actions. And often, you have multiple things. You always have a route (7.x used to call this type callback). And addition, you add menu links, local tasks or actions for that route.

So, you can't convert a menu link to a local task for example, or even a route to a local task. The only thing you could do is e.g. alter a menu link away (which has nothing to do with route alter mentioned above) and create a new local task instead.

See Linus' answer for links and more information on how to do each of those things.
> 8 votes

# Answer
Drupal 8 has a new menu system, there is no `hook_menu` and no `hook_menu_alter` anymore.

If you want to alter an existing route, it is a little bit more complicated in comparison to Drupal 7.

In your module you have to create a class file at `YOURMODULE/src/Routing/CLASSNAME.php` that extends `RouteSubscriberBase`:

```
/**
 * @file
 * Contains \Drupal\YOURMODULE\Routing\RouteSubscriber.
 */

namespace Drupal\YOURMODULE\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Get the route you want to alter
    $route = $collection->get('system.admin_content');

    // alter the route...
  }
}

```

You can take the RouteSubsciber class of the node module as an example.

To let your RouteSubscriber be recognized you also have to create a `YOURMODULE.services.yml` file in the root of your modules directory:

```
services:
  node.route_subscriber:
    class: Drupal\YOURMODULE\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

```

To get a better insight to the new menu system I would recommend the following articles:

**Edit:** As mentioned by Berdir, the menu system has a different structure now, which has nothing to do with D7's menu system, so there is no such thing as a menu type anymore.
> 23 votes

---
Tags: 8, routes
---


# Question
Title: hide unpublished content in view, for everybody except the author
I'm trying to make a view of articles written by an author. I use the author UID from the URL as a contextual filter.

I want to hide unpublished content from everybody except the author himself.

I have removed the published filter, hence all unpublished content is visible. My first guess was to write some php code to check if the uid of the logged in user and that from the URL are same or not. If true display unpublished content or else hide unpublished content. But could not implement it.

Please suggest any possible solutions. Thank You.

# Answer
I think the similar question asked previously . You can find the solution at Use Views to display unpublished nodes to authors, but not to other users
> 0 votes

---
Tags: views
---


# Question
Title: hide repeated data from my view table for some specific field
\****how can hide repeated data from my view table. i want to print employee Id and name field only once for each group. can you please help me out.\****

---

I am fetching two table in view using JOIN.So few data gets repeated with respect to foreign key. So I need to hide those field value... Suggest me any solution...distinct and aggregation mixing up my data..

---

# Answer
> 0 votes
you need to remove the month and aggregate the salary field as SUM, if you only want to suppress display of 2+ column values try the views merge rows module

# Answer
> 0 votes
Enable Aggregation in the advanced settings of your view and group the fields.

---
Tags: hooks, views
---


title: How do I load a php library?

text:
# Question
Title: How do I load a php library?
I'm writing a wrapper module for a php library, and for some reason, can't get to actually doing something. When I try to call

```
libraries_load($library_name);

```

I get an error message:

```
PHP Fatal error:  Call to undefined function libraries_load()

```

I do have set

```
dependencies[] = libraries (>=2.x)

```

in the `module_name.info` file and `module_name_libraries_info()` seems to be okay. When I run `drush libraries-list`, I do get the library listed correctly.

The version of the libraries api I have installed is 7.x-2.2

How do I fix this?

# Answer
> 1 votes
It's very rare to need to use the Drupal API outside of a hook/callback function.

That's what's causing the problem in this case - your module file is simply being included before that of the libraries module, so the interpreter doesn't know what `libraries_load()` is yet.

I'd recommend moving your code into an appropriate function that gets invoked when Drupal is properly bootstrapped, and all enabled modules are loaded.

Failing that, you might get some joy out of tweaking the `weight` field in the `system` table for the modules in question. If your module has a higher weight than Libraries, you might be able to get it working. But moving the code to a more reliable place would arguably be better.

---
Tags: theming
---


title: Theme a specific view with Twig

text:
# Question
Title: Theme a specific view with Twig
Is it possible to write a twig template for a specific view? I have a view with multiple blocks and I want all these blocks to look the same. But I am having trouble with my views actually knowing which theme to use. I am trying to inherit the block.html.twig template but none of my changes render.

I am also afraid that my changes will change every block not just the blocks for that view. How can i limit it to just my view?

# Answer
Views in Drupal 8 has pretty much the same template options as in Drupal 7. If you are in doubt, what suggestions are offered, you should turn on twig debugging (settings in service.yml). You will get the suggestion output as HTML comments. Unlike in Drupal 7, Views in Drupal 8 does not have a button to see the templates files being used along with suggestions.

This might be added later as Drupal 8 is still in beta, at the time of this writing.
> 0 votes

# Answer
In addition to the advice offered by googletorp, this page on api.drupal.org has some examples:

https://api.drupal.org/api/drupal/core%21modules%21views%21views.theme.inc/group/views\_templates/8

The Drupal 7 version for comparison:

https://api.drupal.org/api/views/theme!theme.inc/group/views\_templates/7
> 0 votes

---
Tags: 8, theming
---


# Question
Title: How to set viewing of Bookmarks User Profile tab to just the owner?
So, with the Flag module comes a ready made flag and view for "Bookmarks". The view that comes with the Bookmark flag creates a tab on the user profile page labeled "Bookmarks" showing all of the bookmarks saved by that user.

I would like this tab to only be visible for the actual owner of that user profile page.

That way, if some other user views a different user's profile page, they will not see the Bookmarks tab.

Currently, from what I can tell, a view can only be limited in access by Roles or specific permissions. Any suggestions?

I would prefer now to have to use custom PHP.

Drupal 7.12

# Answer
> 3 votes
Try "permissions" and "view own published content."

# Answer
> 0 votes
I used the filter User:Current. So now I cannot see the bookmarks but I can still see the page.

If anybody has a better solution, pls post over here.

Here is a related link from drupal.org https://www.drupal.org/node/605142

---
Tags: flags
---


title: How to to add a percent-based discount?

text:
# Question
Title: How to to add a percent-based discount?
Now during order edit it is possible to apply only a fixed discount. How to to add a percent-based discount?

# Answer
You need to install (or perhaps just begin using) Commerce Discount.

Discounts are applied either to the individual product line items (product discounts) or the order total (order discounts).
> 1 votes

---
Tags: 7, commerce
---


title: How do I add Bean content to solr?

text:
# Question
Title: How do I add Bean content to solr?
I have a bunch of pages that contain only beans. I need these pages to show up when searching (using search\_api\_solr) for words used in those beans. The bean fields don't show up in the solr field settings page. Any ideas?

Update: though you can create an index containing both nodes and blocks this will just give me the blocks as results and not the pages they are on. Could this be 'fixed' in views?

# Answer
> 1 votes
Enable the 'Complete entity view' filter and then select the field 'Entity HTML output'. This will put the entire page in one field including any beans on that page.

I assume there is a better solution but I have not found one yet.

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


# Question
Title: Have the same rendered output, whether the video is a local or remote ressource
I need to let contributor either upload video or link to some remote streams (youtube).

For this, I use media (and media\_youtube) module.

I works well for remote ressources, however when I try to upload a video instead, the video appears as a link, on the front (though I tried to fumble with the manage display settings for this peculiar field).

I tried to implement jwplayer for the local videos, but it did not work this time. I also had a look at mediafront module, but as far as I know, it does not handle "local" videos (I may be wrong, but it seems overkill).

Have you been facing such a problem before, that is render a consistent display (a player with the same dimensions), regardless of the source (local or remote) ? Can you point me to some resources ?

Thank you.

# Answer
> 0 votes
Haven't tried it yet, but I believe that is what is good about the mediafront module. It wraps the youtube or local videos in it's own themeable player.

You could also try http://drupal.org/project/mediaelement module, though I'm not sure how well that display's youtube videos.

# Answer
> 0 votes
i had tried many options to deal with video, i believe that video hosting and publishing solution for delivering professional quality video to digital audiences on any device. you can try Brightcove Video Connect. it also has an integration with media module.

---
Tags: files, media, nodes
---


# Question
Title: In Drupal 8 view.html.twig file how do I access the view content such as individual field title and/or field content?
Using `views-view.html.twig` as a starting point, I can output `{{ rows }}`, but I want to loop through each field of each row to aggregate and style them.

In Drupal 7, I use `dpm(rows)` to locate (in the array) where content, label etc. But `kint` doesn't seem to provide me the same information. Can anyone help?

# Answer
> 4 votes
In views-view.html.twig is not appropriate to style your row and fields.

To style them first you need override template "views\_view\_'format\_style'" (format style specified when you edit/create a view). Here you can style row and access 'fields' variables (use kint(row) to see them).

Something like:

```
{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  {{ kint(row) }} {# devel #}
  <h2> {{row.content['#node'].getTitle()}} </h2> {# access fields #}
  <div{{ row.attributes.addClass(row_classes) }}>
    {{ row.content }}
  </div>
{% endfor %}

```

For style fields its better override field template.

For example `field--node--body--article.html.twig`:

```
{% set mode = element['#view_mode'] %}
{% if label_hidden %}
  {% for item in items %}
    {% if mode == 'full' %}
        <div{{ attributes }}>{{ item.content }}</div>
    {% elseif mode == 'teaser' %}
        <p{{ attributes }}>{{ item.content }}</p>
    {% endif %}
  {% endfor %}
{% else %}
  <div{{ attributes }}>
    <div{{ title_attributes }}>{{ label }}</div>
    {% for item in items %}
      <div{{ item.attributes }}>{{ item.content }}</div>
    {% endfor %}
  </div>
{% endif %}

```

---
Tags: views, theming, 8
---


# Question
Title: adding a phone field in out of stock form of commerce stock notifications drupal commerce
Is there a way adding a phone number field (along with the e-mail) in the out-of-stock form that is being used from the commerce stock 7.x-2.2 module and commerce stock notifications 7.x-1.1 module?

I am using drupal commerce kickstart2 and when i have a product that is out of stock the above modules helps no to be able to add them in the shopping cart as long as it gives the option to fill in an e-mail address. I would like to add a phone number field as well under the e-mail address I was wondering if anyone knows how.

# Answer
> 0 votes
Ash joshmiller noted, you can add a field using a form alter and then add another custom submit handler to take the submitted values and do something with that data. You'll have to provide your own DB or come up with some method to store that data on the customer or product.

---
Tags: commerce
---


# Question
Title: How to add css immediately (display:none) to a block created through hook?
I created a block through drupal hook\_block\_info (and hook\_block\_view, but this doesn't really matter)

```
function mymodule_block_info() {
  $blocks['menu_mobile'] = array(
    'info' => t('Mobile Menu'),
    );
  return $blocks;
}

```

I need it to be hidden initially and then to show on webpage resize/mobile. I did this by applying a display:none to css and the media rule

```
@media screen and (max-width: 768px)

```

It works. Almost Perfectly. The problem is that, at the very beginning of webpage loading, the block is visible and, for maybe a second, it shows on its webpage, then the display:none does its work hiding it. It is annoying. I saw here some properties of the array to be returned by the hook, but none really fits my case. For example, enabling/disabling hides the block, but i don't really know how or when to show it again.

```
https://api.drupal.org/api/drupal/modules%21block%21block.api.php/function/hook_block_info/7

```

So, how i can have the block initially hidden, or fasten the display:none (that is contained in the style.css of my custom theme)?

# Answer
> 1 votes
A block can have a content element when created in code. This content element can be raw HTML or a drupal render array. If you use raw HTML for your block you can just put `<style type="text/css">#your-block-id { display: none;}</style>` directly into your block output.

Or if you use a render array you can do something similar with the `#attached` key on the render array. This is outlined in the API usage of drupal.org and a comment provides an example:

```
$block['content'] = array(
  '#markup' => mymodule_testblock_content(),
  '#attached' => array(
      'css' => array(
        drupal_get_path('module', 'mymodule') . '/css/mymodule.css',
      ),
      'js' => array(
        drupal_get_path('module', 'mymodule') . '/js/mymodule.js',
    ),
  ),
);

```

Obviously the render array approach is a cleaner, more elegant solution. You can even have the CSS `inline` when using `#attached`.

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


# Question
Title: Webform: POST data and send user to external URL
I was reading this interesting post: Webform - Submit values from Drupal 7 from to external url

I'd like to know: instead of just sending the data via POST and keeping the user on the Drupal site, how would you send the user to the URL the form values are posted to, so that they would arrive at the new URL and see a new form with the values they submitted?

Thanks.

# Answer
> 0 votes
That post is accurate. You just need to set the `#action` of the form to be the URL you want to be POSTed to:

```
$form['#action'] = 'https://some.other.site.com/destination';

```

---
Tags: 7, webforms
---


# Question
Title: How to fix Openlayers "Unable to load CTools exportable" errors
So, Openlayers 3.1 and 3.x Dev both have this issue. I've looked and this issue has been reported as fixed in the Drupal Openlayers issues list.

The issue is that everyone of my added layers, components, and sources each triggers these errors:

```
Unable to load CTools exportable Component (ol_users_geojson).
Unable to load CTools exportable Component (ol_geojson_chapter).
Unable to load CTools exportable Component (ol_geojson_reg_gr).
Unable to load CTools exportable Component (ol_geojson_alum).
Unable to load CTools exportable Component (google_base_layer).
Unable to load CTools exportable Component (users_popup).

```

Most of these components works in my map, except the popup, but that's a different issue. Part of the issue, is that this error is displayed prominently on my map page, even to regular users. What confuses me, is that for each of those components I'm following the OL examples, so I don't know why my custom implementations don't work. I speculate that this might have to do with the fact that the openlayers examples are all defined in code in the module, while my custom implementations are saved to the database and there might be an issue in how they are written there. There was an issue in the 2.x that some of the style component settings were getting mis-written to the db, but I haven't been able to find where in the db these are written to. From what I can tell, when I export my custom components they match those of the examples, so I'm not sure what's going on.

So, my question, which isn't obvious from the issue queue, is: is there anything I can do to fix this (patch, etc)?

# Answer
I just got an answer from the Openlayers issues cues. The unable to load CTools errors exist when the module is looking for a missing or deleted component of a map.

In my case, I had to re-install my OL module and reconstruct the map with just the components I needed. It took some trial and error to get there.
> 1 votes

---
Tags: javascript
---


# Question
Title: How to know which users/nodes failed to import in feeds logs?
I'm trying to convert my implementation from the location to geofield modules. Not finding an easy way to convert the data, I tried the manual way which is to export the data to CSV and then repopulate the appropriate fields through fields. The issue is I have a lot of users, around a 1000, and the feeds log is just telling me that 44 of them failed. Is there anyway to know which ones failed? The feeds log doesn't give me a lot of diagnostic information, and manually checking is going to be a pain.

# Answer
> 0 votes
So views data export will truncate some user names based on their lengths. This resulted in a mismatch between the exported users' name and the user name in the DB, leading to errors.

---
Tags: users, feeds
---


title: How is a theme template file picked up?

text:
# Question
Title: How is a theme template file picked up?
Does any one know how Drupal 8 picks up theme template file? I mean in source code.

I have module which use a custom template file for a custom block , but the custom template file was not been picked up.

I have tried many different ways, but none working, so I have decided to looking Drupal 8 source code to find out , but I am unable to find out exact source code that picks up the theme template file.

# Answer
> 0 votes
Ok, I have just uninstall / re install the module, now it worked. Drupal 8, probably keep some old information somewhere in cache.

By the way, during debuging, I have found this interesting class:

Drupal\Core\Template\Loader\ThemeRegistryLoader

# Answer
> 1 votes
I had a similar problem and tried:

```
{% include 'my-template.html.twig' %}
{% include directory ~ '/templates/my-template.html.twig' %}

```

but ThemeRegistryLoader wouldn't recognize 'my-template'. This syntax worked:

```
{% include 'modules/custom/my_module/templates/my-template.html.twig' %}

```

---
Tags: theming, 8
---


# Question
Title: Disable select drop-downs, display names only
I am looking for a way to remove the select drop-downs from the datepicker popup and display only months (and the year). As for the appearance, it can be altered in datepicker.1.7.css.

How do I disable the select drop-downs and show only the names?

# Answer
> 1 votes
As of date\_popup 7.x-2.9, you can do this in your theme or custom module, implementing `hook_element_info_alter(&$type)`.

```
function mytheme_element_info_alter(&$type) {
  $type['date_popup']['#datepicker_options'] += array(
    'changeMonth' => FALSE,
    'changeYear' => FALSE,
  );
}

```

# Answer
> -1 votes
Did it. Turns out, that you can influence the datepicker options in modules/date/data\_popup/date\_popup.module. In the function date\_popup\_element\_info you can influence the datepicker-options for the jquery-part. This means that:

```
'#datepicker_options' => array(
  'changeMonth' => FALSE,
  'changeYear' => FALSE
),

```

will disable the dropdowns. However remember: This is a system wide change and might be gone with the next update.

---
Tags: theming, datetime
---


# Question
Title: How to edit the People (users admin view) to include filter by user name?
I want my admins to be able to search through the admin users view by the user name. I have a site with a lot of users and periodically the admins want to be able to check on various user fields. Is there a way to do this?

# Answer
> 0 votes
You cannot easily alter admin/people page but you can add a new tab to it using Views. Create a custom View page that uses users as base table and expose user:name as a filter. Set its menu to a tab under admin/people and give access based on role or "administer users" permission.

# Answer
> 3 votes
You can take a look at the Administration Views Module:

> Replaces administrative overview/listing pages with actual views for superior usability.
>
> Features
>
> * Filter all administrative views via AJAX.
> * Perform any kind of bulk/mass operations on items in administrative views.
> * Filter content by title, node type, author, published status, and/or vocabulary.
> * Filter comments by title, author, node title, or published status.
> * Filter users by name, ban/blocked status, or user roles.
>
> \*Note: If you are upgrading from an older version of Administration views and the default views have been overridden (saved in the database) you could encounter issues or not see any new changes unless you revert these views, so the default in-code views are used. This can be done in the views UI listing or using drush (drush cter views\_view --module=admin\_views)

By default it has a specific users view, but since it is a view, you can modify it.

---
Tags: users
---


# Question
Title: variable_get('var') VS $GLOBALS['conf']['var']
Let's say I set a variable in settings.php: `$conf['var'] = foo;`

In my module or theme code, I can access this with either: `variable_get('var');` or `$GLOBALS['conf']['var'];`

Which is the preferred method and why?

# Answer
> 7 votes
Pros:

* variable\_get() provides the ability to give you a fallback if it doesn't exist
* using the variable directly could wind up with a PHP notice if it doesn't exist is able to use the variable system (and any available hooks)
    + accesses all the variables (settings.php, variables in the DB, etc.) - a one stop shop. I don't believe $conf does this. A simple print\_r($GLOBALS\['conf'\]) would show if that is true or not

Cons:

* accessing the variable directly is more efficient since it doesn't execute any functions or require any logic

Personally I would use variable\_get() because of the fallback functionality and ability to tap into whatever other sources the variable system may provide

# Answer
> 7 votes
It is preferable to use `variable_get()` instead of `$GLOBALS['conf']['var']`.

Despite being gone in Drupal 8, you always want to ***program to the API*** instead of ***programming to the implementation***.

It is highly unlikely, but there could be some change that pops up in Drupal 7 where there is a difference between the two. For example, a future version could include a `hook_variable_alter()` to allow modules to muck with variables between the database and their usage.

---
Tags: 7, configuration
---


# Question
Title: How do I move conditional library includes out of a twig template?
I have a javascript library with several separate files which I would like to include only if necessary. I currently determine which need to be included within the twig template.

```
{{ attach_library('flot_d8/flot') }}
{% if options['xaxis']['mode'] == 'categories' %}
{{ attach_library('flot_d8/categories') }}
{% endif %}

{% if options['selection'] is defined %}
{{ attach_library('flot_d8/selection') }}
{% endif %}

{% if options['pan'] is defined %}
{{ attach_library('flot_d8/navigate') }}
{% endif %}

{% if resizable == true %}
{{ attach_library('flot_d8/resize') }}
{% endif %}

{% if nodiv == false %}
<div id="{{div_id}}" style="width:600px;height:300px;"></div>
{% endif %}

```

Is there a better, or alternative way to perform this logic? I would like to override this template in another module and make the simple `<div>` element more complex. However, I would have to copy all the library inclusion logic with it.

# Answer
> 1 votes
Attaching libraries in Drupal 8 should be done by either attaching the #attached attribute to render arrays or by adding them to the info file to be added to all pages.

For example let's say I have a custom form class that needs my custom javascript and/or css files.

```
class MyForm extends FormBase {
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['#attached']['library'][] = 'my_module/my_library'
    return $form;
  }
}

```

If you want to attach a library to an element you didn't initiate then you will need to use an alter hook for that specific element. If you want to attach a library based on other conditions then you can use the `hook_page_attachments(array &$attachments)` function

# Answer
> 0 votes
You can do it by this way

**Step one**

In function preprocess\_theme() you need define variable is name libraries

```
<?php

function template_preprocess_FUNCTION_THEME(&$vars) {

    $vars['libraries'] = [];

    if ($vars['options']['xaxis']['mode'] == 'categories') {
        $vars['libraries'][] = 'categories';
    }

    if (isset($vars['options']['selection'])) {
        $vars['libraries'][] = 'selection';
    }

    if (isset($vars['options']['pan'])) {
        $vars['libraries'][] = 'navigate';
    }

    if ($vars['resizable']) {
        $vars['libraries'][] = 'resize';
    }
}

```

**Step two** In twig template add libraries

```
{% for library in libraries %}
    {% set library_name = 'flot_d8/' ~ library %}
    {{ attach_library(library_name) }}
{% endfor %}

{% if nodiv == false %}
    <div id="{{div_id}}" style="width:600px;height:300px;"></div>
{% endif %}

```

I think it's ok. About function hook\_theme. Example i have function

```
function md_slider_theme($existing, $type, $theme, $path) {
  $theme = [];

  $theme['slider_edit_form'] = array(
    'variables' => array(
      'slid' => NULL,
      'settings' => NULL,
    ),
    'path' => $path . '/templates/backend',
  );

  $theme['admin_slides_render'] = array(
    'variables' => array(
      'slid' => NULL,
      'settings' => NULL,
      'slides' => NULL
    ),
    'path' => $path . '/templates/backend',
  );

  return $theme;
}

```

after hook\_theme(). I have two function theme are slider\_edit\_form and admin\_slider\_render(). You can call function with array render example

```
$build = [
    '#theme' => 'slider_edit_form',
    '#slid' => $slid,
    '#settings' => $settings,
];

```

Html will define by template slider-edit-form.html.twig... .And every function theme have preprocess. Example

```
function template_proprocess_slider_edit_form(&$vars) {
    //process data is here
}

```

---
Tags: 8
---


# Question
Title: Superfish - File not found: sites/all/libraries/superfish/sfsmallscreen.js
I just downloaded and enabled the latest (dev) version of superfish module, as well as the library... I am getting the following error:

> File not found: sites/all/libraries/superfish/sfsmallscreen.js

Should I remove this line from the libraries path:

```
sites/all/libraries/superfish/sftouchscreen.js

```

Or just download a previous (recommended) version of superfish?

# Answer
> 5 votes
Download the Superfish library and extract it to `sites/all/libraries/superfish` (so that the **superfish.js** will be located at http://example.com/sites/all/libraries/superfish/superfish.js)

# Answer
> 3 votes
use command for drush user: "drush superfish-plugin" then it create new libraries folder and contains superfish library.then add your libraries file in config file.it works.

# Answer
> 0 votes
The correct path for `Superfish` is

```
sites/all/libraries/superfish/jquery.hoverIntent.minified.js
sites/all/libraries/superfish/jquery.bgiframe.min.js
sites/all/libraries/superfish/superfish.js
sites/all/libraries/superfish/supersubs.js
sites/all/libraries/superfish/supposition.js
sites/all/libraries/superfish/sftouchscreen.js
sites/all/libraries/superfish/sfsmallscreen.js

```

Enter this lines in **Superfish library Path**

# Answer
> 0 votes
Download the `superfish` library from https://github.com/mehrpadin/Superfish-for-Drupal. This includes `sfsmallscreen.js`.

---
Tags: 7, navigation
---


title: How download images from ftp

text:
# Question
Title: How download images from ftp
I imported products with the help of feeds via commerce product processor. The images from http://example.com/image.jpg downloaded successfully. But why does not loading the images from ftp://account:123@xx.xxx.xxx.xxx/image.jpg ?

# Answer
> 1 votes
Because the image actually does not below at `/image.jpg`. You need to investigate where you are storing your files at `admin/config/media/file-system`. And from there you might find where is your files locate.

The default file path is going to be `/sites/default/files` so it might be ftp://account:123@xx.xxx.xxx.xxx/sites/default/filesimage.jpg.

# Answer
> 1 votes
Maybe you also have to check your image field path settings under `/admin/structure/types/manage/[contentelement]/fields`.

---
Tags: feeds, importing-exporting, files
---


# Question
Title: Send email with profile2 fields with account email token in rules
I am trying to send an email to users contains information they put into their profile2 fields when they registered on the website.

My problem is that their is no email field token available in rules and I was wondering if their is a way to expose the account email token so that I send emails to the user.

The rule I have setup is as follows and I have exported the rule which can be found below.

Event: After saving a new profile

Actions: Send HTML e-mail

```
{ "rules_email_banking_details" : {
    "LABEL" : "Email Banking Details",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "mimemail", "profile2" ],
    "ON" : { "profile2_insert" : [] },
    "DO" : [
      { "mimemail" : {
          "key" : "[site:name]",
          "to" : "[profile2:field_account_email]",
          "subject" : "Banking Details for accounts that you must make a  payment to.",
          "body" : "[profile2:field_name_of_your_bank]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

If anybody has some advice that could help it would be much appreciated.

# Answer
> 2 votes
Your token will be - \[profile2:user:mail\]. It is available in your rule with the setup that you described. You might not see it in replacement patterns for the "to" field when you are using "direct input" mode, but if you switch to "data selection" mode - you'll be able to find that token much easier.

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


# Question
Title: How to limit preprocess functions base on a theme?
I'm working on a theme that using `hook_preprocess_node` and `hook_preprocess_page` and everything is working fine. However, whenever I go to any admin pages, it's throwing me some errors because the array changes. So what I'm trying to achieve is to add a condition only to run this preprocess function if using my theme.

How can I limit the preprocess function base on my theme?

# Answer
You can check theme active with function:

```
<?php

$active = \Drupal::theme()->getActiveTheme()->getName();

```

Get list all themes with:

```
<?php

$themes = \Drupal::service('theme_handler')->listInfo()

```
> 2 votes

# Answer
If you implement the preprocess functions in your theme's `template.php` file, those will only be executed on the pages where the theme is applied.
So, if your admin theme is different (which is the case almost every time), the preprocess functions from your site theme would not be executed.
> 0 votes

---
Tags: 8, theming
---


# Question
Title: Line item custom field value not be saved after update line item
I added a custom field into line item type, but it cannot be edit on order edit page. My environment: commerce\_kickstart-7.x-2.22(With IEF 1.5 and the widget: Inline entity form - Multiple values)

Steps to produce this issue:

* Add a "field\_additional\_information" text field on admin/commerce/config/line-items/product/fields, Do not include it on "add to Cart from".
* Switch widget line item manager into inline entity form - multiple values.
* Edit order on admin/commerce/orders/%commerce\_order/edit, click "Edit" link to edit a line item, "field\_additional\_information" field is shown, fill something in it.
* Reopen admin/commerce/orders/%commerce\_order/edit page, click "Edit" link again, the value of "field\_additional\_information" field is not be shown(leave blank). Check database, the value is not be saved.

Many problems on Drupal Commerce make me distracted recently. Any comment or help would be appreciated, Thanks!

# Answer
> 1 votes
I have to "save" the whole form at bottom of the page, not only update that line.

---
Tags: commerce, entities
---


# Question
Title: Filter a view result by matching a view field to a URL term
I have a content type called "Post" which contains two fields:

1) title 2) username

I created a View which creates a block that gathers all Posts. The block will reside on a user's account page, wherein the URL will always be: www.mysite.com/user/username

How can I filter that block to only show the results where the username field matches the second term in the URL?

Thanks!

# Answer
Use contextual filter in views and set raw value as second argument from the url (here second argument will be username).
> 0 votes

---
Tags: views
---


# Question
Title: insert webform component values into a custom table
i am having trouble storing webform component values into a custom database table, i have created a custom module to insert the data into the table but its not working and i can't figure out where my problem is can someone please help here's my code thanks

```
<?php
function customform_form_alter(&$form, $form_state, $form_id) {
    if ($form_id == 'webform_client_form_24') {
        $form['#submit'][] = 'customform_additional_insert';
        if ($node = menu_get_object()) {
            $form['submitted']['node_id']['#value'] =$node->nid;
            $form['submitted']['amount']['#value'] = @$node->field_needed_amount['und'][0]['value'];
            $form['submitted']['full_name']['#value'] = @$node->title;
            $form['submitted']['image']['#value'] = @$node->field_student_photo['und'][0]['fid'];
        }
    }
}

function customform_additional_insert($form, &$form_state) {
    $data = $form['submitted'];

    // Insert a record into a 3rd-party module table when a submission is added.
    db_insert('sponsorship')
        ->fields(array(
            'n_id' => $form['submitted']['node_id']['#value'],
            'user_id' => 1,
        ))
        ->execute();
}
?>

```

# Answer
> 1 votes
I would suggest taking the data straight out of the webforms DB tables.

To understand how to do that we need to look at how data is stored in the DB.

Each time a new webform is created a row for it is created in the webform table. Each webform has a unique identifier called nid.

Each component added to the webform is stored in the webform\_component table and has a unique identifier of cid (cid is only unique per webform, nid is also required to make the primary key).

Now when a user fills in the webform a row is created in the webform\_submission table (with a unique id of sid) and each fields value is stored in webform\_submitted\_data. Each row in the webform\_submitted\_data table has a nid (the webform ID), sid (submission ID) and cid (the component ID).

So, if you wanted to get all of the data from a particular submission with the name of the field (or component), uid and the data submitted you can use the following query:

```
SELECT c.`name`, sd.`data`, s.uid
FROM webform_submitted_data sd
INNER JOIN webform_component c ON c.cid = sd.cid AND c.nid = sd.nid
INNER JOIN webform_submissions s ON s.sid = sd.sid
WHERE sd.sid = {YOUR SUBMISSION ID}

```

Or to show all of the values submitted for a particular field with uid and date then you could use:

```
SELECT sd.`data`, s.uid, s.submitted
FROM webform_submitted_data sd
INNER JOIN webform_component c ON c.cid = sd.cid AND c.nid = sd.nid
INNER JOIN webform_submissions s ON s.sid = sd.sid
WHERE sd.cid = {YOUR COMPONENT ID}

```

# Answer
> 0 votes
I know this is a bit old, but if anybody else is trying to do this check out webform\_mysql\_views. Doesn't create a table, but a database view can be really helpful if you're doing this for integration purposes.

http://drupal.org/project/webform\_mysql\_views

---
Tags: webforms, database
---


title: Core and modules upgrade

text:
# Question
Title: Core and modules upgrade
I want to upgrade my site from Drupal 6 to the latest version of Drupal 7. Currently I have version Drupal 6.21 for my site and there are other releases available 6.22 - 6.29 so I need to upgrade first to 6.29 or I can directly upgrade to Drupal 6.37 which is the latest version in Drupal 6? Also after having latest Drupal 6 version can I then upgrade directly to 7.41 or I need to do it in steps like 1-4?

Is it necessary to update core and modules first to the latest version of Drupal 6, before upgrading to Drupal 7, or can I directly upgrade to Drupal 7? I read a few articles on this, but I didn't get it.

# Answer
> 1 votes
You can't skip versions when you upgrade. For instance you cant go from 6.0 to 6.2 in one step. You also can't upgrade directly from 6.0 or 6.1 to Drupal 7. You have to have your Drupal 6 installation at the latest level.

---
Tags: 7, upgrading
---