# Question
Title: How to make a chart in Views with date as x-axis (using the charts module)?
I want to make a simple view using the Charts module.

The `x-axis` will be a custom field of type `Date` that I want to show in `Y-m-d` format and grouped by the same date. The `y-axis` will be `NID` with `COUNT` aggregation.

This seems so easy but the problem is the aggregation of the date field. Apparently, views doesn't like to aggregate those kind of fields. Tried Views Date Format SQL but this only works for core date fields (Posted Date, Updated date...)

So, is there any other way to do this?

# Answer
Within the Charts module, there is an interesting issue about this, i.e. Graph node input over time (support date formatting on a continuous axis).

In Comment #3 of that issue is stated: 'The trouble here is that neither Views nor Date modules provide aggregation options for date-based fields.'. The patch(es) included in this issue are expected to soon be applied.
> 0 votes

---
Tags: 7, views, datetime, charts
---


# Question
Title: How to load and display a view with Ajax in Drupal 7?
This is the first time I've ever tried to load a view using Ajax in Drupal7 and I would be appreciated if you help me from scratch. I've spent hours to learn how to do this but I still failed!

I created a view called `image_gallery`, it has three blocks called `hd`,`tablet` and `phone` and it displays set of images.I created a tab and I want to display and load these blocks (generally views) with Ajax. this my HTML:

```
    <div>
        <div id="image_gallery_tab">
            <ul>
                <li id="igt1">HD</li>
                <li id="igt2">Tablet</li>
                <li id="igt3">Cellphone</li>
            </ul>
        </div>
        <div id="image_gallery_content">
            <div class="igc" id="igc1">
                <?php print views_embed_view("image_gallery","hd") ?>
            </div>
            <div class="igc" id="igc2">
            </div>
            <div class="igc" id="igc3">
            </div>
        </div>
    </div>

```

I set the `Use Ajax` to "yes" in the views UI. this is my jQuery code:

```
$("#image_gallery_tab ul li").click(function(){
        var id = $(this).attr("id").slice(-1);
        $(".igc").css("display","none");
        if(id==2)
            {
            $.ajax({
                url: Drupal.settings.basePath + 'views/ajax',
                type: 'POST',
                dataType: 'json',
                data: 'view_name=image_gallery&view_display_id=tablet', // Pass a key/value pair.
                success: function(response) {
                  $("#igc2").innerHTML=response.display;
                },
                error: function(data) {
                 alert('An error occured!');
                }
              });
            }
    });

```

but it displays nothing. what is wrong here and what shall I do? thanks

# Answer
For anyone who ends up here looking for an answer, this is how you do it. First you need to enable "Use AJAX" under Other settings in the view and take note of the "Machine Name" as that is your display ID:

Then, this is how you pull it with JS using jQuery ajax:

```
$.ajax({
  url: Drupal.settings.basePath + '/views/ajax',
  type: 'post',
  data: {
    view_name: 'your_view_name',
    view_display_id: 'page', //your display id
    view_args: VIEW_ARGUMENT_HERE, // your views argument(s)
  },
  dataType: 'json',
  success: function (response) {
    if (response[1] !== undefined) {
      console.log(response[1].data); // do something with the view
    }
  }
});

```
> 11 votes

---
Tags: views, ajax
---


# Question
Title: How to print all Drupal commerce order variables available inside the template?
I'm struggling to understand how to print out all order information at the order view link, including the order author.

I mean printing it out at **/admin/commerce/orders/XXX/view**

I've manage to get the page--admin--commerce--orders.tpl.php working, but how do I find all the variables?

I've tried with dpm($account), and dpm($content), with no luck.

ie. How may I print out the author of the order?

# Answer
Try using `dpm($order)` for this. This will give you most of what you need including the order author's uid:

```
$order->uid

```
> 1 votes

---
Tags: theming, commerce
---


title: Suppressing another module's warnings

text:
# Question
Title: Suppressing another module's warnings
Is it possible to suppress another module's warnings? My module calls another causing a warning to appear.

# Answer
You could use the Disable Messages module for this. Here is a quote from its project page:

> Gives a site owner options to disable specific messages shown to end users. The core drupal message system as offered by drupal\_set\_message is an excellent way for modules to send out messages to the end users. However not all drupal site owners are keen to show all the messages sent out by drupal core and all modules to their users. This module gives site administrators a reasonably powerful way to filter out messages shown to the end users.

Some of its features are:

> * Filter out messages that match a full text string exactly.
> * Filter out messages that match a regular expression.
> * Permissions to specifically hide all messages of a given type from any role.
> * Disable all filtering for specific users.
> * Disable all filtering for specific paths.
> * Apply filtering only for specific paths.
> * Debug system to get messages in the HTML without showing it to the end users.

Available for either Drupal 6 or Drupal 7 (and a DEV version for Drupal 8).
> 1 votes

---
Tags: debugging
---


# Question
Title: How do I backup a site when it weights is more than 200MB and host can't do it?
How do I backup a site when it weights is more than 200MB and host can't do it? I have it on hostinger.ru and can't backup with Internet server error 500. I cleared cache and deleted some modules.

# Answer
> 2 votes
Refer to my answer to "Which tables are safe to clear?", which should help to get the size of your database reduced.

And/or use the Backup and Migrate module, which also support exclusion of selected tables (typically the ones that are safe to clear also). Here is a quote from its project page (bold markup added here):

> Back up and restore your Drupal MySQL database, code, and files or migrate a site between environments. Backup and Migrate supports gzip, bzip and zip compression as well as automatic scheduled backups.
>
> With Backup and Migrate you can dump some or all of your database tables to a file download or save to a file on the server or offsite, and to restore from an uploaded or previously saved database dump. **You can choose which tables and what data to backup and cache data is excluded by default**.

---
Tags: backups
---


# Question
Title: How do I customize a table display with views
I want to setup a View that will display all Title's within the company in a certain way.

