# Question
Title: How to add a column to the list of group members or create a Views equivalent of it?
I use the "Group" module and I want to add a column "Email Address" on the page that lists the members of the groups (I want to put this "Email" column between the column "member name" and the column "statut").

This page is not a view, it is the page that comes with the module, and which is located at `/group/gid/member` (with `gid` the id of the group). Here is a screenprint of it:

As an alternative (if adding such Email column on that page is too difficult or impossible), I want to create a Views page (to replace the module's member page). This view page should be identical (or as close as possible) to the screenshot above.

Here is a screenprint of the view I created so far:

And here is an export of this view:

```
$view = new view();
$view->name = 'group_membres';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'group_membership';
$view->human_name = 'Membres';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Membres';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['use_more_text'] = 'plus';
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['exposed_form']['options']['submit_button'] = 'Appliquer';
$handler->display->display_options['exposed_form']['options']['reset_button_label'] = 'Réinitialiser';
$handler->display->display_options['exposed_form']['options']['exposed_sorts_label'] = 'Trier par';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'views_bootstrap_table_plugin_style';
/* Relation: Adhésion au groupe : Groupe gid */
$handler->display->display_options['relationships']['group']['id'] = 'group';
$handler->display->display_options['relationships']['group']['table'] = 'group_membership';
$handler->display->display_options['relationships']['group']['field'] = 'group';
/* Relation: Adhésion au groupe : Utilisateur uid */
$handler->display->display_options['relationships']['user']['id'] = 'user';
$handler->display->display_options['relationships']['user']['table'] = 'group_membership';
$handler->display->display_options['relationships']['user']['field'] = 'user';
/* Champ: Groupe : Titre */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'groups';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['relationship'] = 'group';
/* Champ: Utilisateur : Nom */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'user';
$handler->display->display_options['fields']['name']['label'] = 'Nom d\'utilisateur';
/* Champ: Utilisateur : Courriel */
$handler->display->display_options['fields']['mail']['id'] = 'mail';
$handler->display->display_options['fields']['mail']['table'] = 'users';
$handler->display->display_options['fields']['mail']['field'] = 'mail';
$handler->display->display_options['fields']['mail']['relationship'] = 'user';
$handler->display->display_options['fields']['mail']['link_to_user'] = '0';
/* Champ: Adhésion au groupe : Statut de membre */
$handler->display->display_options['fields']['status']['id'] = 'status';
$handler->display->display_options['fields']['status']['table'] = 'group_membership';
$handler->display->display_options['fields']['status']['field'] = 'status';
/* Champ: Adhésion au groupe : Group role */
$handler->display->display_options['fields']['role']['id'] = 'role';
$handler->display->display_options['fields']['role']['table'] = 'group_membership';
$handler->display->display_options['fields']['role']['field'] = 'role';
$handler->display->display_options['fields']['role']['label'] = 'Rôles';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'membres';
$translatables['group_membres'] = array(
  t('Master'),
  t('Membres'),
  t('plus'),
  t('Appliquer'),
  t('Réinitialiser'),
  t('Trier par'),
  t('Asc'),
  t('Desc'),
  t('Groupe'),
  t('Utilisateur'),
  t('Titre'),
  t('Nom d\'utilisateur'),
  t('Courriel'),
  t('Statut de membre'),
  t('Rôles'),
  t('Page'),
);

```

My questions about this view:

* How to add the "Actions" column with links ?
* How to add filters ?

# Answer
> 0 votes
Have a look at this updated version of your view (in Views export format, which you should be to import in your own site):

```
$view = new view();
$view->name = 'group_members';
$view->description = 'List of all members in a specific Group';
$view->tag = 'default';
$view->base_table = 'group_membership';
$view->human_name = 'Group Members';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Membres';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['use_more_text'] = 'plus';
$handler->display->display_options['access']['type'] = 'role';
$handler->display->display_options['access']['role'] = array(
  3 => '3',
);
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['exposed_form']['options']['submit_button'] = 'Appliquer';
$handler->display->display_options['exposed_form']['options']['reset_button_label'] = 'Réinitialiser';
$handler->display->display_options['exposed_form']['options']['exposed_sorts_label'] = 'Trier par';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'table';
/* Relationship: Group membership: Group gid */
$handler->display->display_options['relationships']['group']['id'] = 'group';
$handler->display->display_options['relationships']['group']['table'] = 'group_membership';
$handler->display->display_options['relationships']['group']['field'] = 'group';
/* Relationship: Group membership: User uid */
$handler->display->display_options['relationships']['user']['id'] = 'user';
$handler->display->display_options['relationships']['user']['table'] = 'group_membership';
$handler->display->display_options['relationships']['user']['field'] = 'user';
/* Field: Group: Group ID */
$handler->display->display_options['fields']['gid']['id'] = 'gid';
$handler->display->display_options['fields']['gid']['table'] = 'groups';
$handler->display->display_options['fields']['gid']['field'] = 'gid';
$handler->display->display_options['fields']['gid']['relationship'] = 'group';
$handler->display->display_options['fields']['gid']['exclude'] = TRUE;
/* Field: User: Uid */
$handler->display->display_options['fields']['uid']['id'] = 'uid';
$handler->display->display_options['fields']['uid']['table'] = 'users';
$handler->display->display_options['fields']['uid']['field'] = 'uid';
$handler->display->display_options['fields']['uid']['relationship'] = 'user';
$handler->display->display_options['fields']['uid']['exclude'] = TRUE;
/* Field: Group: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'groups';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['relationship'] = 'group';
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'user';
$handler->display->display_options['fields']['name']['label'] = 'Nom d\'utilisateur';
/* Field: User: E-mail */
$handler->display->display_options['fields']['mail']['id'] = 'mail';
$handler->display->display_options['fields']['mail']['table'] = 'users';
$handler->display->display_options['fields']['mail']['field'] = 'mail';
$handler->display->display_options['fields']['mail']['relationship'] = 'user';
$handler->display->display_options['fields']['mail']['link_to_user'] = '0';
/* Field: Group membership: Membership status */
$handler->display->display_options['fields']['status']['id'] = 'status';
$handler->display->display_options['fields']['status']['table'] = 'group_membership';
$handler->display->display_options['fields']['status']['field'] = 'status';
/* Field: Group membership: Group role */
$handler->display->display_options['fields']['role']['id'] = 'role';
$handler->display->display_options['fields']['role']['table'] = 'group_membership';
$handler->display->display_options['fields']['role']['field'] = 'role';
$handler->display->display_options['fields']['role']['label'] = 'Rôles';
/* Field: Global: Custom text */
$handler->display->display_options['fields']['nothing_3']['id'] = 'nothing_3';
$handler->display->display_options['fields']['nothing_3']['table'] = 'views';
$handler->display->display_options['fields']['nothing_3']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing_3']['label'] = 'View';
$handler->display->display_options['fields']['nothing_3']['alter']['text'] = 'view';
$handler->display->display_options['fields']['nothing_3']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['nothing_3']['alter']['path'] = 'group/[gid]/member/[uid]';
/* Field: Global: Custom text */
$handler->display->display_options['fields']['nothing']['id'] = 'nothing';
$handler->display->display_options['fields']['nothing']['table'] = 'views';
$handler->display->display_options['fields']['nothing']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing']['label'] = 'Modifier';
$handler->display->display_options['fields']['nothing']['alter']['text'] = 'modifier';
$handler->display->display_options['fields']['nothing']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['nothing']['alter']['path'] = 'group/[gid]/member/[uid]/edit?destination=group/[gid]/member';
/* Field: Global: Custom text */
$handler->display->display_options['fields']['nothing_1']['id'] = 'nothing_1';
$handler->display->display_options['fields']['nothing_1']['table'] = 'views';
$handler->display->display_options['fields']['nothing_1']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing_1']['label'] = 'Annuler';
$handler->display->display_options['fields']['nothing_1']['alter']['text'] = 'annuler';
$handler->display->display_options['fields']['nothing_1']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['nothing_1']['alter']['path'] = 'group/[gid]/member/[uid]/cancel?destination=group/[gid]/member';
/* Field: Global: Custom text */
$handler->display->display_options['fields']['nothing_2']['id'] = 'nothing_2';
$handler->display->display_options['fields']['nothing_2']['table'] = 'views';
$handler->display->display_options['fields']['nothing_2']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing_2']['label'] = 'Metadata';
$handler->display->display_options['fields']['nothing_2']['alter']['text'] = 'metadata';
$handler->display->display_options['fields']['nothing_2']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['nothing_2']['alter']['path'] = 'group/[gid]/member/[uid]/metadata';
/* Contextual filter: Group: Group ID */
$handler->display->display_options['arguments']['gid']['id'] = 'gid';
$handler->display->display_options['arguments']['gid']['table'] = 'groups';
$handler->display->display_options['arguments']['gid']['field'] = 'gid';
$handler->display->display_options['arguments']['gid']['relationship'] = 'group';
$handler->display->display_options['arguments']['gid']['title_enable'] = TRUE;
$handler->display->display_options['arguments']['gid']['title'] = 'Members of the group with Group Id = %1';
$handler->display->display_options['arguments']['gid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['gid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['gid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['gid']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['gid']['specify_validation'] = TRUE;
$handler->display->display_options['arguments']['gid']['validate']['type'] = 'numeric';
/* Filter criterion: Group membership: Membership status */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'group_membership';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['exposed'] = TRUE;
$handler->display->display_options['filters']['status']['expose']['operator_id'] = 'status_op';
$handler->display->display_options['filters']['status']['expose']['label'] = 'Membership status';
$handler->display->display_options['filters']['status']['expose']['operator'] = 'status_op';
$handler->display->display_options['filters']['status']['expose']['identifier'] = 'status';
$handler->display->display_options['filters']['status']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
  4 => 0,
  5 => 0,
  6 => 0,
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'group/%/memberlist';

```

Some more details about the changes in this view:

* I changed the machine name of it (to `group_members`), to avoid overwriting a same named view if you try to import this view.
* I changed the "`style_plugin`" to a standard "table" (to not have to depend on that bootstrap-variation, feel free to change that again).
* I added 2 fields that are "excluded from display", ie: the Group id (`gid`) and User id (`uid`). That way I can use their tokens in URLs in other fields I added afterwards.
* I added the fields (with appropriate links) for "Modifier", "Annuler" and "Metadata". For each of those fields I used the "rewrite results" technique.
* Note that I also added a similar "View"-link, since in your original view the links for users point to `user/uid` (which is not what matches with the orginal screenprint you started from ...).
* And I added an (exposed) filter for "Membership status".

Apart from the changes detailed above, I also included these enhancements (which I recommend you to also include):

* Add a **contextual filter** to specify the group ID for which the members should be shown.
* Adapt the **path** of this view to `/group/%/memberlist` (I couldn't use `/group/%/member` because that path is already used by the Group module). The `%` in this path is to be replaced by the group Id you want to show its members for. And if you want to see a list of members for **all** groups together, then just use `/group/all/memberlist`.
* Add a **title** like "Members of the group with Group Id = x" (with x = the selected group id).
* Limit **access** to the results of this view. The view in your question does not have any access restrictions. So I restricted (within "Page settings") the access to something with "Role", and selected as role "Administrator". Without that, even an anonymous user who knows the path to get access to this view can see a list of all group members, including there eMail IDs ... However, as delivered by the Group module, a path like `/group/gid/member` (with `gid` equal to some group id) cannot be accessed by an anonymous user.

With that, I think ... I'm ***done***.

PS (1 more recommendation to further improve it): use the DataTables module to change the table-display to a ***dataTables*** display (try it, you'll love it ... especially if you have a high number of views results).

---
Tags: 7, views, group
---


# Question
Title: Why is my functional test not matching my manual testing?
I have a Drupal 8 module for banning users based on country.

In it, I have the following test.

```
public function setUp() {
  parent::setUp();
  $this->drupalLogin($this->adminSitesUser);
}

public function testCompleteBan() {
  // node/1.
  $this->addBanNode("Read only page");
  // node/2.
  $this->addBanNode("Complete ban page");
  $this->drupalGet(IP_BAN_ADMIN_FORM_PATH);
  $edit = [
    // Set the United States to Read Only
    // 0 = no action / 1 = Read Only / 2 = Complete Ban.
    'ip_ban_US' => 2,
    // Set the test IP address to a known Google US address.
    'ip_ban_test_ip' => '66.249.84.22',
    // Configure the paths for read-only and complete ban.
    'ip_ban_readonly_path' => '/node/1',
    'ip_ban_completeban_path' => '/node/2',
  ];
  $this->drupalPostForm(IP_BAN_ADMIN_FORM_PATH, $edit, t('Save configuration'));
  $this->assertOptionSelected('edit-ip-ban-us', 2, 'Complete ban set correctly in country list table.');
  // Should be redirected to complete ban page after logout.
  $this->drupalGet('user/logout');
  $this->assertUrl('node/2');
}

```

However, I get an error on the last line (`assertURL()`): "Expected 'http://d8.dev/node/2' matches current URL (http://d8.dev/). Value 'http://d8.dev/' is equal to value 'http://d8.dev/node/2'."

It seems as if the page is not redirected on logout the way it is when manually testing with an extremely minimal installation and using the exact same settings (including permissions)/workflow as the tests.

Note all the form-based tests are working as well.

Any idea why this is not working in D8? (It works fine in D7.)

# Answer
The assertion failure looks as though the testing framework isn't following the double redirect (from `/user/logout` to `<front>` and thence to `/node/2`). Maybe explicitly request the front page after logging out?

Ie.

```
$this->drupalGet('user/logout');
$this->drupalGet('<front>');
$this->assertUrl('node/2');

```
> 0 votes

---
Tags: 8, testing
---


# Question
Title: Show either a node or a blocks page at frontpage
At the path "/" - the frontpage of my site, I want to show either

* For anonymous users, the content of a particular node, which is normally available at "/somepath".
* For authenticated users, a series of blocks.

How do I do this?

I think the most elegant answer involves using page manager to take control of the "/" route. With this it is easy to show a series of blocks as one variant, but I don't see how to show a particular node.

I have tried setting the "Default front page" at admin/config/system/site-information to "/somepath". But when I do this my panel page defined in page manager does not show up, either when it targets "/" or "/somepath".

As a fallback, I can probably achieve the same result without page manager at all, by choosing to hide the "content" block on the home page and show only the blocks I want. But I worry this gets messy fast, even using the block visibility groups module to avoid repeating the conditions.

# Answer
I agree, the block layout gets quite messy when you try to do this. Another option would be a separate twig template for the front page.

Create two new regions `frontpage_auth` and `frontpage_anon` and fill them with the blocks you want to show. Don't configure the visibility here. Just place the blocks.

Modify `page.html.twig`, so that `{{ page.content }}` is enclosed in a twig block `maincontent`:

```
{% block maincontent %}
  {{ page.content }}
{% endblock %}

```

Then create a new twig file for the front page

**page--front.html.twig**

```
{% extends "page.html.twig" %}

{% block maincontent %}

  {% if logged_in %}
    {{ page.frontpage_auth }}
  {% else %}
    {{ page.frontpage_anon }}
  {% endif %}

{% endblock %}

```

where you display one of the two regions dependent on the variable `logged_in`.

For the node you can use the *Main page content* block or you can put the node in a view and use this view as a block.
> 1 votes

---
Tags: 8, panels
---


title: How to install Drush 8 on Windows 10?

text:
# Question
Title: How to install Drush 8 on Windows 10?
I am currently running Drush 7 and its working fine for D7.

But I want to run it for D8 site. I have also seen many post where it is mentioned that Drush 7 support D8 but its not true.

So i am trying to install Drush 8.

Try to run below command

```
composer global require drush/drush:8.*

```

Or

```
composer require drush/drush:dev-master

```

./composer.json has been created Loading composer repositories with package information Updating dependencies (including require-dev) Your requirements could not be resolved to an installable set of packages.

> Problem 1 \- Installation request for drush/drush dev-master -\> satisfiable by drush/drush\[dev-master\]. \- drush/drush dev-master requires consolidation/robo dev-master -\> satisfiable by consolidation/robo\[dev-master\] but these conflict with your requirements o r minimum-stability. Installation failed, deleting ./composer.json.

But unable to get success. Any suggestion how achieve this?

# Answer
Finally...

using this command

```
 composer global require drush/drush:8.*

```

But i need to refer few steps before running this command.

```
  composer.json  # Removed the line containing drush like below

```

> {
> "require": {
> ~~"drush/drush": "7.\*"~~
> }
> }

```
composer global update
composer global require drush/drush:8.*

```

source https://github.com/drush-ops/drush/issues/2006
> 3 votes

---
Tags: 8, drush
---


title: What does publishing a node accomplish?

text:
# Question
Title: What does publishing a node accomplish?
This is a general question that I couldn't find a satisfactory answer to. Apart from the obvious, making a node visible on the user side versus keeping it in a 'draft' mode, what does publishing a node accomplish? Especially if the node isn't front-end content.

# Answer
> 2 votes
Node status is baked into the node access system fairly deeply in implementations. What I mean is, it is not directly used by used `hook_node_access()` and `hook_node_grants()`, but implementations of these hooks do. The node access system defines who can see and do what to nodes. So, if you are using nodes outside of page content (eg, using Rabbit Hole w/ Nodequeue), you can still hide your unpublished content from people who don't need to see it.

# Answer
> 1 votes
In the database, the 'node' table has a 'status' column. On 1, the node is published, and on 0 it is unpublished. Basically, publishing an unpublished node is setting this 0 to 1.

---
Tags: nodes
---


# Question
Title: How can I output a Drush report in table format?
I'm getting into my first drush command and coming up with a ton of things I don't understand. Basically, I need to output a list of image files referenced in my content, and the best seemed to be to output it in a table format so that the different bits of information would be easy to see and distinguish from each other.

I started by following the tutorial and did this (in the COMMAND\_drush\_command $items array):

```
    'engines' => array(
        'outputformat' => array(
            'default' => 'table',
            'pipe-format' => 'json',
            // Commands that return deep arrays will usually use
            // machine-ids for the column data.  A 'field-labels'
            // item maps from the machine-id to a human-readable label.
            'field-labels' => array(
                'node' => 'Nid',
                'title' => 'Title',
                'filename' => 'Filename',
                'directory' => 'Directory',
            ),
            // In table format, the 'column-widths' item is consulted
            // to determine the default weights for any named column.
            'column-widths' => array(
                'title' => 20,
            ),
            'require-engine-capability' => array('format-table'),
        ),

```

That worked fine, because I built an array of output line by line and at the end of the command passed it back to drush which duly printed it. The only problem is that there is a LOT of data, so the command gives the appearance of hanging. So I thought I would try to print line by line and did this instead:

```
            $result[0] = array(
                'node' => $nid,
                'title' => $title,
                'filename' => end($file),
                'directory' => $directory,
            //    'orphan' => '?',
            );
            $output = drush_format_table($result,false,array('node'=>5,'title' => 20,'filename'=>30,'directory'=>25));
            drush_print($output);

```

The problem is, that the output is all over the shop, rather than being lined up nicely as it should be.

Where am I going wrong?

# Answer
> 2 votes
You are better off sticking with your initial implementation; if you use Drush output formatters, then the end-user will be able to convert your data to csv or yaml or other formats as needed. If it takes a long time to collect your data, then use `drush_log` or perhaps a progress bar to let the user know something is going on.

---
Tags: drush
---


# Question
Title: Front-end page to add content for a specific content type
I am new to Drupal and I am working on a page created by the Views module and I am displaying my content as a grid.

As I already know it is possible to add content to my specific content type from the admin panel, I would like to have a front page which has the same functionality.

Is there anything which helps me achieve this?

# Answer
You can simply go to achieve Using the **'Admin Menu': Configuration \> Site Information**.

Under the Front Page section, change FRONT PAGE to content add information.

I think you should look into

Form Block module.

> Enables the presentation of user registration, site wide contact, or node creation forms in blocks. This is particularly useful for including forms on panels.

Advanced Form Block module.

> Create any number of blocks with a particular node edit form.
>
> Create any number of blocks with a particular node add form of a content type.
>
> Create as many blocks as you like of each kind.
> 3 votes

# Answer
Another approach is to display a special (informational) message on your specific page where you want to have this functionality (= "*add content to my specific content type*") available. And eventually only show such message to users with a specific role (eg an administrator).

To do so, all you'd need is to enable the Rules module, and create an extremely basic custom rule which looks like so (in Rules export format):

```
{ "rules_show_a_message_on_a_specific_path" : {
    "LABEL" : "Show a message on a specific path",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      },
      { "data_is" : {
          "data" : [ "site:current-page:path" ],
          "value" : "path\/to\/my\/page"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Click \u003Ca href=\u0022[site:url]\/node\/add\/article\u0022\u003Ethis link\u003C\/a\u003E to add some content of type Article ..." } }
    ]
  }
}

```

If you have the Rules UI enabled, you can simply import the above rule in your own site (and enable the rule afterwards, which is disabled as shown above).

Here is what the above rule actually does:

* Check if the currently logged in user has access to role "administrator" (which corresponds to role id = "`3`").
* Check if the current path is `path/to/my/page`.
* If both checks (= Rules Conditions) are satisfied, then the Rules Action will be performed, which is to display a message like "*Click **this link** to add some content of type Article ...*", whereas ***this link*** is actually an hyperlink to `/node/add/article`.

If needed, just adapt the values for the role id, the current path, and the actual message (including the URL in it and or the used content type) to fit your own needs.
> 0 votes

---
Tags: 7, views, forms
---


title: Get current language in a template file

text:
# Question
Title: Get current language in a template file
I tried to get the current language in the menu.html.twig template file.

The current language is not available in this template and a preprocess function is not existing for this template as far as I could see. So I did not manage to get the current language by using template\_preprocess function as it is described here.

I tried a few things but ended up creating my own Twig function that delivers `\Drupal::languageManager()->getCurrentLanguage()->getId()` in this (and any other) template.

I could think of declaring a global variable maybe in `template_preprocess()`, but I believe this is not a good option if I only want it in one special template.

So my question is: Is it a proper way for this to go via own TWIG function or is there another more easier way of doing this?

For reference I used code like this:

```
class MyLanguageCheckerExtension extends \Twig_Extension {

  public function getName()
  {
      return 'lang_check';
  }

  public function currentLang() {

    return \Drupal::languageManager()->getCurrentLanguage()->getId();
  }

  public function getFunctions() {
    return array (
      new \Twig_SimpleFunction('languagecheck', array($this, 'currentLang')),
    );
  }
}

```

# Answer
The proper way is in a preprocess function and this does exist for the menu template. The reason is caching. In the preprocess function you can check if the caching metadata is in synch with the additional information you add to the twig.

In case of the language, you might get this working in a Twig function, because many templates are already cache dependent on the language, but not with other information like (for example) information from the current user.

This is an example for the menu preprocess function from the Bartik theme.

```
/**
 * Implements hook_preprocess_HOOK() for menu.html.twig.
 */
function bartik_preprocess_menu(&$variables) {
  $variables['attributes']['class'][] = 'clearfix';
}

```
> 1 votes

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


title: Content missing

text:
# Question
Title: Content missing
I inherited this production 6.36 website (20 or so multisite) that is heavily customized. Lately, it has begun to show weird behavior - like some js not working for non-admin users. One issue that is particularly worrying is losing pages. We have lost a page here and there over the last few months, but just this last week it has lost some 20 odd pages (as a band-aid we have been rebuilding those pages with the waybackmachine version of them).

I'm looking through the logs, but I am not sure what exactly to look for (I see http errors of page-not-found, but not much beyond that). We are on a LAMP stack, with PostgreSQL instead of mysql.

Anyone have any thoughts on what might be causing this kind of behavior?

# Answer
> 1 votes
If you're pulling information back from the Wayback Machine and you're losing data it sounds like step one is to make sure you have functional database backups. *Do that before you do anything else.*

Drupal 6.36 has known security problems, in the past we've seen cases where attackers found ways to use attacks more broadly than initially documented. It's possible that's your problem.

That said, my experience is that the most common sources of missing content on Drupal 6 were either user error (deleting things they shouldn't), database corruption (less likely on Postgres than D6's default setup), or custom modules causing problems.

Since you say the site is heavily customized it is possible that you have custom code that attempts to alter pages under some condition and causes problems. Check your web server error logs to see if something is appearing there.

> **Note:** Drupal 6 is no longer supported by the community and Drupal 6 does not run well (at all?) on currently supported versions of PHP. *You should plan to update to Drupal 7 or Drupal 8 as soon as possible.*

---
Tags: 6
---


# Question
Title: Make support ticket subscriptions visible by default
I have a Drupal 7 site using the Support Ticketing System module. When viewing a ticket, the client would like the Subscribed fieldset (id="edit-subscribed") visible by default. Currently it is collapsed, and you have to click on it to expand the field.

This problem is similar to a previous post, where hook\_form\_BASE\_FORM\_ID\_alter() allowed me to expand the Subscribed field by default when the ticket was being edited.

But when viewing the ticket, the form in question is the comment-form, and I can't find the right array to target the edit-subscribed fieldset, if in fact the hook\_form\_alter is the right way to do this.

# Answer
> 1 votes
It proved far easier to just add a line of JQuery to the page. `jQuery('#edit-subscribed').removeClass('collapsed');` added to the footer took care of it.

---
Tags: forms
---


# Question
Title: Mutlti level filter with search api and facet in commerce kickstart
I'm using commerce kickstart, I want to use the built-in filter blocks (facet & search-api).
I have multi-level categories (taxonomy), but filters just display parents categories.
For example I have as categories:

> computers
> -laptops
> -desktops
> -notebook
> Networking
> -routers
> -modems

Filters just display computers and networking

# Answer
It sounds like you need to enable the "Expand Heierarcy" option under Facet Display settings (for the search index you are working with).
> 1 votes

---
Tags: commerce, search
---


title: View field nesting

text:
# Question
Title: View field nesting
I need some help. I have view with two fields

* Featured image
* 2.Logo

normally Drupal renders is as separate divs what i want is to nest the 2nd div to the 1st div

**Normal Drupal render**

```
<div class= "views-name-featured-image"> Featured Image </div>
<div class= "views-name-logo"> Featured Image </div>

```

**what I want is**

```
<div class= views-name-featured-image>

   Featured Image goes here

      <div class= views-name-logo>

         Logo goes here

   </div>
</div>

```

Views field-set is not available for Drupal 8

How can I achieve this... rewriting the result is not working too.

# Answer
> -1 votes
Resolve by rewriting results on view... thanks anyways

---
Tags: views, 8
---


# Question
Title: Which user related token(s) can be used to create a Rule for setting up a message type?
I have created few activity logs using the Message module. All works ok, but when I try to create a message type for example **"username started following you on github"**. When setting up the rules for this message type, I am not able to understand how to achieve this.

**What should happen?**

Message must be logged for the **"User who ‘Is flagged’"** user and at the same time the username token must be replaced by the **"User who ‘Flagged it’"** user. The problem is that this is not happening.

**What is happening?**

When the message is logged for **"User who is flagged"**, the username is also replaced by **"User who is flagged"** user and vice versa. Obviously this is not what is required.

**Export of "User Following" message type**

```
{
  "name" : "user_following",
  "description" : "User following",
  "argument_keys" : [],
  "argument" : [],
  "category" : "message_type",
  "data" : {
    "token options" : { "clear" : 0 },
    "purge" : { "override" : 0, "enabled" : 0, "quota" : "", "days" : "" }
  },
  "language" : "",
  "arguments" : null,
  "message_text" : { "und" : [
      {
        "value" : "[message:user:name] started following you on [site:name]",
        "format" : "plain_text",
        "safe_value" : "[message:user:name] started following you on [site:name]"
      }
    ]
  },
  "rdf_mapping" : []
}

```

**Rules for above message**

```
{ "rules_started_following" : {
    "LABEL" : "Started_following",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "user" ],
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_follow" : [] },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "message",
            "param_type" : "user_following",
            "param_user" : [ "flagged-user" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      }
    ]
  }
}

```

**Note:** It is about rules setup for message type when you select data-selectors in rules setup.

Another example is for **"xyz mentioned you on github"**. Same problem goes here. Here username replaced by xyz and it was logged for xyz as well. It should not happen.

If abc user was mentioned by the xyz user, then the above message or notification must be received by the abc user and not the xyz user. Like normally you receive a notification on other websites when someone follows you or mentions you.

**Export of "Mentions" message type**

```
{
  "name" : "log_mentions",
  "description" : "Log mentions",
  "argument_keys" : [],
  "argument" : [],
  "category" : "message_type",
  "data" : {
    "token options" : { "clear" : 0 },
    "purge" : { "override" : 0, "enabled" : 0, "quota" : "", "days" : "" }
  },
  "language" : "",
  "arguments" : null,
  "message_text" : { "und" : [
      {
        "value" : "[message:user:name] mentioned you",
        "format" : "plain_text",
        "safe_value" : "[message:user:name] mentioned you"
      },
      {
        "value" : "\u003Cp\u003E[message:user:name]\u003C\/p\u003E\r\n",
        "format" : "full_html",
        "safe_value" : "\u003Cp\u003E[message:user:name]\u003C\/p\u003E\n"
      }
    ]
  },
  "rdf_mapping" : []
}

```

**Export of Rules for above message**

```
{ "rules_test_rule" : {
    "LABEL" : "test rule",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "statuses_tags" ],
    "ON" : { "statuses_tags_user_was_tagged" : [] },
    "IF" : [
      { "statuses_tags_has_specific_tag_condition" : { "status" : [ "status" ], "type" : "user", "tag" : "[account:name]" } }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "message",
            "param_type" : "log_mentions",
            "param_user" : [ "account" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:field-message-mentioning:name" ],
          "value" : "[status:sender]"
        }
      }
    ]
  }
}

```

**Problem:** When using it, if I mentioned Pierre in a post, the output is, **"Pierre mentioned you"** and the message is also logged for Pierre.

**Statuses Sub-Modules:** I am using all sub-module except following:

Statuses Domain Access, Statuses Mollom, Statuses Notifications and Statuses Userpoints. It is important to tell here that Flag 3 does not work with statuses module, Flag 2 does. Good thing is you do not want flag module to workout this problem. I am using flag 2 as I want the "like" button and follow functionality for status updates.

Note: I created the field of **machine name** "field\_message\_mentioning" **Label:** "mentioning" **Type:** "Entity Reference (User)" **Widget:** "Autocomplete". I have tried lot of things and spent hours, but I do not know what I am doing. I just read online and try to apply.

Hope you understood. Please read the whole explanation in the context of rules setup for message type. If there is any confusion, please ask me before answering.

# Answer
# Part 1: Rules tokens

Here is a sample of a rule (in Rules export format), for a flag which is used to flag an entity of type "user":

```
{ "rules_set_the_ever_flagged_with_flagx_flag" : {
    "LABEL" : "Set the ever flagged with FlagX flag",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "flag" ],
    "ON" : { "flag_flagged_flagx" : [] },
    "DO" : [
      { "flag_flaguser" : {
          "flag" : "ever_flagged_with_flagx ",
          "user" : [ "flagged-user" ],
          "flagging_user" : [ "flagging-user" ],
          "permission_check" : "1"
        }
      }
    ]
  }
}

```

The Rules Action of it, uses these 2 tokens:

* `flagged-user`, which you should use for ***User who ‘Is flagged’***.
* `flagging-user`, which you should use for ***User who ‘Flagged it’***.

Those 2 tokens should also be available for you to select in your custom rule.

You may also want to look at my answer to "Flag Module: "Never Flagged" Status", which provides more details about my example rule here.

However, the above technique is not going to work in your case, because your question has to do with tokens that you need to be available at the level of the Message module. And that is a completely different story ... Read on for more details on that (and a working solution) ...

# Part 2: Message tokens

Your question is about messages created via Rules, but for 2 variations of message types:

* Messages triggered by the Flag module (after a user got flagged).
* Messages triggered by the Statuses (Social Microblog) module (and it's Tag related submodule).

But in both case (types of messages), you want to create a message that requires some token that is not provided by the Message module. And even though it seems that `status:recipient` token might be a possible fit, it is actually NOT what you're looking for (that token is about who the message is to be delivered **to**, not about **who** triggered that message to be delivered).

However, since you are using Rules to create your messages to be delivered, you can make the missing tokens available by using the ***Replacement patterns*** for each message type. Refer to the answer to What's the purpose of "Replacement tokens" of a Message type? for way more details on that (these Replacement tokens are really a hidden gem about how Rules integrates with Message!).

# Part 3: Solution for "User following"

### Step 1 - Define replacement tokens

Define a replacement token for this message type that is like so: `@following_user` (adapt to whatever fits, if you also adapt it in the steps below).

### Step 2 - Custom message using these replacement tokens

Within the Message text, use something like so (note the tokens I'm using):

> @following\_user started following \[message:user:name\]

### Step 3 - Custom rule

Here is how your adapted rule should look like (I mostly just added that extra Rules Action):

```
{ "rules_somebody_started_following_you" : {
    "LABEL" : "Somebody started following you",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "user" ],
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_follow" : [] },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "message",
            "param_type" : "user_following",
            "param_user" : [ "flagged-user" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:arguments:following-user" ],
          "value" : "[site:current-user]"
        }
      }
    ]
  }
}

```

# Part 4: Solution for "Log mentions"

### Step 1 - Define replacement tokens

Define 2 replacement tokens for this message type that is like so: `@mentioning_user, %mentioning_statuses_text` (adapt to whatever fits, if you also adapt it in the steps below).

Note the 2 (instead of just 1) tokens I used here, just to also show how to do that ...

### Step 2 - Custom message using these replacement tokens

Within the Message text, use something like so (note the tokens I'm using):

> @mentioning\_user mentioned \[message:user:name\] in the statuses message "%mentioning\_statuses\_text" ...

Note the `@` versus `%` I used in this message text, doesn't matter which one you use, just to show the difference ...

### Step 3 - Custom rule

Here is how your adapted rule should look like (I mostly just added those 2 extra Rules Action, 1 for each replacement token):

```
{ "rules_somebody_mentioned_you" : {
    "LABEL" : "Somebody mentioned you",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "statuses_tags" ],
    "ON" : { "statuses_tags_user_was_tagged" : [] },
    "IF" : [
      { "statuses_tags_has_specific_tag_condition" : { "status" : [ "status" ], "type" : "user", "tag" : "[account:name]" } }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "message",
            "param_type" : "log_mentions",
            "param_user" : [ "account" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:arguments:mentioning-user" ],
          "value" : "[site:current-user]"
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:arguments:mentioning-statuses-text" ],
          "value" : "[status:message-formatted]"
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:field-message-mentioning:name" ],
          "value" : "[status:sender]"
        }
      }
    ]
  }
}

```

Note that I did not change anything to the (now) last Rules Action, though IMO you could savely remove that Rules Action (it's not needed to make it work, but maybe you need it for something else). Similarly: I'm not sure what the purpose of that extra "field" is for your message type (possibly obsolete now?).

# Part 5: Fruit of your labor

If you make it this far, and implement the above rules and message types in your own site, you should be able to get results similar to my setup ...

### Demo of "User following"

* Scenario:

`Hillary.Trump` flags `Donald.Clinton`
* Result:

Message delivered to `Donald.Clinton`:

> 11/09/2016 - 12:05 Hillary.Trump started following Donald.Clinton

### Demo of "Log mention"

* Scenario:

`drupal.admin` posts a statuses-msg like "Just saw the answer from \[@Pierre.Vriens\], and it works like a charm!!!"
* Result:

Message delivered to `Pierre.Vriens`:

> 11/09/2016 - 12:22 `drupal.admin` mentioned `Pierre.Vriens` in the statuses message "Just saw the answer from \[@Pierre.Vriens\], and it works like a charm!!!" ...
> 1 votes

---
Tags: 7, users, rules, flags, message-subscribe
---


# Question
Title: Import orders from xls/csv to drupal commerce
I am trying to import orders from xls file to drupal commerce store.Is there any existing module for this, I found commerce\_migrate and commerce\_feeds module I am not sure if they can be helpful here could not find if any of the two module provides this functionality as not mentioned on project page.

# Answer
> 2 votes
I wrote a script to import orders. Here is the workflow I followed

1. imported all users using user\_import module, the orders belongs to.
2. Created a custom database tables with columns needed to make an order.
3. Imported the excel/csv file to custom table after formating data.
4. Created a script to import orders and create customer profile linked to a order

Here is the script

```
/*
 * Helper function to facilate order import functinality.
 */

function mymodule_name_order_import_($email, $product_sku, $order_created_date, $quantity, $status, $billing_fields, $payment_method) {

  // Get product id.
  $product = commerce_product_load_by_sku($product_sku);
  $product_id = $product->product_id;

  $user = user_load_by_mail($email);
  $uid = $user->uid;

  if (!empty($uid)) {

    // Set order status.
    if ($status == "Pending") {
      $status = "pending";
    }if ($status == "Completed") {
      $status = "completed";
    }

    // Keeping order status to pending. -- Need to Change as per order. --
    $order = commerce_order_new($uid, $status);

// Save the order so its ID is assigned.
    commerce_order_save($order);

// Order created date in time stamp.
    $date = DateTime::createFromFormat('m/d/Y', $order_created_date);
    $order->created = $date->getTimestamp();

    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);

//add products to order by ids array
    $product = commerce_product_load($product_id);

// Create a line item with quantity 1 and this product.
    $line_item = commerce_product_line_item_new($product, $quantity, $order->order_id);

// Save the line item to get its ID.
    commerce_line_item_save($line_item);

// Add the line item to the order using the wrapper.
    $order_wrapper->commerce_line_items[] = $line_item;

// Get Billing Profile.
    $profile_billing = mymodule_name_order_import_map_billing_fields($uid, $billing_fields);

// Map billing address to order.
    $order->commerce_customer_billing[LANGUAGE_NONE][0]['profile_id'] = $profile_billing->profile_id;

// Get Shipping Profile.
    $profile_shipping = mymodule_name_order_import_map_shipping_fields($uid, $billing_fields);

// Map billing address to order.
    $order->commerce_customer_shipping[LANGUAGE_NONE][0]['profile_id'] = $profile_shipping->profile_id;

// Payment Method
    if ($product_sku == "25PDVDP") {
      $order->data['payment_method'] = "payment_commerce_2|commerce_payment_payment_commerce_2";
    }
    elseif ($product_sku != "25PDVDP") {
      if ($payment_method == "Credit Card") {
        $order->data['payment_method'] = "credit_cart|custom_import";
      }
      if ($payment_method == "PayPal") {
        $order->data['payment_method'] = "paypal|custom_import";
      }
      else {
        $order->data['payment_method'] = "na|custom_import";
      }
    }

// Save the order.
    commerce_order_save($order);
  }
  else {
    print "This user doesn't exists : " . $email;
  }
}

/**
 * Helper function to map billing fields.
 * @param $uid user id of user to make billing profile for.
 */
function mymodule_name_order_import_map_billing_fields($uid, $billing_fields) {
  $profile_billing = commerce_customer_profile_new('billing', $uid);
  $profile_billing->commerce_customer_address = array(
    LANGUAGE_NONE => array(
      0 => addressfield_default_values()
    )
  );

// Full Name(Required)
  $profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['name_line'] = $billing_fields['name_line'];

// Country(Required)
  $profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['country'] = $billing_fields['country'];

// Address 1(Required)
  $profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['thoroughfare'] = $billing_fields['thoroughfare'];

// Address 2
  $profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['premise'] = $billing_fields['premise'];

// City(Required)
  $profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['locality'] = $billing_fields['locality'];

// State(Required)
  $profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['administrative_area'] = $billing_fields['administrative_area'];

// Postal Code(Required)
  $profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['postal_code'] = $billing_fields['postal_code'];

//Business name(Required)
  $profile_billing->field_business_name[LANGUAGE_NONE][0]['value'] = $billing_fields['field_business_name'];

// Who runs your front desk?(Required)
  $profile_billing->field_who_runs_your_front_desk_[LANGUAGE_NONE][0]['value'] = $billing_fields['field_who_runs_your_front_desk_'];

// Email address for the front desk person(Required)
  $profile_billing->field_email_address_front_desk[LANGUAGE_NONE][0]['value'] = $billing_fields['field_email_address_front_desk'];

// Phone(Required)
  $profile_billing->field_phone[LANGUAGE_NONE][0]['value'] = $billing_fields['field_phone'];

// Save billing profile.
  commerce_customer_profile_save($profile_billing);

  return $profile_billing;
}

/**
 * Helper function to map billing fields.
 * @param $uid user id of user to make shipping profile for.
 */
function mymodule_name_order_import_map_shipping_fields($uid, $billing_fields) {
  $profile_shipping = commerce_customer_profile_new('shipping', $uid);
  $profile_shipping->commerce_customer_address = array(
    LANGUAGE_NONE => array(
      0 => addressfield_default_values()
    )
  );

// Full Name(Required)
  $profile_shipping->commerce_customer_address[LANGUAGE_NONE][0]['name_line'] = $billing_fields['name_line'];

// Country(Required)
  $profile_shipping->commerce_customer_address[LANGUAGE_NONE][0]['country'] = $billing_fields['country'];

// Address 1(Required)
  $profile_shipping->commerce_customer_address[LANGUAGE_NONE][0]['thoroughfare'] = $billing_fields['thoroughfare'];

// Address 2
  $profile_shipping->commerce_customer_address[LANGUAGE_NONE][0]['premise'] = $billing_fields['premise'];

// City(Required)
  $profile_shipping->commerce_customer_address[LANGUAGE_NONE][0]['locality'] = $billing_fields['locality'];

// State(Required)
  $profile_shipping->commerce_customer_address[LANGUAGE_NONE][0]['administrative_area'] = $billing_fields['administrative_area'];

// Postal Code(Required)
  $profile_shipping->commerce_customer_address[LANGUAGE_NONE][0]['postal_code'] = $billing_fields['postal_code'];

// You sould pass the entire $profile object as parameter.
  commerce_customer_profile_save($profile_shipping);

  return $profile_shipping;
}

function jh_order_import_run($jh_product_sku = '') {

  //$jh_product_sku = '25PDVDP';
  $result = db_select('jh_order_import', 'joi')->fields('joi')->condition('product_sku', $jh_product_sku, '=')->execute()->fetchAll();

  foreach ($result as $key => $value) {
    echo "<pre>";
    print_r($value);
    $country = array('United States' => 'US', 'Canada' => 'CA',
      'Australia' => 'AU', 'United Kingdom' => 'GB', 'South Africa' => 'ZA');
    $jh_bill = array('name_line' => $value->full_name, 'country' => $country[$value->country],
      'thoroughfare' => $value->billing_address_1,
      'premise' => $value->billing_address_2,
      'locality' => $value->billing_city,
      'administrative_area' => $value->billing_state,
      'postal_code' => $value->billing_postal_code,
      'field_business_name' => $value->billing_bussiness_name,
      'field_who_runs_your_front_desk_' => $value->billing_front_desk_name,
      'field_email_address_front_desk' => $value->billing_front_desk_email,
      'field_phone' => $value->billing_phone,
    );
    $payment_method = $value->payment_methods;
    mymodule_name_order_import_($value->email, $value->product_sku, $value->order_date, $value->quantity, $value->status, $jh_bill, $payment_method);
    print "imported " . $key;
  }
}

```

**NOTE: the above script is use case specific, so it will need modifications per need, but might be helpful to start with. I am using drupal commerce API's to import orders, customer profiles that's all.**

# Answer
> 2 votes
You can use latest feeds module (currently 7.x-2.x-dev from 2014-Dec-10) which contains EXPERIMENTAL importers to import **entities**!

Luckily, ***Orders are entities***. The steps you need for this (using feeds of course) are:

1. Import `drupal users` (if they do not exist and they are needed)
2. Import `commerce products` (if they do not exist)
3. (Optional) Import `product displays (nodes)` for the commerce products.
4. Import `commerce orders` (you need at least the owner uid)
5. Import `commerce line items of your type` for each order (eg commerce products, commerce profiles, commerce shipping etc). Notice that the match here is with the order\_id.

So you may need at least 1 importer for the Orders and 1 additional importer for each line item type (products, shipping, payments, customer profiles etc).

# Answer
> 0 votes
You can use the Feed Importer module with no bother. Just convert your XLS file to a CSV file. https://www.drupal.org/project/feed\_import

---
Tags: commerce
---


title: image_image plugin does not exist

text:
# Question
Title: image_image plugin does not exist
Trying to build a content module (= a module that adds a content type) for drupal 8 but I get the following error on install, the error isnt very informative and Im stuck. The module has a image upload field, and I assume its whats throwing the error but the code for it is copied out of drupals export

> Drupal\Component\Plugin\Exception\PluginNotFoundException: The "image\_image" plugin does not exist. in Drupal\Core\Plugin\DefaultPluginManager-\>doGetDefinition() (line 52 of core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php).

Code is at the following https://github.com/ShadyRabbit/drupalIssue

Update: I found the answer myself: ***`entity_view_display` was the same as `entity_form_display` resulting in the error of the content type***

# Answer
> 1 votes
Somewhere you specified image\_image, a widget, formatter or field type. There is no such thing, find it and correct it.

You get better help if you share your code.

---
Tags: 8, media
---


# Question
Title: I am using https://github.com/drupal-composer/drupal-project . How to add more scripts after "create-project"?
I want to use https://github.com/drupal-composer/drupal-project to generate several customized projects.

If I want a contrib module to be available for all instances, what is the best way to get them when running "composer create-project"?

I thought to add this logic (to add contrib modules by default) in scripts/composer/ScriptHandler.php but this file doesn't seem to be suitable for customizations.

Is there an easy way to add other scripts to run on project creation? Or which other way should I chose?

# Answer
when you use `create-project` you're creating a new composer project with a **composer.json** based on the package type.

The **composer.json** file is highly customizable. You can set install paths for specific modules/libraries and/or set a list of default modules to install when the project is created. You can also apply patches and run post-install scripts if nessecary. Plenty more options as well. I suggest jumping into the composer docs.

to add a module to **composer.json** run:

```
composer require drupal/module_name 8.1.*@dev

```

Once you have a composer.json the way you like, you can take that composer.json file, place in a different empty project directory and you can simply run `composer-install` and it will install the drupal project, all the modules in the appropriate directories specified inside the **composer.json** file, post install commands ect, it will also write a **composer.lock** file if one doesn't exist. No need to create a brand new project everytime, just manage custom **composer.json** files thats the beautfy of composer.

https://www.lullabot.com/articles/goodbye-drush-make-hello-composer

https://getcomposer.org/doc/01-basic-usage.md

https://getcomposer.org/doc/
> 0 votes

# Answer
There are various ways to do this.

drupal-project is a composer project like any other. Create your own repository, e.g. by forking on github. Then add all your standard modules there and use your own repository with create-project.

You can also create a repository with a composer.json that contains nothing but dependencies. https://github.com/webflo/drupal-core-strict is something like that, except that it enforces specific versions of core dependencies. Simply add the modules you want to use there, then add that with composer require on a new project and it will merge it together and download all those projects.
> 0 votes

---
Tags: 8, composer
---


title: How to get a remote server posted JSON?

text:
# Question
Title: How to get a remote server posted JSON?
A remote server will redirect with posting a JSON string back to a URL in my Drupal site defined by hook\_menu. But I don't know either care the URL of the remote server. How can I get the JSON data in my hook\_menu? I use these codes:

```
      $received = file_get_contents("drupal://input"); // Use inputstream module.
      $received = json_decode($received, TRUE);
      dpm($received);

```

When the redirection happened, the hook\_menu page shows nothing. When I thereafter access the frontpage of my Drupal site, it shows as below:

Warning: file\_get\_contents(): Unable to find the wrapper "drupal" - did you forget to enable it when you configured PHP? in shisuepay\_postback() (line 130 of /.../sites/all/modules/custom/shisuepay/shisuepay.module).

Warning: file\_get\_contents(drupal://input): failed to open stream: No such file or directory in shisuepay\_postback() (line 130 of /.../sites/all/modules/custom/shisuepay/shisuepay.module).

# Answer
It turned out that the postback data is not the format of JSON. So I just use $\_POST variable to get the data. Thank you all the same.
> 0 votes

---
Tags: 7
---


title: How to Display Empty Fields in views

text:
# Question
Title: How to Display Empty Fields in views
How do I Display empty fields in Views? Empty\_Fields module does not work for me as there needs to be a custom text for it to display.

I want to display all labels even if the fields are empty. How do i achieve this?

Thanks

# Answer
In Views field settings add ` ` to `No results behavior`. Your View will then display a space and a field label if the field is empty.

---

If you're using Unformatted list format for your View block, then in `Format -> Fields -> Settings` make sure that `Hide empty fields` checkbox is unchecked. See screenshots below.
> 0 votes

---
Tags: views
---


# Question
Title: How can I tell if a node has more than one parent taxonomy term assigned to it
I have a situation where the colour scheme of a node depends upon which taxonomy terms have been assigned to it.

However, if a node has more than 1 parent taxonomy term assigned to it, this is a certain colour scheme of itself. I'm not sure of the technical name but by parent taxonomy term I mean the top level taxonomy term, as there will only ever be 2 levels deep, so I call this parent taxononomy term.

So I need a certain html class to be created for these special nodes who have more than one taxonomy term assigned to them.

I was thinking even to use a hidden field and to write a module which checks how many parent taxonomy terms have been assigned before creating or saving this content type in question, and then simply adds a value to this hidden field, I could then use this field to add a class to my content in views.

Am I allowed to ask for suggestions here for this, I am sorry if this is against rules

# Answer
There's no need to store this information when it can be calculated on the fly.

The taxonomy module contains a function called `taxonomy_get_parents()` that can retrieve the parents for a given term. Using this, you can iterate over the node field values to look for any root ("parent") level terms (i.e. they have no parent) and count the number of terms accordingly.

```
// Given a node object & taxonomy field machine name, return count of root terms
function mymodule_node_root_term_count($node, $field_name) {
  $count = 0;

  // $node->{$field_name}[LANGUAGE_NONE] will vary with multi-lingual enviroment
  foreach($node->{$field_name}[LANGUAGE_NONE] as $term) {
    $parents = taxonomy_get_parents($term['tid']);
    // A root term will return an empty array.
    $count += empty($parents) ? 1 : 0;
  }

  return $count;
}

```

Once you've built your logic for determining the type of node, you can utilize it in a theme preprocess function to add CSS classes accordingly.
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: How do I append a view to the node body in custom module?
In Drupal 7, we could do the following within a hook\_node\_view:

```
$node->content['nodehierarchy_children'] = array(
  '#theme' => 'nodehierarchy_children_embed',
  '#nodehierarchy_view' => $node->nh_children_view,
  '#nodehierarchy_view_display' => @$node->nh_children_view_display,
  '#nodehierarchy_view_args' => $arguments,
);

```

Then in the hook\_theme:

```
function nodehierarchy_views_theme() {
  return array(
    'nodehierarchy_children_embed' => array(
      'render element' => 'element',
    ),
  );
}

```

Finally we have the theme function:

```
function theme_nodehierarchy_children_embed($variables) {
  $element = $variables['element'];
  $display = $element['#nodehierarchy_view_display'];
  $arguments = $element['#nodehierarchy_view_args'];
  return $view->execute_display($display, $arguments);
}

```

How do I accomplish the above in Drupal 8? I'd like the implementation to be Drupal 9 compatible, so ideally I don't want to use depreciated functions etc.

I mean should I attempt to somehow override node.html.twig and provide it with a render array using something similar to:

```
$view = views::getView($node->nh_children_view)
$build['nodehierarchy_children_embed'] = $view->buildRenderable($display,$arguments);

```

I think if someone could provide the functions and general methodology, I could fill in the coding portion.

# Answer
For later versions of Drupal 8, the above no longer worked, so I had to change it to the following:

```
/**
 * Implements hook_ENTITY_TYPE_view().
 */
function mymodule_node_view(array &$build, EntityInterface $node, EntityViewDisplayInterface $display, $view_mode){
  // Get the arguments to send to the view.
  $arguments = ...;
  if ($view = Views::getView('my_view')) {
    $view->setDisplay($display);
    $view->setArguments($arguments);
    $build['some_random_name'] = $view->render();
    // Set the weight high to append the view to the end of the body or omit it otherwise.
    $build['some_random_name']['#weight'] = 1001;
  }
}

```
> 0 votes

# Answer
So it turns out that the hook\_node\_view was all that was needed, but I don't know why it didn't work the first time:

```
/**
 * Implements hook_ENTITY_TYPE_view().
 */
function mymodule_node_view(array &$build, EntityInterface $node, EntityViewDisplayInterface $display, $view_mode){
  // Get the arguments to send to the view.
  $arguments = ...;
  if ($view = Views::getView('my_view')) {
    $display = ...
    $build['some_name'] = $view->buildRenderable($display,$arguments);
    $body = $node->get('body')->value;
    $node->set('body')->value = $body.render($build['some_name']);
  }
}

```
> 2 votes

---
Tags: nodes, 8
---


# Question
Title: Using base_url() in image paths without using PHP?
So normally I can do `<img src="<?php base_url(); ?>/default/files/image.png" />` and that works just fine if I enable the php filter.

The trouble is that enabling the php filter disables all shortcodes. My drupal site is not installed in the root of the domain so `<img src="/default/files" />` will not work.

Is it possible to have a relative path (this site will be moving once I'm finished) but have drupal know it's relative to the base url without using php? Maybe a setting?

# Answer
in your `.htaccess` file, you could try something like:

```
RewriteEngine on

```

(in case it is not already turned on)

```
RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
RewriteRule ^$ subfolder [L]

```

(where in this case 'subfolder' represents the address of the installation)

This should create a system based, base url, rather than a php based url - so relative paths should work.
> 1 votes

# Answer
You can use the pathologic module. One of its uses cases is related to subfolders:

*The address of your site has changed. Perhaps you moved to a shiny new domain name, or perhaps you moved the Drupal installation from one subdirectory to another. Now all the images and internal links in your content don’t work. Using Pathologic is an alternative to going through all of the site’s content and correcting the paths manually.*

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

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

You can configure it in:

```
/admin/config/content/pathologic

```

As an example if your website is on /staging/ (dev.example.org domain)

You should include `http://dev.example.org/staging/`
> 0 votes

---
Tags: uri
---


title: Admin toolbar unstyled list

text:
# Question
Title: Admin toolbar unstyled list
I successfully migrated a Drupal site I'd been working on to my local machine. The site itself and its content are all fine, but when I login as administrator, the admin toolbar is an unstyled list, as seen here.

I seem to have the same problem as described in this other thread; however, I have tried the solution suggested with no success.

All the permissions are correct, either 755 (folders) 644(files), and I did a recursive chown on the entire directory. I flushed the caches before I migrated the site and then again when I got it live locally. I am using the admin toolbar module, so I tried uninstalling, no change, and reinstalling, no change.

If I observer the console output from web browser, when I log in as admin, I get the following:

> The stylesheet http://localhost/drupal/?og6o9k was not loaded because its MIME type, “text/html”, is not “text/css”.
>
> SyntaxError: expected expression, got '\<'

I don't know if these are related, but they are the only noticeable difference when I log in as admin, so I'm acting as if they are related.

# Answer
> 0 votes
Have you tried turning off CSS aggregation and seeing what happens?

The fact that it's trying to load a stylesheet at "http://localhost/drupal/?og6o9k" makes me think it's an issue with how your public file system is setup. Like it tried to create a CSS file but failed. I would check which folder it's set to and make sure the permissions are correct.

It could also be an issue with the theme. Trying switching to another theme temporarily and see if that fixes things.

Lastly, you can try uninstalling and reinstalling a fresh version of Admin Menu.

---
Tags: 8, migrations
---


# Question
Title: How do I embed a node information/content into another node?
I have two content types. One is author (fields are author name, designation, bio, image etc) and another one is article. In article content type, I have created an entity reference field "Author Info" where target bundle is author. While I am creating article, I get author list in Author Info field and I can select an author from the list.

When visiting the article page I only see the Author name/title under Author Info field. But I want to display there all author fields information.

I did some search to find out a way but no luck so far.

How I can do that?

Do you have any hint about that or what to search for?

# Answer
> 1 votes
Depending on your layout and other details there are a few ways to handle the display of the content from your related entity.

The most basic (and therefore limited) way is to go to Manage Display first on your article content type and adjust the settings for the format. It is likely already "rendered entity" (if not set that) and then click the gear to the right and set the view mode to be Default or Teaser. Once that's set, switch to manage the display of your authors and make sure the fields you want to display on your article pages are enabled.

The draw back to this approach is that it can have side effects unless you create extra view modes and are careful about when those modes are displayed. For example, if you change the teaser settings any place the author teasers appear will change to match. If you install Display Suite you will have additional options to control the layout of both content types within the Manage Display form.

A common approach is to use views. With Views you can create a block that displays the author information, and then you can carefully place that block where ever you need. There is a reasonably good tutorial on Drupal.org for how to set something like this up in a general case.

If you'd like to do more research on options I suggest searching for things like "drupal views entity reference" or "drupal ds entity reference".

---
Tags: 7, theming, nodes
---


# Question
Title: How to make question answer content type with answer as a separate node?
I want to create a "question" content type, but is it possible to make the answer a separate node?

Because I want to use Views with user relationships module to show answers to friends or followers.

# Answer
If you don't want to reinvent the wheel, you should have a look at the Answers module. Here are some details about it (from its project page):

> Answers enables the implementation of a Question & Answer system in a Drupal site. Users can post questions and other users can answer them.

Head over to its project page for more details.

At its core, this module exists of 2 typical content types:

* Question.
* Answers.

The "Best Answer" submodule can be used so that the question author can "accept" one of the answers as the best one. And you could make the Rules module to either trigger all sorts of subsequent things to happen "when an answer gets marked as best answer", or to add all sorts of validations when posting an answer (or question).

The Answers module comes with integrations with other modules such as the Rules module and the Userpoints module and supports voting.

# Demo

Have a look at the (new) demo site of the Answers module. This link shows various menu options within the block with title ***Answers Menu***, i.e.:

* **Questions** (= a view):
    + **All**: of all existing questions (= default tab).
    + **Answered**: all questions which have a "best" (= accepted) answer (= sub-tab).
    + **Unanswered**: all questions which do not yet have a "best" (= accepted) answer (= sub-tab).
* **Answers** (= a view): lists all existing answers for any of the existing questions and which does not (yet) have any submenu options (implemented as tabs).
* **Rankings** (= a view): contains a list of users with their actual ranking (= reputation points implemented via user points), and with each user a link to either the questions or answers from that user.
* **Ask Question**: to post a new question (the equivalent of `node/add/question`), which is only shown for authenticated users though.

Disclosure: I'm a (co-)maintainer of this module.
> 0 votes

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


# Question
Title: How do I find out the machine name of a view in hook_preprocess_views_view_field?
In Drupal 8, I am trying to use `hook_preprocess_views_view_fields` to process certain fields of certain views. I know how to test for the field name via `$variables['field']->field`, but I can't find any similar way to test for the view's machine name. Is there a similar way to do it for the view?

# Answer
The view itself is in the `$variables` array for all of the views hooks.

```
/** @var \Drupal\views\ViewExecutable $view */
$view = $variables['view'];
$view->id();

```

should give you what you are looking for.
> 5 votes

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


# Question
Title: How to display body content in custom text?
How to display body content in this line?

I had tried "content\_body" and "field\_body" but doesn't work.

The script below is inserted in "Configure field: Global: Custom text"

```
<li class="one-third column info_item"><a href="[path]" title="[title]" class="pic_info_link_type4">
    <div class="pic_info type4">
        <div class="pic_holder">
            <div class="plus_overlay"></div>
            <div class="plus_overlay_icon"></div>
            [field_image]
            <div class="img_overlay_icon"><span class="portfolio_icon [field_portfolio_format]"></span></div>
        </div>
        <div class="info_overlay">
            <div class="info_overlay_padding">
                <div class="info_desc"><span class="portfolio_icon [field_portfolio_format]"></span>
                    <h3>[title]</h3>
                    <p>[field_categories]</p>
                    <p>[content_body]</p>
                </div>
            </div>
        </div>
    </div>
</a></li>

```

# Answer
Under the custom text box, if you click on "Replacement Patterns" it will show you all the patterns you can use.

Should be `[body]`

Also, make sure all the other fields are arranged above the `Global: Custom text` or else the pattern will not work.
> 1 votes

---
Tags: views
---


# Question
Title: What is this operator:content value mean?
What is this operator:content mean?

1) Under Content:Title

2) Click on Content:Title, under Configure filter criterion: Content: Title, there is a operator:content. What does value mean?

# Answer
The operator shown in the screenshot is *Contains*. Since that is a filter for *Content: title*, it will show nodes whose titles contain the string you put in the *Value* field.

To make a summary, that view will show nodes, where:

* The node is published
* The content type is *Webform*
* The node title contains *style 2*
> 4 votes

# Answer
For the most part, you can think of `Content` as being "node". So the title of the node.

Since you have `Content Type (=webform)` as a filter, then `Content: Title` would be the Title of your web form.

Where this could change, is if you add a relationship, EX: Terms of the node, and then select a relationship for your title field. Then it would be the title of a taxonomy term, or some other thing/entity. Depends on the relationship you add.
> 2 votes

---
Tags: views
---


# Question
Title: How do I translate the Book module tree navigation?
We only have English and Spanish translations on our website. I can easily translate each book page, but there doesn't seem to be a way to translate the book tree navigation. Is there a way to translate the book tree navigation so the links will display translated text and link to the translated pages?

# Answer
> 0 votes
I found this that outlines the path to doing this with menus in general: https://www.drupal.org/node/2182497

After testing it appears that this does NOT work with the Book module menus. All configuration options I have tried thus far have not been successful and I'm guessing the only options left are probably a custom code alter of the book\_navigation or a custom book menu all together.

Those steps would included either using the book\_navigation preprocess hook: function template\_preprocess\_book\_navigation https://api.drupal.org/api/drupal/core%21modules%21book%21book.module/function/template\_preprocess\_book\_navigation/8.2.x

and/or the twig template that renders the menu: book-navigation.html.twig https://api.drupal.org/api/drupal/core%21modules%21book%21templates%21book-navigation.html.twig/8.2.x

Hopefully those are a good start.

---
Tags: 8, i18n-l10n
---


# Question
Title: Move a site hosted on IIS/MS SQL Server across to LAMP stack
I have a Drupal 7 site which is currently hosted in a Windows servers environment (e.g. IIS and MS SQL Server). The site needs to be moved over to Platform.sh, which is using the LAMP stack.

I am wondering if there are likely to be any issues with doing this? For example, is it possible to simply export the existing database from MS SQL Server and then import it into MySQL on the new site using drush?

# Answer
There shouldn't be any issues as such if you properly follow the steps of Migrating a Drupal Site. You can find detailed steps on How to Migrate a Site.

This documentation provides a detailed documentation on Backing up and migrating a site.

Regarding taking a database backup of Site, you can checkout Backup and Migrate Module for quick and easy database backup of site. Here's how you can quickly setup Backup and Migrate module and backup your site databse.
> 0 votes

---
Tags: 7, database, drush
---


title: Sanitizing Query Results Data

text:
# Question
Title: Sanitizing Query Results Data
In my customized module, I have queried a database value, *Jocelyn D. Napiñas*. It contains *ñ* that causes my code to break. Is there any way I can display it? I tried the following code.

```
$data;  //Contains `Jocelyn D. Napiñas`

drupal_convert_to_utf8($data, 'us_ascii'); //Returns false

check_plain($data); //Returns ''

```

How will I display it as *Jocelyn D. Napiñas*?

# Answer
> 3 votes
According to drupal\_convert\_to\_utf8 it required **Requires the iconv, GNU recode or mbstring PHP extension** to work, make sure **mbstring Php extension** installed(Go to `/admin/reports/status` and take a look at your unicode library) if not installed install it and try again

```
 drupal_convert_to_utf8($data , 'us-ascii');

```

if not worked according to mb convert encoding you can let Php detect encdoing with *AUTO*, so use

```
drupal_convert_to_utf8($data, 'auto');

```

Also I can suggest another solution for you

```
iconv(mb_detect_encoding($data, mb_detect_order(), true), "UTF-8", $data);

```

# Answer
> 1 votes
Try `us-ascii` instead of `us_ascii`. That's how it's written in unicode.inc

---
Tags: 7
---


# Question
Title: How to change rendering of div order in a field?
It appears that the module label help is not compatible with Date fields. It allows you to enter text, but it does not display.

I found out that in the div with class description should be above div id edit-field-geboortedatum-und-0-value instead of below

How to achieve this? Should I change a weight key in something?

# Answer
> 1 votes
You can use $form\['#after\_build'\] to modify a form. Put below element at the end of your hook\_form function.

```
$form['#after_build'][] = 'FORM_NAME_after_build'; //Calls function

```

After build function to change the position of DIV

```
function FORM_NAME_after_build($form, $form_state) {
  drupal_add_js('jQuery(document).ready(function ($) {
    $("#edit-field-geboortedatum-und-0-value").insertAfter($(".description"));
  });', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));

  return $form;
}

```

---
Tags: entities
---


# Question
Title: Is there any easy way to set the default author for a node being edited to the current author if it is currently anonymous?
The site I am working on has a lot of Anonymous nodes because it is a migration from a system that didn't have a proper user system. Users can claim their articles by going in and editing the node and changing the system author, but I'd like that to happen by default whenever someone (preferably someone who is not the administrator) edits a node that has the anonymous author. I'm sure it must be imminently doable through some form alter or form preprocess hook, but I don't quite get the drupal form system yet. Solutions and pointers to good sources of information both welcome.

**UPDATE** I refined this question here: How can I set a default node owner for anonymous nodes on the node edit form?

# Answer
> 2 votes
You can use hook\_form\_alter() function like:

```
/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  // If edit page is node
  if (isset($form['#node_edit_form'])) {
    $form['actions']['submit']['#submit'][] = 'mymodule_node_edit_submit';
  }
}

/**
 * Implements submit function for node edit.
 */
function mymodule_node_edit_submit($form, &$form_state) {
   // Get node id
   $nid = $form_state['values']['nid'];
   // Get current user
   $current_uid = $form_state['values']['uid'];
   // Load node if owner is anonymous
   if($current_uid == 0){
     // Get logged in user id to append uid as owner to node.
     global $user;
     $node = node_load($nid);
     // Set owner id as logged in user
     $node->uid = $user->uid;
     // Save node
     node_save($node);
    }
}

```

# Answer
> 3 votes
### Option 1 - Adapt node author after editing it

If you have the Rules module enabled, you can simply use a rule that looks like so:

```
{ "rules_change_anonymous_user_to_current_user" : {
    "LABEL" : "Change anonymous user to current user",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_update" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "node-unchanged:author:uid" ], "value" : "0" } },
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2" } }
        }
      },
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "node:author" ], "value" : [ "site:current-user" ] } },
      { "drupal_message" : {
          "message" : "Be aware: this was a node with an anonymous author. Since you just edited it, you are now considered as the author of it.",
          "type" : "warning"
        }
      }
    ]
  }
}

```

After you enable the Rules UI, you should be able to import this rule in your own site.

Just in case it's not clear what this rule does:

* Rules Event: after updating existing content.
* Rules Conditions:
    + Author of node being edited has `uid=0`.
    + User editing the node is logged in.
    + User editing the node does NOT have role "administrator".
* Rules Actions:
    + Set node author to current user.
    + Display a (warning) message like "*Be aware: this was a node with an anonymous author. Since you just edited it, you are now considered as the author of it.*".

***Done!*** ... with Option 1.

### Option 2 - Adapt node author after flagging it (instead of editing it)

As per your requirement like "*...whenever someone (preferably someone who is not the administrator) edits a node that has the anonymous author ...*") the previous option has a disadvantage I think: the node has to be edited. But what if the node content is actually fine, and does not need any edits at all? Therefor I'd recommend a possible alternative, which you either use together with the previous option, or as a replacement of it. Read on for more details ...

You could also use the Flag module to create a (non-global) flag that are allowed to be used by authenticated users. Let's say you define a flag labeled like "**`I am the author`**", with machine name "`i_am_the_author`". With such flag in place, you can use a variation of the rule from Option 1, which looks like so:

```
{ "rules_change_anonymous_user_to_flagging_user" : {
    "LABEL" : "Change anonymous user to flagging user",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_i_am_the_author" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "flagged-node:author:uid" ], "value" : "0" } },
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2" } }
        }
      },
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "flagged-node:author" ], "value" : [ "site:current-user" ] } },
      { "drupal_message" : {
          "message" : "Be aware: this was a node with an anonymous author. Since you just flagged it, you are now considered as the author of it.",
          "type" : "warning"
        }
      }
    ]
  }
}

```

After you enable the Rules UI, you should be able to import this rule in your own site.

Just in case it's not clear what this rule does:

* Rules Event: after a node has been flagged, under "I am the author".
* Rules Conditions:
    + Author of node being flagged has `uid=0`.
    + User flagging the node is logged in.
    + User flagging the node does NOT have role "administrator".
* Rules Actions:
    + Set node author to current user.
    + Display a (warning) message like "*Be aware: this was a node with an anonymous author. Since you just flagged it, you are now considered as the author of it.*".

***Done!*** ... with Option 2.

### Option 3 - Heading for the golden cradle

If you'd implement Option 2 (using the "I am the author" flag), you could even replace the rule from Option 1 by a variation of it, which is that you simply disallowed edit attempts of nodes that (still) have an anonymous user. Here is a summary of how such rule could look like:

* Rules Event : Drupal is initializing.
* Rules Condition: Current path is like `/node/nid/edit` (using a regular expression).
* Rules actions:
    + Perform a redirect (to any path that fits, eg some help page to explain the reason for the direct).
    + Set a Drupal message to indicate that edits are only allowed by a user who flagged the node first by ... you guessed it ... the "**`I am the author`**" flag.

***Voilà!***

### Option 4 - Resolving node author disputes

No matter which solution (option) you'd use, there is always a chance that multiple users might claim to be the node author.

To also take that scenario into consideration, you could create a variation of the rule from Option 2. Some details about such rule:

* Replace 1st Rules Condition by "node author of flagged node is NOT `uid=0`.
* Replace both Rules Actions with sending an eMail to (eg) the site administrator, to indicate that some type of conflict about a node author came up (and adapt the message being shown accordingly).

***Game over!?!?***

# Answer
> 1 votes
You can use hook\_node\_update

```
/**
 * Implements hook_node_update().
 */
function hook_node_update($node) {
   global $user;

     //administrator role id
     $admin_rid = 3;

     //To check if user is not admin
     if (!array_key_exists( $admin_rid , $user->roles)) {
         $node->uid = $user->uid;
         node_save($node);
     }
}

```

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


# Question
Title: How to programmatically create an exposed filter?
Is there a way to create programmatically exposed filters in Drupal 7?

I searched a lot but I found only topics related remove or alter exposed filters already available in a view.

By instance my view doesn't provide any exposed filter. I must create it through the code in my module. I have a view but I can't change it via Views administration interface. I must achieve the result by implementing hook\_views\_pre\_view() and add\_item().

Unfortunately add\_item is not very well documented or, at least, not the part concerning the $options array structure.

Given 'field\_status' a "select list" with 3 items defined in the field configuration, and the following piece of code:

```
 function hook_views_pre_view(&$view, &$display_id, &$args) {
   $field = field_info_field('field_status');
   if (!empty($field)) {
    $filter = array(
     'identifier' => 'field_status',
     'exposed' => TRUE,
     'is_grouped' => FALSE,
     'table' => 'field_data_field_status',
     'type' => 'list_text',
     'expose' => array(
       'operator_id' => 'field_status_value',
       'label' => 'Status',
     )
   );
   $view->add_item($view->current_display, 'filter', 'field_data_field_status', 'field_status_value', $filter);
   $view->display_handler->set_option('css_class', 'view-status');
}

```

what should be the structure of the array $options (in my case $filter)?

As a result of this I can see the submit button 'Apply' and the label "Status" in an empty widget 'div'.

Here is the code edited following suggestions in comments:

```
function my_module_views_default_views_alter(&$views) {
  if (array_key_exists('my_view_name', $views)) {

    $options = array (
      0 => 'Blocked',
      1 => 'Active',
    );

    $display = $views['my_view_name']->display['my_view_page'];

    $display->display_options['filters']['field_status']['id'] = 'field_status';
    $display->display_options['filters']['field_status']['table'] = 'field_data_field_status';
    $display->display_options['filters']['field_status']['field'] = 'field_status';
    $display->display_options['filters']['field_status']['exposed'] = TRUE;
    $display->display_options['filters']['field_status']['expose']['operator_id'] = 'field_status_value';
    $display->display_options['filters']['field_status']['expose']['label'] = 'Status';
    $display->display_options['filters']['field_status']['expose']['operator'] = 'field_status_value';
    $display->display_options['filters']['field_status']['expose']['identifier'] = 'field_status';
    $display->display_options['filters']['field_status']['value'] = $options;

    $views['my_view_name']->display['my_view_page'] = $display;
  }
}

```

--- ALTERNATIVE SOLUTION ---

Since this problem seems to be hard to fix (@ least for my specific case) I have used a workaround to achieve the goal. The solution consists basically on a Views Block Clone with Exposed Filters which overrides the Views Block (without exposed filters) according to specific cases (Is User LoggedIn, Content Type, Contextual Filters ecc..).

# Answer
Can you please try with hook\_views\_default\_views\_alter function. This function should be defined in MODULE\_NAME/views/MODULE\_NAME.views.inc file. And don't forget to include this file on .info file as `files[] = views/MODULE_NAME.views.inc.`

```
 function MODULE_NAME_views_default_views_alter(&$views) {
        if (array_key_exists('MY_VIEW_NAME', $views)) {
          $options = array(
          0 => 'Blocked',
          1 => 'Active',
          );
          $display = $views['MY_VIEW_NAME']->display['MY_VIEW_PAGE'];
          $display->display_options['filters']['field_status']['id'] = 'field_status';
          $display->display_options['filters']['field_status']['table'] = 'field_data_field_status';
          $display->display_options['filters']['field_status']['field'] = 'field_status';
          $display->display_options['filters']['field_status']['value'] = $options;
          $display->display_options['filters']['field_status']['exposed'] = TRUE;
          $display->display_options['filters']['field_status']['expose']['operator_id'] = 'field_status_value';
          $display->display_options['filters']['field_status']['expose']['label'] = 'Status';
          $display->display_options['filters']['field_status']['expose']['operator'] = 'field_status_value';
          $display->display_options['filters']['field_status']['expose']['identifier'] = 'field_status';
          $views['MY_VIEW_NAME']->display['MY_VIEW_PAGE'] = $display;
          }
    }

```
> 3 votes

---
Tags: 7, views
---


# Question
Title: How can I refer to a table to make a level system?
I'm working on a RPG website. Users are awarded userpoints (named XP for the need of the "game") depending on their actions.

I want to make a level system based on these userpoints. I already made a table using Drupal Data, which stores values for each level (level number, minimum XP, maximum XP, and some ratios to apply when a user is earning points).

My question is : How can I refer to this table to check a user level (and all the values attached) depending on the user's amount of XP?

I tried with Rules, but no success.

# Answer
Give it some thought to replace that table you made with:

1. a new content type (eg called "XP") and
2. with custom fields as in your question, such as:

* level number.
    * minimum XP.
    * maximum XP.
    * some ratios.

That way you could create 1 node for each row in your table, with field values matching the values in those table rows. If appropriate, use the Feeds module to automatically create 1 node for each row in your table.

After you'd have created such nodes, you could use them in combination with the modules you're already using / considering, such as User Points and Rules.

To implement that "*level system*" (as in your question), you can probably use the Goals module (disclosure: I'm the maintainer of it). If you're not familar with this module, have a look at "How to implement gamification in a Drupal site and award incentives?".

Bonus tip: since you're thinking of using User Points and Rules already, you may also want to look at the answer to "How to access current amount of earned userpoints in a Rules Condition?" (pretty sure you'll need something like that also).

PS: All this only requires site builder skills (no need for any custom coding).
> 1 votes

---
Tags: rules, userpoints
---


title: Printing Administrative title to page

text:
# Question
Title: Printing Administrative title to page
Is there a function I can use or object I have access to in page.tpl.php in order to get the Administrative title of the current page or it's machine name?

# Answer
The page title in Drupal doesn't have a machine name. If you want to add one, you can use Safeword module. How to do that: after installing the module, add a new field to that content type where you want to add the machine name; select field type as "Machine name from node title" and widget as "Machine name". After doing this, save the content type and you'll have the machine name for node title.
> 0 votes

---
Tags: 7, theming
---