History (not sure if necessary, but I imagine it can't hurt): I had a lot of duplicate Title's, because I grab the title from the user node, no distinct features seemed to help. I found a way of using `hook__query_alter(QueryAlterableInterface $query)` to make sure the titles were in order and they were not duplicated. If I display the View, as is, as a table, it looks like a normal list:

But I want the table to look like the following:

Can I do this without code? No idea how, If I can't, which is fine, my real question is below:

I can grab the view in `template_views_pre_render(&$view)`, I noticed I can also snag some of it in the `hook_preprocess_views_view(&$vars)`, and I can grab pieces in the template (...tpl.php) files like `views-view-field-w/e.tpl.php` and `views-view--w/e.tpl.php`. But as it stands I really don't know where to begin my algorithm and sifting through. In order to do this I imagine I build 3 arrays, array A, B, and C (eventually also D, E, F, etc.) and just spit them out in one of the template files to build rows for each alphabetical column in a table structure, but where do I build these arrays up, I hear `preprocess` hook is where it might be done? If so, how do I hand them over to the template files (stuff them back into the views array?). If I shouldn't be doing it that way, should I just build up my arrays and spit them out in the table format all in the template files?

# Answer
In order to do this I handled everything on the views-view-unformatted-{view\_name}.tpl.php level.

I am not sure if it is the most efficient way of doing all of the work, but it works like a charm. If anyone has any suggestions on how to optimize the code, or if I should be putting this work in the template.php file please let me know, but as it stands this answered and solved my problem.

```
/* Issue:         In order to accomodate the appropriate style requirements of
 *               this view we need to override with this file and handle the $rows
 *               in the following format. The standard Table Format for Views
 *               does not provide what we want (refer to Description to understand
 *               what we wanted).
* Description:   Overriding the views-view-unformatted...tpl.php file so we can
 *               better control view page. This View displays
 *               all the Employee Titles. Which is fine, but we want it in a
 *               particular format:
 *  (headers)                  A                 B                 C
 *  (titles)              App Specialist   Batch Processor   C.........
 *                        App Developer    B..........       C.........
 *
 *
 * ==========================================================================
*/
?>
<?php
    /*
     Lets grab and collate all of the Employee Titles and the the headers for
     each set of Employee Titles (Example of a set = all titles that start
     with 'A', or 'B', etc.
    */

    // Employee Titles.
    $titles = array();
    // Employee Title Headers.
    $title_headers = array();
    // Keep track of the character we are on.
    $first_character = '';
    // Keep track of the last character we were on.
    $last_character = '';
    // Header count for the iteration process.
    $head_count = 0;
    // Title count for the iteration process.
    $title_count = 0;

    foreach ($rows as $row) {
      $employee_title = strip_tags($row); //strip
      $employee_title_trimmed = trim($employee_title); //trim
      $first_character = $employee_title_trimmed[0];

      // We don't have the character saved.
      if ($last_character != $first_character) {
        // Increase count.
        $head_count++;
        $title_count++;
        // Fill the headers array.
        $title_headers[$head_count] = $first_character; // add the letter
        $last_character = $first_character; // update the last character
      }
      // Fill the employee title's array
      $titles[$title_count][] = array($employee_title_trimmed => $row);
    }

    /* Time to display the header and title arrays. */
    // We only want 3 columns, so that's what this variable ensures. if we
    // wanted 4 or 2 columns we just change this variable and it will take effect
    // throughout.
    $columns_limit = 3;
    // counter for the employee title headers.
    $count_header = 1;
    // Max counter for the headers.
    $max_count_header = $count_header + $columns_limit;
    // Counter for the employee titles.
    $count_list = 1;
    // Max counter for titles.
    $max_count_list = $count_list + $columns_limit;

    print("<table>");
    while($count_header < sizeOf($titles)){ //never exceed size of titles
      print"<tr>"; // Header row starts.
      // Display 3 or less headers, depending on where we are in the array.
      for ($count_header; $count_header < $max_count_header; $count_header++){
        print "<th>";
        print $title_headers[$count_header]; // Display header.
        print "</th>";
      }
      print"</tr>"; // Header row stops
      print"<tr>"; // Employee title row starts
      for ($count_list; $count_list < $max_count_list; $count_list++) {
        print'<td id="title-list">';
        print"<ul name=\"$title_headers[$count_list]\">";
        foreach ($titles[$count_list] as $titles) {
          $title_value = array_values($titles);
          $title_entry = $title_value[0];
          print"<li id=\"blue-li\">";
          print $title_entry; // Display the employee title.
          print"</li>";
        }
        print"</ul>";
        print"</td>";
      }
      print"</tr>"; // Employee title row stops.
      $max_count_header = $count_header + $columns_limit; // Update Header's Max
      $max_count_list = $count_list + $columns_limit;     // Update Employee's Max
    }
    print("</table>");

```
> 0 votes

---
Tags: views
---


# Question
Title: How do I properly render a private file URI with l()?
If given a private file with a uri of `private://Screenshot from 2015-12-07 15-52-42_0.png`. How might I use l() to properly render the link?

When rendered as follows I see `https://server/drupal-private-file-system/Screenshot%20from%202015-12-07%2015-52-42_0.png` instead of `system/...`. in the URL.

# Answer
The function file\_create\_url() is what I was after. I'm able to find what I was after with that.

`dpm(file_create_url($file_obj['uri']));`
> 1 votes

---
Tags: 7, files
---


# Question
Title: Content type select field is not listing in front end
I created a content type field called which have widget type **`select list`**

But its not displaying the field in frontend. When I changed the widget type to the **`text field`** it displays the field in frontend. I given the `edit` and `view` permissions to the filed too

But its not displaying in the front end.

# Answer
> 2 votes
when you create new field of type "list(text)" and then click "save" you will go to new page where you have to insert the values you want the user to select from, add all the values in that page one value per line. you can also assign key to the value by using this format "key|label"

---
Tags: nodes, entities, 6
---


title: View Table Format with a group by

text:
# Question
Title: View Table Format with a group by
Is there a way to create a group by in a table views.

Here is how I would like that the group by looks like

# Answer
> 2 votes
Here is a module that does exactly the same as you want.

From Module page.

> > Create a new view (eg: a list of node). Set format Table Rowspan for this view. Add some field to this view. Group field that has same value. Check option "Merge rows in group".

Click on settings and group by your results by `Principal`, `Guest`, `Email Member`, `Non Email Member`. This module will render your table in exactly the same format you want.

# Answer
> 2 votes
You can use Views Merge Rows to achieve this.

> The Views Merge Rows module provides a way to combine rows with the same content in the specified fields.

I use this module in a project and it works fine.

---
Tags: views
---


title: Gift Wrap Option Ubercart 3 on Drupal 7

text:
# Question
Title: Gift Wrap Option Ubercart 3 on Drupal 7
I would like to add a global gift wrap option to our checkout pane on Ubercart 3 (running on Drupal 7).

It is an option that can apply to any product and has a fixed price no matter how many products are purchased.

I do not want to add it as an attribute to individual products or product classes, but would like to add a simple yes/no radio button to all checkouts. If yes is selected, the fixed amount is added to the order.

What is the simplest/best way to implement this?

# Answer
Another approach would be to create a Gift Wrap product class. Create a node of this custom type with the price of your gift wrap option. Then create a view of the custom Gift Wrap entity and display it prominently as a block on your cart and checkout pages.
> 1 votes

# Answer
You can achieve this using following way,

1. You can use **hook\_checkout\_pane**() to create your 'simple yes/no radio button' to all checkouts
2. If yes is selected, the fixed amount can be added to the order as **line\_item**

A working example can find here, which will give you idea to proceed

Also Creating line items in Ubercart 3 , check this similar question
> 0 votes

# Answer
The easiest way I've found is to install Ubercart Webform and
Ubercart Webform Checkout Pane. Create a Gift Wrap product and add it as a Form component to your form. Then under Form settings, check 'Generate a checkout pane'.
> 0 votes

---
Tags: 7, ubercart
---


# Question
Title: Custom VBO Action only works when enqueued (Adding User Role and Organic Group)
I wrote a custom module to add a VBO action that allows an Admin of a group to search the sites users, add them to their list (adds a role to the select users to get them on the list) and then allows the Admin to optionally add the user to an organic group they also may admin. The role is added just fine, but the organic group won't 'stick' unless I enqueue the operation. When I don't enqueue the operation, I dpm'ed the call to og\_group and it's returning a membership object and claims it was successful, but it clearly didn't save. I don't have any errors or notices in the logs either. Here's my setup for saving the group/user relationship:

```
$values = array(
        'entity_type' => 'user',
        'entity' => $user,
        );

og_group('node', $group->nid, $values);

```

$user is a fully loaded user account and $group is the group node. I tried adding name\_field and the group audience to the values array, but this made no difference.

Here's the hook for the VBO:

```
function vbo_users_to_groups_action_info() {
 return array(
   'vbo_users_to_groups_my_custom_action' => array(
   'type' => 'user',
   'label' => t('Add users to Pro List and optional Group'),
   'behavior' => array('changes_property'),
   'configurable' => TRUE,
   'vbo_configurable' => FALSE,
   'triggers' => array('any'),
   ),
  );
}

```

Is there anything else you need to see that may be causing this?

# Answer
If anybody runs into this in the future, I had to pass the group id into the og\_user\_node field and save the user after calling og\_group():

```
$values = array(
    'entity_type' => 'user',
    'entity' => $user,
    );

og_group('node', $group->nid, $values);
$data['og_user_node']['und'][0]['target_id'] = $groupid;
user_save($user, $data);

```

You should check for any other groups the user is in and create an array of groups along with the new group id and save that into og\_user\_node, but in my situation, users are only allowed in 1 group, so this takes care of putting them in the new group and removing the old one.
> 0 votes

---
Tags: 7, organic-groups, users, cron, views
---


title: Search a content type and return JSON

text:
# Question
Title: Search a content type and return JSON
I'm trying to create a JSON API that will return an array of JSON results matching specific search criteria. It will always be searching one specific content type, but will need to match custom fields for specific search terms. I will be passing a term to match a given field, for example:

```
/api/my-content-type?first_name=bob&term_a=my+term&another_field=search+term+here

```

The response from this needs to be an array of JSON objects containing the fields for that given content type.

I've seen many modules for this, but don't seem to see any that allow searching by field. Is this something I would need to implement custom? If so, what is the best module and/or method to start from?

Im not sure if I should be using a Search API, Services, one of the many REST JSON API Modules, etc.

# Answer
> 1 votes
> I've seen many modules for this, but don't seem to see any that allow searching by field.

There are many modules which provide this feature, not necessarily out of the box, but with some customization.

I would say, the best module to start with this would be Restful.
I have personally used it for a similar use case for building the service endpoints which could be filtered using specific field values, and it work charms!
The documentation seems to have improved a lot since the last time I've seen it!

There are other modules present which help you create custom endpoint too. However, the ease of building such filterable endpoint is good with Restful as per my experience.

---
Tags: search, 8
---


# Question
Title: Print taxonomy term field in views-view.tpl.php
Do you know if it's possible to print a taxonomy term field inside a views-view.tpl.php template in Drupal 7?

For example, you would do this:

```
<?php print render($content['field_example_field']); ?>

```

in node--content-type.tpl.php.

What would be the equivalent to get a specific taxonomy term field in views-view--name-of-view.tpl.php?

Thanks in advance!

# Answer
Thanks guys for your responses, but I figured it out. The view I was targeting was a content view not a term view, didn't think it was possible to add a Taxonomy term field. So I thought I could add the term field in a template (hence the question I asked here) but I worked it out in Views instead:

Went to Relationship, added "Content: Taxonomy terms on node". Selected the Vocabularies I wanted to add in relationship. Then went to Fields, "Add" and selected "Taxonomy term: Example Field".

Sorry if I wasn't clear enough, hope this helps someone else (spent many countless hours googling this).
> 1 votes

# Answer
For this you need to create the *Row style* output template file for the view.

For ex: `views-view-fields--your_view_name--block.tpl.php`.

In this file you get the *row array* and then you can print your field like:

```
$row->field_example_field[0]['raw']['value']

```
> 2 votes

# Answer
In your *views template* file just add this line of code;

```
print render($fields['term_node_tid']->content);

```
> 1 votes

# Answer
For this you need to do the following;

*First:* ( on node page )

```
print_r($row);
exit;

```

You can see the list.

Now your can print this as;

```
$row->field_example_field[0]['raw']['value']

```

And you get the value.
> 1 votes

---
Tags: views, theming, entities, taxonomy-terms
---


# Question
Title: Create Empty User as Admin, and force entering info on login
For my website, user accounts should only be created by the admin. However, the only fields that should be given by the admin are his full name. All other fields should be supplied by the user himself. For this, I have 2 things I would like to do:

1: Allow the admin to create a new user without supplying required fields.

2: Redirect the user to their profile edit page as long as there are required fields that have not been given.

For 2, I imagine it should be possible with the rules module, although I have not yet tried this. But is there a way to do 1? One thing I have considered is to add a custom page with a simple form to create the user, and to have custom PHP code that will actually create the user. However, I am hoping this is possible without resorting to that.

**Edit**: The only information I do have are an email, username and full name. All other fields, such as address, profile picture, etc. should be provided by the user themselves.

# Answer
> 2 votes
It's not possible to create a new user without email, username and password.

The only workaround for this is to create placeholders. E.g. always enter *username@example.com* in the `email` field where *username* is the machine name of the user's full name.

As for creating the user without entering the required fields I think it's best to create a custom form. This form would only contain a textfield *Full name*.

On submit you dynamically generate the `username`, `email` and `password` (see drupal\_clean\_css\_identifier to easily generate a machine name) and create the user object.

Here's a code example:

```
$full_name = $form_state['values']['full_name'];
$username = drupal_clean_css_identifier($full_name);
$email = $username . '@example.com';

//This will generate a random password, you could set your own here
$password = user_password(8);

//set up the user fields
$fields = array(
  'name' => $username,
  'mail' => $email,
  'pass' => $password,
  'status' => 1,
  'init' => 'email address',
  'roles' => array(
    DRUPAL_AUTHENTICATED_RID => 'authenticated user',
  ),
  // If you have custom field 'Full name' do this:
  'field_full_name' => array(
    LANGUAGE_NONE => array(
      0 => array(
        'value' => $full_name,
      ),
    ),
  ),
);

//the first parameter is left blank so a new user is created
$account = user_save('', $fields);

```

# Answer
> 1 votes
Your 1. use code in a custom module, to change the behaviour of the user\_register form depending on whether the person using it is an administrator (at admin/people/create) or a regular user self-registering themselves.

As suggested at Seperate /user/register fields and admin/people/create something along the lines of:

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

  // Is logged in user admin.
  if (user_access('administer users')) {

    // Hide myfield.
    $form['myfield']['#required'] = FALSE;
  }
}

```

Alternatively:

* have your admins enter any old value for the required fields, and then use Rules to blank those fields when they have been created by an admin
* create a new form using Webform or Form API, and change the "Add user" action to link to that form instead

Your 2. can be accomplished by the complete\_profile module, or by Rules. See Force existing users to complete profile after adding required fields

# Answer
> 0 votes
If you already have email and username, then one solution would be :

* set up your user fields as non required so you can create them easily with admin
* add one Rule with conditions "If non-admin user log in, and if user fields are empty", and 2 actions : send message error "Please complete your profile in order to access website" and redirect to Profil Edit Page.

# Answer
> 0 votes
* set the rule to redirect to edit form if user logged in after creating account for user by admin without required fields.
* edit form with required fields which has to be altered by custom form.

# Answer
> 0 votes
I have a simpler solution for you,

we have 2 form for user, user registration form and user edit form

Form Ids of them is

* user\_profile\_form (for user edit)
* user\_register\_form(for user register)

So what you need is your fields are not required by default but when in edit form ( user\_profile\_form) you need set them to required with powerful Drupal Form API

and solution form you is something like

```
function yourmodule_form_alter(&$form, &$form_state, $form_id)
{
    global $user;
    if ($form_id == "user_profile_form") {
       // ym($form);
       // you also can perform this action for specified roles
        //if (!in_array('administrator', $user->roles))) {
          $form['field_mytest1']['#required'] = TRUE;
          $form['field_mytest2']['#required'] = TRUE;
            // hide other field with this method
        //}
    }

}

```

if getting required not work take look at this question and my answer there

---
Tags: 7, users
---


title: Convert db_query in EntityFieldQuery

text:
# Question
Title: Convert db_query in EntityFieldQuery
I have the following query, which works.

```
  $email = db_query('
    Select u.init as email
    FROM user__roles as r
    JOIN users_field_data as u ON r.entity_id = u.uid
    WHERE u.status = 1
      AND r.roles_target_id = :role
  ', array('role' => 'pubblisher'))->fetchAll();

```

I want to convert it to use `EntityFieldQuery`, but I didn't find any Join function in the documentation. How do I convert my code to use `EntityFieldQuery`?

# Answer
> 1 votes
As long as you only query for fields, entity query does the joins automatically for you.

Note that entity query can only return entity ID's, you then need to load them.

```
$ids = \Drupal::entityQuery('user')
  ->condition('status', 1)
  ->condition('roles', 'pubblisher')
  ->execute();

$users = User::loadMultiple($ids);

```

---
Tags: 8, database
---


title: How do I change the default front page?

text:
# Question
Title: How do I change the default front page?
How do I change the URL present under Home » Administration » Configuration » System in my Drupal site?
I want to get rid of the stuff circled in red, but it only seems that I can add different pages only in the blank input box next to it.

# Answer
It is because you run Drupal in local; if you uploaded your site to a valid domain or set a virtual host, you get rid of it.

You can set your virtual Host following How to Add Virtual Directory Alias on Apache Xampp. You could also use Acquia Desktop dev2 which handles virtual hosts by itself.
> 0 votes

---
Tags: 7, uri
---


# Question
Title: How use views exposed filters with taxonomy and panels
I need some help with the use of contextual and exposed filters with taxonomy terms views using panels.

Context:

1. I have a panels taxonomy page overriding drupal default page.
2. In this page I have a views content pane display listing nodes with contextual filter set to "has taxonomy term Id" with type "taxonomy term id from URL" and "limit terms by vocabulary".
3. In "filter criteria" section I have a content type filter and the most relevant for my case, an exposed filter: "Content has taxonomy term", "is one of... allow multiple selection..." the usual. 4- In Pane settings: Use panel path, set to "Yes".

The idea behind this is to have a taxonomy views pane showing results with exposed filters in the panel page. I.E: The user go to "animales/aves" URL and see as expected all the nodes from a content type categorized as "aves". The problem here is when the user try to filter to another animal category. In my example, the view give me no results. The URL change from animales/aves to this: animales/aves?tid\[\]=1 (or other id) but allways I get an empty view, except if I select back the exposed filter for "aves".

Any help?

Drupal 7.41 Ctools 7-1.9, Panels 7-3.5, Views 7-3.13

# Answer
> 0 votes
Not sure if you did this already under the "MORE" section.

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


# Question
Title: Are regions and features automatically created when creating a sub subtheme?
I want to inherit everything from a main theme except the layout. When I create the .info file and specify which regions and features I want are these generated automatically by drupal or do I have to specify each one in a separate .tpl file like the diagram below?

# Answer
> 0 votes
Yes, you will enherit everything unless you modify the **page.tpl.php** file located in `/sites/all/themes/yourtheme/template` folder.

The **page.tpl.php** file contains all **block regions**. Thus, you should modify this file if you want to add, remove, or move regions.

If you want to resize or theme a region, it's all css. As you will see in page.tpl.php, the regions will have a div `class` or `id`.

---
Tags: theming
---


# Question
Title: How to render a specific page as if the currently logged in user is not logged in?
Anyone know how to do this, or have an idea on how to do it?

I want to render a specific page exactly as it looks when the user is not logged in. But the trick is, the user is in fact logged in.

# Answer
For an anonymous user, the easiest way to do this is to use a second browser and visit the specific page without being logged in. An alternative to that would be to logout (but that seems to contradict with "user is logged in).

For other (none anonymous) roles, you can use the Masquerade module (for sure). You might consider using this module also for "anonymous users". However be aware of this note on its project page:

> Any previous support to masquerade as "anonymous" has always been buggy and hurts performance on larger sites. To masquerade as anonymous users, logout.

My recommendation therefor is: open that page in a 2nd browser, without being logged in.

PS: works for any currently supported release of Drupal.
> 2 votes

---
Tags: nodes, users, hooks
---


# Question
Title: How to use template_preprocess_views_view to pass a variable to a views tpl file
Since the case re-occurred to me for the second time recently, I decided to ask the question so to perhaps learn something.

In Views, the main display title (the one that usually gets rendered at the top of the view) is available in *display output* as `$title` but does not seem to be available in *style output* at all. Instead, the `$title` variable in *style output* means the name of a group if grouping is used.

What I want is to have that display title ('human name') available in *any* template as `$display_title`. So what I did was putting this code in my template.php:

```
function MYTHEME_preprocess_views_view(&$variables){
  if($variables['name'] == 'studios' && $variables['display_id'] == 'block'){
    $view = $variables['view'];
    $variables['display_title'] = $view->human_name;
  }
  dpm($variables);
}

```

...hoping to have the human title handy: `<?php print $display_title; ?>`

...but no joy. What am I doing wrong?

# Answer
As you would also know, a view has several templates, which can vary depending on the style, for example:

* Display output: `views-view.tpl.php`
* Style output: `views-view-STYLE.tpl.php`
* Row style output: `views-view-fields.tpl.php`
* Field content: `views-view-field.tpl.php`

etc.

Each of those templates has its own preprocess function. What you do in your code is only affecting the display output since you are preprocessing only the views-view.tpl.php (`template_preprocess_views_view`)

To find out which template files are available to your specific view, you can go to view edit page and under 'Advanced' section at the end of the column click on 'Theme: Information'. You will see which template files your view is using (in bold) and which template files you would use to override them.

The preprocess functions should be named after the template file, replacing the dashes with underscores. For example for `views-view-STYLE.tpl.php` would be `template_preprocess_views_view_STYLE()`.
> 10 votes

# Answer
You could use the functions:

1. drupal\_set\_title()

> Sets the title of the current page.
2. drupal\_get\_title()

> Gets the title of the current page.
> 0 votes

# Answer
If I remember right you can pass the title with the view object, add a new variable inside the view object and ust in the template file.
> 0 votes

# Answer
To address the specific question of "pass a variable to a template file"... I think you just have to use a different hook. Attach the variable to your `$view` object like this:

```
function NAME_OF_MODULE_views_pre_render(&$view) {
  $view->display_title = "What have you";
}

```

Then in a template file like `views-view--NAME_OF_VIEW--page.tpl.php`:

```
print $view->display_title;

```

Just had to do this myself and it worked great.
> 0 votes

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


title: How do I make a Graphic Button?

text:
# Question
Title: How do I make a Graphic Button?
I want to make a button on location on a php file that currently is just a hyperlink. Currently, the code segment appear in a browser with the text "Donate now", but I want it to be a paypal button instead.

All this is part of a paypal module I have set up in Drupal. I have already figured out the proper way to use a .css file with this module to modify another aspect of it. And now I want to change the textual hyperlink to a paypal button.

The line of code in question looks like this in the paypal\_donations\_single.tpl.php file:

```
<a href="#" class="donation-submit-button"><?php echo t($variables['submit_value']); ?></a>

```

The hyperlink text appears in the browser as "Donate now". This text appears in the .inc file includes\paypal\_donations.admin.inc:

```
$form[$type_key]['paypal_donations_' . $type_key . '_submit_value'] = array(
  '#title' => t('Form submit text'),
  '#type' => 'textfield',
  '#description' => t('The button text when someone sends the form'),
  '#default_value' => variable_get('paypal_donations_' . $type_key . '_submit_value', 'Donate now'),
);

```

This line of code is of particular interest to me:

```
'#type' => 'textfield',

```

Maybe there is an example somewhere that has a graphic as a '#type'.

I have an extensive list of modules already and when I did a grep-style dos/cmd file findstr command I found many examples. The one that looks the most promising is:

```
'#type' => 'image_button'

```

and the accompanying code looks like this:

```
 $form['go'] = array(
      '#type' => 'image_button',
      '#src' => $options['image'],
      '#submit' => array('ctools_jump_menu_submit'),
      '#attributes' => array(
        'class' => array('ctools-jump-menu-button'),
      )

```

based on what I can observe, I assume that all I need to do is change this:

```
$form[$type_key]['paypal_donations_' . $type_key . '_submit_value'] = array(
  '#title' => t('Form submit text'),
  '#type' => 'textfield',
  '#description' => t('The button text when someone sends the form'),
  '#default_value' => variable_get('paypal_donations_' . $type_key . '_submit_value', 'Donate now'),
);

```

into this:

```
$form[$type_key]['paypal_donations_' . $type_key . '_submit_value'] = array(
  '#title' => t('Form submit text'),
  '#type' => 'image_button',
  '#src' => $options['image'],
  '#description' => t('The button text when someone sends the form'),
  '#default_value' => variable_get('paypal_donations_' . $type_key . '_submit_value', 'Donate now'),
);

```

I only need to figure out how to best assign this '#src" variable. When I looked into the $options settings, the complexity and flexability reached new heights and I think now is a good time to ask for some help online with more experienced Drupal scripters and developers. Perhaps there is an easier way to assign this value a hardcoded path and image name.

I looked around at the code to see how this array $options is used, I could not see where the 'image' part is assined to a graphic.

I need some help, advice, and guidance.

On the chance that I have been going down the wrong direction, I did a grep search on "donation-submit-button" since this is the class name of the html tag I am interested in:

```
<a href="#" class="donation-submit-button"><?php echo t($variables['submit_value']); ?></a>

```

But the only place it appears to be defined is in a .js file:

```
paypal_donations\js\paypal_donations.js:    $(".donation-submit-button").click(function(){
paypal_donations\templates\paypal_donations_recurring.tpl.php:  <a href="#" class="donation-submit-button"><?php echo t($variables['submit_value']); ?></a>
paypal_donations\templates\paypal_donations_single.tpl.php:  <a href="#" class="donation-submit-button"><?php echo t($variables['submit_value']); ?></a>

```

and all that is denoted is the functionality, not the apparance:

```
//When user click Donate now
$(".donation-submit-button").click(function(){
  var post_form = false;
  //If any checkbox is checked set true
  if($('INPUT:checkbox:checked',$(this).closest('.donation-form')).length > 0)
    post_form = true;

  //If Other has value set true
  if($('INPUT:text',$(this).closest('.donation-form')).val() != '')
    post_form = true;

  if(post_form){
    $(this).closest('.donation-form').submit();
  }
  else{
    alert(Drupal.t('Please enter your donation amount'));
  }

```

# Answer
> 1 votes
The easiest solution is by doing it using css only.

Inspect the element with your browser and find the div class that belongs to the "Donate Now". By looking at your code I suspect it is **donation-submit-button**

So all you gotta do is:

* Add a background image
* Set the font-size to 0px to hide the "Donate Now" text.

Example:

```
.donation-submit-button a{ background-image: url("paypal-logo.jpg");
    background-size: 80px 60px;
    background-repeat: no-repeat;
}
.donation-submit-button a{ display:block; height: 60px; width: 80px; border: solid red; }

.donation-submit-button a{ font-size: 0px; }

```

See it in action, check out this JS FIDDLE

---
Tags: commerce
---


# Question
Title: Getting different results for admin versus non-admin user on view when there is a relationship
I have a `view` that shows the two newest articles with specific taxonomy rules. We got a new requirement to now exclude articles that are linked via `entity reference`.

So I added the relationship for referencing entities. With just the relationship in place and no filters added, non-admin users only see articles that are related (the relationship is not set to required).

When I add the filter that node ID of the related (referencing) articles should be NULL, non-admin users see nothing, but admin users see the results as they should be.

What can explain the discrepancy and what can fix it?

Drupal 7

# Answer
> 1 votes
Seems like this problem is related to this drupal bug https://www.drupal.org/node/1349080 .

Solution: Edit your view \> Right column "Advanced" \> Query settings: check "Disable Query Rewriting"

Simple explanation for the bug and the solution https://www.drupal.org/node/1276450#comment-10451305, quote the comment below

> Actually, this is a bug, in Drupal core, and there is a fix, in #1349080: node\_access breaks any query that has node table appearing twice with a left join. It just has not been committed to Drupal core yet, because the fix is a bit brittle and may not work in all corner cases. It has to do with the node\_access system, and any view that connects the node table or an entity table multiple times (e.g. via a relationship), when there is any access module enabled on the site, will trigger it.
>
> Disabling SQL rewriting will bypass the issue, and should be entirely safe to do, unless you have some access rules you want to enforce (such as products in an OG group that only members of that group should be able to see) -- in which case you can usually address that by adding your own explicit filter to the view instead of relying on the core node access to filter it out for you.
>
> If all your products are public, there's no need for this node\_access check.

Cheers

---
Tags: 7, entities, views
---


title: Monthly sales reports

text:
# Question
Title: Monthly sales reports
I need to create a monthly sales report in Drupal. The report should contain products/services sold during last month, quantity and the price. Sales persons have to enter monthly the information in the report. I am thinking to create the products as a content type Product with the field Month, Name, Quantity, Price, Sales person (Author).

If I display in Views the Content Type - Product, how can Users (Sales role) enter the Quantities? How to control that the quantities for all products are set? How to limit it to 1 Report per month? How to identify which users have entered the report and which users didn't do it?

I would appreciate very much if you can guide me how to better achieve this monthly reporting objective!

# Answer
> 1 votes
This seems like a perfect usecase for the Forena module. Forena is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports (and/or charts). Various DBMSs are supported, such as Oracle, MS Sql, Postgress, SQLite, MySQL, any PDO compliant DBMS ... And there are quite some reasons for considering Forena.

Visit the Forena HowTos page for some links (near the bottom) to some live demo / showcase links, and experiment a bit with some of its demo samples.

Some of its features that I think will help to answer this question (and which only is a matter of minutes to deliver the features you're looking for):

* Create a report about "**products/services sold during last month, quantity and the price.**" Have a look at the "Northwind database" demo videos, which I tink are pretty close to what you're looking for. Such as these videos:
* If you don't want to implement some validation about "**... that the quantities for all products are set?**" ... (or cannot do so for whatever reason), then you could create a report to find all cases that violate (as an alternative).
* To create a report about "**identify which users have entered the report and which users didn't do it?**"

Disclosure: I'm a co-maintainer of Forena.

---
Tags: views, log-messages
---


# Question
Title: How to (double) opt-in the user registration process before admins are notified for approval?
I was wondering if you can provide, with drupal core or any module, a double opt-in registration process.

Ideally, users who fill out a register form should receive an email with an opt-in activation link. Clicking that link, confirming their email, would it trigger the standard functionality of awaiting admin approval.

I tried LoginToBoggan but I'm pretty sure it does not provide double opt-in.

Is this implemented somewhere?

Edit: to prevent confusion: I know Drupal provides double opt-in for an "active user", but not for the registration itself. I would like users to verify that they want to register. Ideally:

1. Visitor enters their email to register
2. Visitor gets an email which he has to verify
3. After the link is clicked, the user gets created

How it currently is:

1. Visitor enters their email to register -\> Blocked user gets created!
2. Either admin approves or user has to "double opt-in"

# Answer
> 3 votes
If I understand you correctly, this is default Drupal functionality.

* Go to the **Account settings** (`admin/config/people/accounts`).
* Under **Who can register accounts?**, Select the option **Visitors, but administrator approval is required**.
* Directly below this option, select the checkbox **Require e-mail verification when a visitor creates an account.**

That's all.

# Answer
> 1 votes
As far as I know, there is no such module which provides exactly what is required to do. However, I think you could still implement a work around in the following way:

1. Follow the procedure mentioned by @Patrick Scheffer in his answer with one change, instead of **Visitors, but administrator approval is required** select **Visitors** (not going with normal admin approval required, **yet**).
2. Create a new user role "unverified" on your site.
3. The user registration could be changed in the following way:

* A user registers to the site.
    * A welcome email with the one time login link is sent to the email for email verification.
    * User clicks on the email and logs in the site. *Note:* At this step the status of the user account will be changed from *blocked* to *unblocked*.
    * Using the Rules module, create a rule to assign a user role *unverified* to the user who uses one time login link.
    * The same rule could be used to send an email to the administrator about the creation of the new user account.
4. Create a view of users with filter "Role=unverified". Using views bulk operations module, add a operation of removing user role from the list of the selected users. Using this view the admin could remove the "unverified" role from any user and make him/her *normal* authenticated user.
5. The use of this "unverified" role could be done at various places depending on the requirements. Listing few possibilities here:

* Using rules, you could log out the user as soon as the user tries to login if the user has "unverified" role associated with him/her. And you could display a message too in the rule saying that the account is pending approval.
    * There could be some cron process implemented, which could find the list of users which are "unverified" for a period or time (say 1 month) and delete them.
    * You could send email reminders to admin about the pending approvals.

Hence, we are tweaking the normal registration process where admin approval doesn't happen when creating the account, but after the "unverified" role has been associated with the user account. Almost all of the above could be done with no custom code and could be maintained using Features, which makes is maintainable as well :)

---
Tags: 7, users
---


title: How do I 'reset' a theme completely?

text:
# Question
Title: How do I 'reset' a theme completely?
I think I have deleted some .css theme files in my local directory by accident and when I delete All the theme's files to re-install and get the original files back, they still aren't there. Is there a way to reset the whole theme folder?

# Answer
If it's a core/contrib theme, just download the original and replace the modified version with it.

If it's a custom theme, just restore from whatever backup you have available (or from Trash or your OS's equivalent feature).

If you're wondering if Drupal somehow keeps track of file system changes and might be able to help you restore deleted files - it doesn't (I've yet to come across a framework that would do this).
> 0 votes

# Answer
If you're using GIT, just compare your current branch with whatever you have available to get more details about what happened, and then perform the appropriate GIT action (command) to get back to that "reset" point you're looking for.

As a variation, the Hacked! module might be of some help also (if this question is about a contributed module). I.e to find out what is "currently different from the module on drupal.org. Some details about it (from its project page):

> This module scans the currently installed Drupal, contributed modules and themes, re-downloads them and determines if they have been changed. Changes are marked clearly and if the diff module is installed then Hacked! will allow you to see the exact lines that have changed.

As per your "***I think I have deleted***": make sure that you also cleared the appropriate caches ... it doesn't hurt, but sometimes it helps (and turns out to be "the" solution).

PS: if you're NOT using GIT, then consider the issue you suffer now as a great lesson why you should ...
> 0 votes

---
Tags: files
---


# Question
Title: Custom layouts with the Display Suite module
How can I make a custom layout with the Display Suite module in Drupal 8?

I checked the example for Drupal 8, but that didn't work for me.

Could anyone help me?

# Answer
In your theme folder, create a THEMENAME.layouts.yml file:

```
clean_empty:
  label: Clean empty page layout
  category: Display Suite
  class: '\Drupal\ds\Plugin\DsLayout'
  type: partial
  template: templates/nodes/clean-empty
  regions:
    title:
          label: Title
    ds_content:
      label: Content

```

Then just create your twig file. In this example, create a clean-empty.html.twig file inside THEME/templates/nodes:

```
{#
/**
 * @file
 * Custom display suite layout
 *
 * Available variables:
 * - title
 * - ds_content: content region
 */
#}
{{ title_suffix.contextual_links }}
<h1>{{ title }}</h1>
{{ ds_content }}

```
> 4 votes

---
Tags: 8, display-suite
---


# Question
Title: Create user after node created and assign node entity reference to it
I have a content type with name `hotel` it have `entity reference` field that referenced to `users` entity, I want when admin create a node automatically created a user according to `hotel email field` and then set `user entity reference` field with that new created user.How can I do it automatically?

I create a rule with below structure but **not work**

```
{ "rules_create_user_based_on_hotel" : {
    "LABEL" : "create user based on hotel",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--hotel" : { "bundle" : "hotel" } },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "user",
            "param_name" : "[node:field_hotel_users]",
            "param_mail" : "[node:field_mail_hotel]"
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : { "data" : [ "node:field-user-ref" ], "value" : [ "entity-created" ] } }
    ]
  }
}

```

# Answer
You can also handle it programmatically in your custom module.

```
function yourmodule_form_alter(&$form,$form_state,$form_id){
     global $user;

     if($form_id=='hotel_node_form'  && !isset($form['nid']['#value'])){
         $form['actions']['submit']['#submit'][] = '_hotel_user_register_submit';
     }
}

function _hotel_user_register_submit($form,$form_state){
    $uname=$form_state['values']['field_hotel_users']['und'][0]['value'];
    $uemail=$form_state['values']['field_mail_hotel']['und'][0]['email'];

    $new_user = array(
     'name' => $uname,
     'pass' => rand(1000000,9999999), // note: do not md5 the password
     'mail' => $uemail,
     'status' => 1,
     'init' => $uemail,
     'roles' => array(
        DRUPAL_AUTHENTICATED_RID => 'authenticated user',
    ),
);
    $nuser=user_save('', $new_user);
    $node=node_load($form_state['values']['nid']);
    $node->field_user_ref['und'][0]['target_id']=$nuser->uid;
    node_submit($node);
    node_save($node);
}

```
> 3 votes

# Answer
* Download the Rules module
* Enable Rules and **Rules UI**

Add a new rule

* **React on event**: After Saving New Content (it's listed under NODE)
* **Restrict by type**: Hotel

Under Action

* Add Action of **Create New Entity** \>\> ENTITY TYPE: **USER** \>\> For your EMAIL field, Ex: **If you called your field "Email"** then it's **node:field-email**. `For user name, I guess you will also need to create a field in the node for that too. Then do same steps as e-mail`

Note: You can always click on "DATA SELECTORS" to see all the tokens you can use.

* Add Action of **Set data value** \>\> select your entity ref field (Ex: **If you called your field "Test"** then it's **node:field-test)** \>\> for Value use **entity-created:uid**
* Add action of **Send Account Email** (`listed under USER`) \>\> Account: **entity-created**

> You can modify the e-mail templates here `/admin/config/people/accounts` use tokens for your needs.
>
> Let me know how this goes, no time to test this Rule.
> 4 votes

---
Tags: users, entities
---


title: Menu disappears on small screens

text:
# Question
Title: Menu disappears on small screens
On this site I implemented the Multi Level Push Menu. All works fine, but the menu disappears on small screens (tablet width and below). I use Bootstrap 3 und Drupal 7 in this project.

I already tried it with increasing the `z-index` on `#menu`, but it didn't worked.

I'm thankful for any suggestion.

# Answer
According to this the problem, was that a div container pushed the menu away.

The old and wrong container was:

```
<div class="col-lg-12" id="content-container" style="
display: table-cell;">

```

It could be fixed by adding additional bootstrap classes:

```
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12" id="content-container">

```
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Use part of the user_profile_form on another page
My users enter a phone number on registration. The amount of values that can be entered is set to unlimited. Setting this changes the field so that you can add another field below to add additional phone numbers. I would like the users to be able to add more numbers after registration without having to go to /user/%user/edit

I am trying to return **just the phone number field** on another page. However I cannot seem to get any of that form displayed on another page. When I have been displaying other forms I have called them like this:

```
drupal_render(drupal_get_form('user_profile_form'));

```

This does return part of the form, First Name, Last Name, Country (all custom fields) but not the phone number field. I also get quite a few errors
Undefined index: user\_profile\_form in drupal\_retrieve\_form()
Undefined index: #user\_category in block\_form\_user\_profile\_form\_alter
Undefined index: #user\_category in overlay\_form\_user\_profile\_form\_alter()
Undefined index: #user\_category in system\_form\_user\_profile\_form\_alter()
Undefined offset: 0 in uc\_roles\_form\_user\_profile\_form\_alter()

Obviously I am doing something very wrong...

# Answer
I made this work based on the work by Erik. I guess you could do `['#access']=false` for all the values you don't want.

```
//Provide a custom page at /custom-profile to access our custom profile form
function mymodule_menu() {
  $items['custom-profile'] = array(
   'title' => 'Custom Profile!',
   'page callback' => 'mymodule_custom_profile',
   'access callback' => TRUE,
   'type' => MENU_NORMAL_ITEM,
 );
}

//displays the custom form at /custom-profile
function mymodule_custom_profile() {
  module_load_include('inc', 'user', 'user.pages');

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

  $form = drupal_get_form('user_profile_form', $user, 'account', 'custom');

  return $form;
}

function mymodule_form_user_profile_form_alter(&$form, &$form_state){
  //modifies the form_user_profile DO CUSTOM STUFF BELOW!
  if(isset($form_state['build_info']['args'][2]) &&
           $form_state['build_info']['args'][2] = 'custom'){

   //rename submit button
   $form['actions']['submit']['#value'] = t("dooo it!");

   //remove a few account things from this page
   $form['account']['#access']=FALSE;

   //needs to be there for the picture to work
   form_load_include($form_state, 'inc', 'user', 'user.pages');
  }
}

```
> 5 votes

# Answer
Try this

```
module_load_include('inc', 'user', 'user.pages');
global $user;
print(drupal_get_form('user_profile_form', $user));

```

This will work.
> 3 votes

# Answer
```
drupal_get_form('user_profile_form',$user,'account', 'my_parameter');

function my_module_form_alter((&$form, &$form_state, $form_id) {
  switch($form_id) {
      case 'user_profile_form':
        $info =  $form_state['build_info']['args'][2];
        if ( $info == 'my_parameter' ) {
           //do something with the form
           $form['my_field']['#access'] = false ;
           //prevent ajax errors
           form_load_include($form_state, 'inc', 'user', 'user.pages');
        }
      break ;
   }
}

```
> 1 votes

# Answer
Based on @pawel-dubiel comment I added user.pages.inc directly to hook\_menu():

```
function mymod_menu() {
   return array(
     'my-path' => array(
        'page callback' => 'mymod_page_callback',
        'file' => 'user.pages.inc',
        'file path' => drupal_get_path('module', 'user'),
     )
   );
}

```

Works like a charm and using hook\_init() is avoided.
> 0 votes

# Answer
Trying to fetch a single field from a form doesn't make sense IMHO.

If you want to update a single value in the database for this field, you'd better code your own form and manage the submit and validate functions to update the database yourself.
> -1 votes

---
Tags: 7, forms, users
---


# Question
Title: Export/Deploy Drupal site/page to static? (no cache)
I wonder if there is an existing module that can help in the subject. I am not looking for a caching module (like Boost or Varnish), but a way to export my whole site (or only certain pages) into static. The idea is that I want my web server will be a very simple and light and will only serve static files (html/css/js) - no database on production, no php engine will be installed on server. All the Drupal engine will be on another server, export will be done each time adding/editing/changing a node or view, and a new set of html files will be created in a directory structure. These files will later on be copied to the production site that will serve always and only static files, no .htaccess that will check requests if file exist etc.

Is there a module for that, or a workaround that this can be achieved with Drupal?

Thanks

# Answer
> 5 votes
I use HTTrack for this, also there's this article on drupal.org: Creating a static archive of a Drupal site.

# Answer
> 2 votes
There is a new Drupal 7 module providing this functionality is Static Generator

**Static Generator:**

> The static module generates a complete copy of your website in html form including all js, css, images and other assets. This can then be transferred to run the website from a simple web server without PHP, MySQL or memcache.

**Benefits:**

* Performance: No PHP, Mysql, etc on public facing site. Everything is a static file so it is served very quickly.
* Security: The static version of the site does not have a database, user accounts or any other form of user interaction (except 3rd party integrations) so it is much more secure.
* Reliability: Most of the usual failure points are gone. PHP, MySQL, memcache, varnish, etc are no longer part of the static site.

**Limitations:**

Due to the fact that there is no database or PHP behind the website, any functionality that requires it can't be used. 3rd part libraries can fill in most of the needed functionality.

Some of the parts that can't be used are:

* No views filters
* Drupal comments
* Drupal search.
* No drupal forms.
* No context (not the module) - meaning you can't change the page contents based on the user unless you do it in javascript.
* No ajax callbacks (except pre-generated GET requests)

Pagers DO work as long as they are passed through hook\_preprocess\_pager.

# Answer
> 1 votes
GNU wget is a WWW client that can download the pages of your site and store them locally. Use the `-r` option to download pages recursively (i. e. follow links to pages on the same site found on the current page). It can also convert absolute URLs to relative one (using the `-k` option).

# Answer
> 0 votes
I'm looking for something similar. I've searched the modules and found the following options, but haven't looked into either of them yet:

We want to use S3 or another static file serving CDN service for our site, so it's possible something more like the following will be helpful:

Another thought is that it may be possible to leverage a caching framework like boost and add something to push the files to production as it caches them.

# Answer
> 0 votes
You can use module Wget Static - Generate HTML and Save To FTP / Webdav, which exactly does what you want. Infact, I have also deployed the same architecture as you have discussed just above.

You can select content for static HTML generation, which can also be bypassed using query parameters. Then the second part comes where you perform static html generation using WGET application. This Wget Static Module almost covers all the options necessary for Static Data Generation.

Not only this, finally beside downloading that generated static html, you have option to either save it to **FTP server** or **Webdav Server**, which again supports Two factor Authentication.

---
Tags: theming, importing-exporting, deployment
---


# Question
Title: How to get new password by mail instead of password reset url (Forgot password)
When we click on "Forgot your password" and enter email id, Drupal will send password reset URL by mail.

**But is it possible Drupal send any random password by email instead of URL?**

I have checked Registration Password Token but this will helpful for new user registration only.

Is there any module available?

# Answer
> 3 votes
You can use Recovery Password (Email New Password) module.

> Recovery Password module makes it possible for Drupal to send any random generated password(new password) by email instead of URL to the user.

Refer to the module page for detailed description. Feel free to contact me, in case of any issue. I'm maintainer of this module.

---
Tags: 7, emails, tokens, users
---


# Question
Title: Drupal views custom filter, check if row exist
I need help with a query. I am having a really hard time going in the right direction.

I have a custom multi-value field, containing one 'name' and one 'id'. I want to filter on contents that:

* None of the delta has a name 'test' ('test' is a name example).
* OR, the name is 'test' and the id is equal to 0.

I was planning on having the logic in the customer filter, like so:

```
class my_module_handler_filter_field_name extends views_handler_filter_boolean_operator {
  function query() {
      // My custom code here
  }
}

```

But I don't have much success for now. I managed to filter rows where `'name' = 'test'` using:

```
$this->query->add_where($this->options['group'], 'field_name', 'test', 'LIKE');

```

But if I do the opposite with '`NOT LIKE`', it just shows me every row not equal to 'test' (also including rows from an item that has one name = 'test'). This behaviour is normal, I know it is simply not the right way.

A table example:

```
    entity_id    delta    store_name  id_in_store
    ---------------------------------------------
    1            0        Amazon      0
    1            1        BestBuy     123442111
    2            0        Apple       123442123
    2            1        Microsoft   124423459
    2            2        Google      112559002

```

`Entity_id` is a node ID for a '`product`' content type. I want to be able to know which products are sold at `Amazon`. And there are 2 ways to know it:

* The field have a delta where store\_name is '`Amazon`', but id = 0.
* Or the the field doesn't have any delta where store name is '`Amazon`'.

# Answer
> 0 votes
I guess you are looking for something like this, but you might need to tweak it a bit. You can group db\_or and db\_and, then combine them like this. Basically create two 'and' groups where all conditions need to match. Then combine those in an 'or' group, where one of the conditions needs to match.

```
function query() {
  $and1 = db_and();
    $and1->condition('field_name', 'test', 'LIKE');
    $and1->condition('field_id', 0);

  $and2 = db_and();
    $and2->condition('field_name', 'test', '<>');

  $combine = db_or();
    $combine->condition($and1);
    $combine->condition($and2);

  $this->query->add_where(
    $this->options['group'],
    $combine
  );
}

```

---
Tags: views
---


# Question
Title: How to convert subset of users into a content type?
I have a Google Map set on view of the node type. I am mapping several piece pieces of content on that map (group meeting locations, organization meeting places, etc). I would also like to be able to add my users to this map but I'm not given "users" as a content type in my list of options.

For this reason I want to take a subset of my users and create a new content type to add to the map. I know I could map a view the users, so it looks like users are a special content type.

So, it seem like the best approach is to create a content type based on a subset of my users (users that aren't admins, or who register under member, chapter head, etc roles).

I realize I could do this manually, and then have the admin add the users that match the criteria, but that seems like a work around, and fairly tedious.

With new users, I could probably hack together a rule that populates the content type from the profile fields, but I have a substantial amount of registered users already.

So, is there some way to populate a content type with user fields? Such that the content type was populated with the fields from every user of a particular role.

# Answer
Content types are not optimal for this use case. Use entities instead.

Create an appropriate user entity to map. You can have several bundles within it to represent any relevant different types of users.

Then you will need to relate the user entities to the actual users. It's up to you how you do the relating. You can use entity references or the relation module.
> 0 votes

---
Tags: users
---


# Question
Title: Existing site drops me back into the install routine
Existing site drops me back into the install routine and when I succumb and try to go through the install, it tells me:

* I need to create a sites/default/settings file when it already exists; even when I delete that and create a new one, I get the same error message
* Similarly, it says I need to create a sites/default/files directory, even when it already exists; when I try to delete the old one and start over I get a bunch of denials and when I try to change the properties, I get a bunch of messages telling me I can't do that.

Do I have to scrap the whole site and start over? Hopefully I can keep the Drupal DB which has some newly-created content pages.

And while we are at it, when I set the properties for a file or folder, is Drupal considered the Owner, Group, or Other?

# Answer
> 1 votes
This seems like a permissions problem. If you are in Linux, use the "chmod" command to set the correct permissions for settings.phpYou may need to have superuser privileges to do this so see your site admin.

Often, the web-server runs as user "www-data" with group "www-data" so you may need to use the "chown" command (once again with superuser privileges) to change its ownership first.

Example:

```
# sudo chown www-data:www-data settings.php

# sudo chmod 444 settings.php

```

You will have to adjust the permissions again before editing this file in the future.

---
Tags: installation
---


title: Change appearance of search form

text:
# Question
Title: Change appearance of search form
I want to change the appearance of the Drupal 7 search form. I used this code in my preprocess-html.inc file for my Omega subtheme. It didn't work. How do I assign html classes to divs within the Drupal 7 preprocess-html.inc file?

Here's what I put in that didn't work:

```
<html>
<body>
<?php

function mythemename_form_search_block_form_alter(&$variables) {
  // custom functionality here

}

?>
    <div class="row">
        <div class="col-md-3">
            <div class="input-group">
            <input type="text" class="form-control" placeholder="Search for...">
            <span class="input-group-btn">
            <button class="btn btn-default" type="button">Go!</button>
            </span>
            </div>
        </div>
    </div>

</body>
</html>

```

To clarify, how do I add this bootstrap html code to the template file? I need to add these classes to the search form.

# Answer
To design the search block form you can override the existing search-block-form.tpl.php in the theme's template folder.

```
<?php

$variables['form']['search_block_form']['#attributes']['placeholder'] = "Search for...";
$variables['form']['search_block_form']['#attributes']['class'] = "form-control";

?>

<div class="row">
  <div class="col-md-3">
    <div class="input-group">
      <span class="input-group-btn">
        <?php if (empty($variables['form']['#block']->subject)): ?>
          <button class="btn btn-default" type="button"><?php print t('Go!');?></button>
        <?php endif; ?>
        <?php print $search_form; ?>
      </span>
    </div>
  </div>
</div>

```
> 2 votes

---
Tags: 7, hooks, search, theming, bootstrapping
---


# Question
Title: Implement parallax effect on Header image from Content type field
I have a Header image which i can upload *per node* from my Basic-page Content type. I want to implement this parallax effect, on my Header image section. But I need to add:

`<div class="parallax-window" data-parallax="scroll" data-image-src="/path/to/image.jpg"></div>`.

How do I add `data-image-src="/path/to/image.jpg"` to the wrapping `<div>`? It has to be dynamic and per node you must be able to attach a specific image.

# Answer
I fixed it with a much easier way:

**1)** I installed the Image URL Formatter module

**2)** now i am able in `Manage Display` \> `Full content` \> Field: `header_image` \> under **Format** i can choose `Image URL`

**3)** Now in my `page.tpl.php` i can call my `header_image` URL like:

```
<figure>
   <div class="parallax-window" data-parallax="scroll" data-speed="-0.2" data-image-src="<?php print render($page['header_image']); ?>"></div>
</figure>

```
> 0 votes

# Answer
Where do you need to add that code? Into `field.tlp.php`, `node.tpl.php` or `page.tlp.php`? Is it D7 or D8?

If you need to extract `src` atribute (`/path/to/image.jpg`) from some `HTML` code (for example from the `node.tlp.php` field) then use Google. When you will have `src` then you can create desired `<div>` element in your template files.

As universal answer as detailed question was.

**Update:**

I found that you have attached your site so I suggest this:

1. Create block in Views for header image field
    * NID as Contextual Filter
    * Enable cache per page
    * Output header image field as src (only image url) - there is such option in views or use this module
    * Override that field (`rewrite the output of this field`) with something as `<div class="parallax-window" data-parallax="scroll" data-image-src="[image_src]"></div>`
    * enable block in proper region only for "Basic-page" CT
> 0 votes

---
Tags: javascript
---


# Question
Title: What are the required fields to create user through social media login?
I want to integrate **Social Media Login** (which is not a module name, I am going to integrate the HybridAuth Social Login module) in my website. So that I just want to know the required (by our website Drupal signup) fields in social sign up process.

I guess that username and email are required, but is the password required?

# Answer
> 1 votes
For Social Media Login Password field is not required. Only Username, Email-ID is required. After register with with social media login, Your account is pending for approval by the site administrator. You will receive an email once your account has been approved and you can then login with your Google account.

---
Tags: 7, users
---


# Question
Title: Is it possible in Views to get parent term of parent term all the way up a tree
I'm at my wits end on this. Here's my situation:

1. I have a content type which references a Vocabulary of geographical areas which actually has 6 levels ("Island Chain \> Region \> Province \> City \> District \> Precinct").
2. I've used Hierarchical Select to control data entry, and set it so that the entire lineage is kept in each attached node - the node should be attached at the precinct level.

Now, what I want to do is to create a View which allows me to display a table of nodes, grouped by geographical area, and at the same time allow the user to select the geographical area he wishes to display (preferably at any level in the hierarchy).

I've already done something like this using a View by Taxonomy formatted as a table, attaching the content, and then displaying in each table row the node data, the term, and the parent term. However, this only seems to work for two levels (ie a Vocabulary where there is only a parent/child relationship), and I'm stuck on displaying the bottom level, then its parent, then its parent again, all the way up to the top and all in the same row so that I don't get duplicate lines and can group/aggregate data at all these different levels.

By the way, it seems that the Hierarchical Select Views module still does not work for D7 - or at least, I can't find out how to display it.

# Answer
> 0 votes
use Client-side hierarchical select" module.

1)Force selection of deepest level (If checked the user will be forced to select terms from the deepest level.)

2)Parent (Allows to select a parent term to use only a subtree of a vocabulary for this field.)

3)Labels per hierarchy-level

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


# Question
Title: What is the correct way to save checkboxes values on form submission?
The FAPI documentation gives the following instruction and example:

> **checkboxes**
>
> Description: Format a set of checkboxes. #options is an associative array, where the key is the #return\_value of the checkbox and the value is displayed. The #options array cannot have a 0 key, as it would not be possible to discern checked and unchecked states.

```
$form['high_school']['tests_taken'] = array(
  '#type' => 'checkboxes',
  '#options' => drupal_map_assoc(array(t('SAT'), t('ACT'))),
  '#title' => t('What standardized tests did you take?'),
  ...
),

```

I have the following element in my form constructor:

```
'audio_options' => array(
  '#type' => 'checkboxes',
  '#title' => t('Options'),
  '#options' => drupal_map_assoc(array(
    t('Controls'),
    t('Autoplay'),
    t('Loop'),
    t('Buffer'),
  )),
  '#attributes' => array('class' => array('container-inline')),
),

```

and the following in my submit handler:

```
$node->field_audio_options[LANGUAGE_NONE] = $form_state['values']['audio_options'];

```

On submission the error thrown is:

> PDOException: SQLSTATE\[HY000\]: General error: 1366 Incorrect integer value: 'Controls' for column 'delta' at row 1

Why does the documentation say that you can use a string as the options key, when presumably it is saved in the delta column of the field's table, which requires an integer?

What is the correct way to save checkboxes values on form submission?

Thanks.

# Answer
The arrays aren't of compatible formats, you need to prepare them yourself:

```
foreach (array_filter($form_state['values']['audio_options']) as $selection) {
  $node->field_audio_options[LANGUAGE_NONE][]['value'] = $selection;
}

```
> 3 votes

---
Tags: 7, forms
---


title: Two forms in register page Drupal

text:
# Question
Title: Two forms in register page Drupal
I'm using Profile2 and Profile2 registration path module and I created two profiles.

I want to display their registration form in `user/register` page. So two forms in one single page.

I set their path to `user/register` but these forms merged together. But what I want is two separate forms.

Like this:

Any suggestions?

# Answer
> 3 votes
You can do it simple, add 2 form concurrent to the page you want ( if they are block put two block in that page) and then with simple Jquery you can handle it with something like below code

```
(function($){
// change jquery selector with real ones
$('.user-register1,.user-profile-register').hide(); // or you can hide them with css
var selector= $('your radio option selecotr').value();
if(selector==1) {
     $('.user-register1).show();
     $('.user-profile-register').hide();
}
elseif(selector==2){
     $('.user-register1).hide();
     $('.user-profile-register').show();

}

})(jQuery);

```

**This code IS the way how can you achieve it and if you copy/paste it it will not worked till you changes its selector and values with your forms**

---
Tags: users
---


# Question
Title: How the RTL css system works in drupal specially in omega theme?
I am building a *multilingual* site (using Omega theme) which has two languages, one *LTR* and the other is *RTL*.

Can someone please explain how the *RTL* mechanism works for css in Omega theme?

# Answer
The css file with the rtl at the end will be loaded whenever you have a RTL language added to your site. in Omega as the CSS files are generated by Scss you need to create a scss file with the rtl at the end of the file so at the time of compiling the scss you will have the rtl css files ready to use. The RTL files will override the original files.
> 1 votes

# Answer
As far as I can see, adding a global-rtl.css file to your subtheme's CSS folder will allow you to have CSS applied when an RTL language such as Arabic or Hebrew is activated. However, for me, adding similar RTL css files to cater for other CSS files in the Omega hierarchy, such as adding an alpha-default-rtl.css file, has no effect and they are overwritten by the alpha-default.css file's CSS.
> 0 votes

# Answer
By default Drupal check the current used language for the logged-in user and if its LTR it will load all defined CSS files normally, and if the language is RTL (Hebrew, Urdu, Arabic ...) it will load the default defined CSS + any file with the same name for the CSS files defined in your theme/module that is suffixed with "-rtl.css".

example:

you have theme defines CSS file:

your\_theme\_name/style.css

in English it will be loaded normally.

http://www.example.com/sites/all/themes/your\_theme\_name/style.css

in your RTL language the style.css file will be load then the style-rtl.css like

http://www.example.com/sites/all/themes/your\_theme\_name/style.css http://www.example.com/sites/all/themes/your\_theme\_name/style-rtl.css

check this: https://www.drupal.org/node/222782

NOTE: you don't need to define the RTL css files in your .info files.
> 0 votes

---
Tags: i18n-l10n, theming
---


# Question
Title: Control access to node by entity reference on User record
Let's say I have a Content Type of fruit. I want to control access to individual nodes of type fruit by an entity reference on a user record. What is the best way to do that?

In other words, if a user record has an entity reference field which references the nodes titled "orange" and "banana", he should only have access to those two nodes of the Content Type fruit.

\[Someone below suggests Node Access User Reference, but that doesn't actually apply to this situation\].

# Answer
> 2 votes
The Node Access User Reference module is probably what you want. From the module page:

> Gives content access permissions to users for content that references the users with User reference or Entity reference.
>
> This is great if you want your content authors to be able to choose additional authors, or choose who can view their content, as well as being able to display the list of authors or viewers within your content, or in views displays.

---
Tags: nodes, users, entities
---


title: How I can view facet view key?

text:
# Question
Title: How I can view facet view key?
I have module where used this code:

```
$variables['facet_metal_level'] = module_invoke('facetapi', 'block_view', '8Ratyom2YlpSn79FmHOAv8S1HaSXS6HJ');

```

How and Where I can find this view key `'8Ratyom2YlpSn79FmHOAv8S1HaSXS6HJ'` ?

# Answer
It's delta of block. You can receive it via this code:

```
$delta = facetapi_hash_delta(facetapi_build_delta('SEARCHER@MACHINE_NAME_OF_SEARCH_INDEX', 'block', 'MACHINE_NAME_OF_FACET'));

```

Example:

```
$delta = facetapi_hash_delta(facetapi_build_delta('search_api@fr_node_index', 'block', 'field_price'));

```
> 1 votes

---
Tags: views, search
---


# Question
Title: don't allow multiple users with same email
I've got a site using Commerce. On checkout a user is created to allow access to files, order history etc.

I just had a customer that couldn't find his files and discovered that he had two accounts registered to the same email address. So it seems my system isn't checking for accounts already registered to the same email address.

How can I make sure that

1. There's only registered an account in the event that the email used for the order haven't been used on the site before?
2. If the email has been used before the new order is attributed to the existing user?

**Edit**

After reading @Neograph734's answer below I checked my rules. And they look right to my eyes, so I'm a bit confused as to what can cause this:

Weight 1: Assign an anonymous order to a pre-existing user

Weight 2: Create a new account for an anonymous order

# Answer
Drupal by default does not allow multiple users with the same email if you try to create them through Drupal forms. If users are created by code this check is not performed.

My best guess it, that this caused by one of the rules Drupal commerce ships with. Specifically the "Create a new account for an anonymous order" rule. This rule fires when a user who is not logged-in completes checkout. It should check if the email is already registered, but might have been altered. Alternatively you might have a similar rule created yourself or by a module that does not check if the e-mail is already existing.

Most of Drupal commerce's behavior is controllable by rules, so I'd start looking there for rules that create users.
> 1 votes

---
Tags: 7, commerce, users
---


title: Drush 8 hangs with any command

text:
# Question
Title: Drush 8 hangs with any command
Up until recently, I've been using version 6 of drush, and it worked like a charm. Since I started delving into Drupal 8, I installed drush 7 on my Mac using the install instructions (using Composer) for global drush. Initially, it was fine, but whenever I try to run it now, it just hangs. When I run it with -d, it gets this far:

```
Using the Drush script found at /Users/steve/.composer/vendor/drush/drush/drush.launcher using pcntl_exec

```

Running `which drush` shows the correct path (`/Users/steve/.composer/vendor/bin/drush`), but like I said, running drush by itself or with any other command, it just hangs. From what I understand, the only error logging is to the screen, but since there's nothing being displayed to the screen, I'm not sure where to look. I don't have memcache installed (unlike this guy), so I know that's not the problem. Any suggestions?

Thanks

**UPDATE:** I am using Drush 8 not Drush 7 (I fixed the title accordingly). After a couple days, it's back to hanging again, and even using `-d` shows nothing.

# Answer
> 1 votes
Only Drush 8 is compatible with Drupal 8. See http://docs.drush.org/en/master/install/#drupal-compatibility

# Answer
> 0 votes
Well, it looks like the Stack Exchange effect (post a question, and the problem is solved) worked. Actually I just restarted my computer (the Microsoft method of support), and it's now working fine.

---
Tags: drush, 8
---


# Question
Title: Why is my rules created shipping profile not being used?
I've created a rule with the intention of pulling an address from the users account and creating a shipping customer profile type instead of showing the user an address field to enter shipping (The site is designed for customers to sell to their customers so someone might be looking over their shoulder and we don't want them to have to type their address in multiple times a day (even if it's saved)) while the rule creates a shipping profile type just fine if I don't have the shipping information pane in the process I don't get rates however I can look at the backend and have a properly (as far as I can tell) filled in shipping profile

A copy of my rule so far:

```
{ "rules_shipping_address_test" : {
    "LABEL" : "shipping Address Test",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "-10",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_shipping" ],
    "ON" : { "commerce_shipping_collect_rates" : [] },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "commerce_customer_profile",
            "param_type" : "shipping",
            "param_user" : [ "commerce-order:owner" ]
          },
          "PROVIDE" : { "entity_created" : { "shipping_info_unsaved" : "Customer Profile Shipping information Unsaved" } }
        }
      },
      { "data_set" : {
          "data" : [ "shipping-info-unsaved:commerce-customer-address" ],
          "value" : [ "site:current-user:field-primary-shipping-address" ]
        }
      },
      { "entity_save" : { "data" : [ "shipping-info-unsaved" ], "immediate" : "1" } }
    ]
  }
}

```

(it's not important now but in the future I'm planning on allowing the user to choose between 2 profiles on their account)

Update 1: After looking at a dsm of the order on a backend administration view that I was attempting to add shipping to I find that commerce\_customer\_shipping is an empty array which I assume is my problem that even though I'm creating and saving a profile it's not being set to the order?

# Answer
It doesn't appear that you're assigning the profile you created to the order. You need to set the order's shipping profile to the one you just created.
> 1 votes

---
Tags: rules, users, commerce
---


# Question
Title: Trouble enabling view modes for content types
I have a custom view mode and need to enable it for a node type. I need to enable it through my module, and it seemed like hook\_entity\_info\_alter() is the way to go, but it's not working. Am I missing something?

My code:

```
function mymod_entity_info_alter(&$entity_info) {
    $entity_info['node']['view modes']['vm_mid_box'] = array(
        'custom settings' => TRUE,
        'label' => 'Mid Box'
    );
}

```

EDIT: I create the displays in Display Suite, and am using the export data dumped into DS hooks.

# Answer
> 0 votes
Late answer, but for anyone else looking, to get your view mode to display try either visiting the module page or disabling then re-enabling your module. Afterwards clear the cache.

---
Tags: 7, nodes, display-suite, entities
---