# Question
Title: How to get order information on the checkout complete page?
How do you get the order information such as user's name, address, e-mail and products he ordered, on the checkout complete page on Drupal Commerce for Drupal 7?

# Answer
I've managed to complete this task. First, you must get the order id from session or database using query. Second, you must create an $order object like this

```
$order = commerce_order_load($orderId);

```

Define a new order sdtClass

```
$myOrder = new stdClass();

```

Wrap the order

```
$orderWrapper = entity_metadata_wrapper('commerce_order', $order);

```

And then you can get various order info like this:

```
// Get order number
$orderNumber = $order->order_number;

// Get user's e-mail address and encode properly encode it
$orderMail = drupal_json_encode($user->mail);

// Prepare an array to store products
$orderPurchasedItems = array();
// Create a foreach to loop through all the products and get the products info
foreach ($items as $item) {
    // Checks if the value is equal to product
    if ($item->type->value() === 'product') {
        // Get the unit price value per product
        $commerceUnitPrice = $item->commerce_unit_price->value();
        $entity = $item->value();
        if ($entity) {
            $orderPurchasedItems[] = array(
                "id" => $entity->nid,
                "quantity" => $item->quantity->value(),
                "price" => commerce_currency_format(
                    $commerceUnitPrice['amount'],
                    $commerceUnitPrice['currency_code']
                ), // this will result in $10
            );
            // Store all the ordered products in a new variable so we can use it later
            $myOrderProducts = $orderPurchasedItems;
        }
    }
}

```
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: How do you clear menu caches programmatically?
I am developing a custom module. In this module, I want to delete menu caches programmatically. For this, I have used

```
\Drupal::cache('menu')->invalidateAll(); // for clearing the menu cache
\Drupal::service('plugin.manager.menu.link')->rebuild(); // rebuild the menu

```

But somehow, menu cache seems not being cleared and still the old menu is being displayed. How can I force Drupal to have my updated menu being displayed?

# Answer
Menu's are displayed via blocks. You will probably have to clear the block render cache as well.

```
\Drupal::cache('block')->invalidateAll();

```
> 6 votes

---
Tags: 8, caching, navigation
---


title: Statistics on drupal projects

text:
# Question
Title: Statistics on drupal projects
I am trying to contribute Drupal modules and placed my first project on drupal.org.

Is it possible to see if a proprietary project on drupal.org has been downloaded and how many times?

# Answer
Have a look at the "Usage statistics" page of any module on drupal.org, which includes all sorts o relevant information.

As an example, checkout the Rules module, for which you can find those statistics at https://www.drupal.org/project/usage/rules . Apart from a nice chart, it also gives you the statistics by Drupal Release (D6, D7, D8), and this for each Drupal Release for which the module does have some release. If you scroll to the bottom of those statistics, you even get more details (for the last 5 weeks) of every (minor) release of the module.

Attention: don't confuse "using a module" with "number of dowloads of a module"! E.g, for the Rules module, there are currently **296,819** sites reporting that they are using this module, while there have been **2,642,716 downloads** so far. Open question: does that mean that only (about) 10% of sites for which this module was downloaded actually still use this module? Answer: I don't think so ...

PS: Replace "rules" in the above URL by any other module's name to find similar statistics.
> 3 votes

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


# Question
Title: Stop overriding for the development snapshot module
I have a development snapshot for a module (*ABC-8.x-1.x-dev*). I added 4 Patches. Now the developer does commit updates to the module.

By running `composer update`, I will loose all my patches.

When I remove the module name from composer.json, the module gets deleted. I have read that I should remove the composer.json file within the module.

Is there some kind of sub-version that defines the commit or so, for example `"drupal/abc": "~1.0-dev-FD1512"` or `"drupal/abc": "~1.0-dev-221"`?

# Answer
Instead of trying to tie yourself to a specific commit, you might consider using composer patches instead:

```
{
  ...
  "require": {
    "cweagans/composer-patches": "^1.0",
    "drupal/abc": "~1.0-dev"
  },
  "extra": {
    "patches": {
      "drupal/abc": {
        "Fix for foo": "https://url/to/foo-patch",
        "Fix for bar": "https://url/to/bar-patch"
      }
    }
  }
  ...
}

```

Patches will be applied on install/update of the relevant packages.
> 3 votes

---
Tags: composer
---


title: creating filter by fields

text:
# Question
Title: creating filter by fields
I'm having a content type publications and researchers associated with these publications. I want to create a filter by the name of the researchers. I created a relationship in the view, and I created a contextual filter, but it's not working. Right, now the filter is not showed in the view. If I create a sort criteria based on the researcher it's not working.

# Answer
I create a entity relationship between in both content types, by creating a content type reference. Then, in the view I created a relationship the user. I created a contextual filter in the view using the user name.
> 0 votes

---
Tags: views
---


# Question
Title: Passing important data to batch operation
I can't seem to pass any info to the 'finished' function of this batch operation. Everything works in terms of data getting saved correctly but I get the following error message due to the 'finished' function looking for things that don't exist.

> Notice: Undefined index: created in my\_csv\_import\_finished() (line 280 of /var/www/html/mysite.com/sites/all/modules/custom/my\_csv/my\_csv.module).
>
> Notice: Undefined index: updated in my\_csv\_import\_finished() (line 281 of /var/www/html/mysite.com/sites/all/modules/custom/my\_csv/my\_csv.module).

And that's because there is no $success, $results, or $operations being passed to my\_csv\_import\_finished

The $context variable is indeed being passed to the $operations function but from what I can tell, there is nothing there that would give me access to any sort of 'created' and/or 'updated' key of this $contexts array. What am I doing wrong?

```
function my_csv_import_form_submit($form, $form_state) {
  // Check to make sure that the file was uploaded to the server properly
  $uri = db_query("SELECT uri FROM {file_managed} WHERE fid =:fid", array(
                   ':fid' => $form_state['input']['import']['fid'],
                  ))->fetchField();
 if(!empty($uri)) {
   if(file_exists(drupal_realpath($uri))) {
     // Open the csv
     $handle = fopen(drupal_realpath($uri), "r");
     $fp = file($uri);
     $total_rows = count($fp);

     // this is somewhat of a hack to skip the first line (headers)
     fgetcsv($handle, 0, ',', '"');

     while (($data = fgetcsv($handle, 0, ',', '"')) !== FALSE) {
     $operations[] = array('my_csv_import_batch_processing', array($data),
    );
  }

    $batch = array(
      'title' => t('Importing CSV...'),
      'operations' => $operations, array($data),
      'finished' => 'my_csv_import_finished',
      'error_message' => t('The installation has encountered an error.'),
      'progress_message' => t('Processed @current of @total rows.'),
    );
    batch_set($batch);

    fclose($handle);
  }
 }

function my_csv_import_batch_processing($data, &$context) {
  watchdog('$context', print_r($context,TRUE));

  .....
}

```

What am I supposed to use here?

$context looks like this:

```
[0] => Array (
            [sandbox] => Array (
                )
            [results] => Array (
                )
            [finished] => 1
            [message] => ''
        )

```

If I've indeed successfully updated a node, where is this info? And how do I get/find it?

Is it something to do with the structure of what's being passed to the operations function?

# Answer
> 0 votes
Soon after posting this I figured out that one can simply pass things into the $context\['results'\] array like so:

```
$context['results'][].

```

---
Tags: batch-operations
---


title: The email address is already taken

text:
# Question
Title: The email address is already taken
I'm trying to edit a user, but I keep getting the following error:

> The email address \[their email\] is already taken.

I'm not editing their email. In fact, I could open the edit page, just hit *Save* without changing anything, and I would still get the error.

Why am I getting this error message?

# Answer
It appears that email is already in the database on another row. This can have many causes; importing users twice, creating accounts in a custom module without proper checking if the email address is available, etc.

If you do not use the account edit forms, but modify users programmatically, it can appear that the same email is added to the database twice (the form validation does not run in those cases). Then later when you try to edit one such user, it cannot save because that account should not have existed in the first place. This measure is there so users cannot sign up with the same email twice, but since the user creation and edit form are in fact the same form (and as such have the same validation), it can happen during the save of a user as well.

Double check that you have no modules that can create accounts from email addresses (eg. Drupal commerce) and check your database `users` table to identify the duplicate account.
> 3 votes

# Answer
I got this same error because an external integration was creating user accounts with duplicate email addresses. The solution for me was to use drush to add the role:

```
drush urol "role" --name=username

```
> 0 votes

---
Tags: 8
---


# Question
Title: Configure web.config to redirect non-www requests to www for multi-site Drupal 7 Install
I have a multi-site Drupal 7 install running on Azure that I would like to force all non-www traffic to the www address for all sites.

I have tried a number of examples from around the web but none of them seem to work.

Here is my current implementation, which looks like it should work, but does nothing.

```
<rule name="Redirect to www">
  <match url=".*" />
  <conditions logicalGrouping="MatchAny">
    <add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" negate="true" />
  </conditions>
  <action type="Redirect" url="http://www.{HTTP_HOST}/{R:0}" redirectType="Permanent"/>
</rule>

```

To clarify, yes, the above rule is nested inside `<configuration> <system.webServer> <rewrite>`

I've read about doing the redirect in settings.php but that seems kludgy to me and I'd rather do it right.

Any help would be greatly appreciated.

# Answer
> 0 votes
Some subtle differences between this and the rule above, but this officially works for my multi-site Drupal install on Azure IIS.

```
<rule name="WWW Rewrite" enabled="true">
          <match url="(.*)" />
            <conditions>
                <add input="{HTTP_HOST}" negate="true" pattern="^www\.(.*)$" />
            </conditions>
            <action type="Redirect" url="http://www.{HTTP_HOST}/{R:0}" appendQueryString="true" redirectType="Permanent" />
</rule>

```

---
Tags: redirection, multi-sites, .htaccess
---


# Question
Title: How to create a custom payment page attached to a user account's form
I am on Drupal 7 and I am building an ads website in which people can buy credits via their account form. **I am not using Commerce or Ubercart** for very complex reasons that would be a bit long to explain.

So lets move forward.

Users will use the credit that they buy to make payable actions on their content, **such as making a content sticky**.

**1. What I already did :**

Now a user who is connected to his account can select the **number of credits** to add to his **balance**. And the balance will be added that amount of credits.

And all the payable action on the ads decrease the balance of the concerned user.

So to say that the system works fine.

**2. What I need to do now :**

I set up field to let the user choose the type of payment his wants : **PayPal** or **Credit Card**.

* How can I create a payment page without programming ?
* How can I make people really see a payment page ?
* How can I make that payment page appear before the users saves the account forms ?

These are the things that I really need to know.

**Anybody know how to ?**

# Answer
> 1 votes
I think that this site will tell you what to do:

Setting up payment methods

You shall download one of the modules to get a list of services.

# Answer
> 1 votes
First of all I advice you the two modules its very helpful and I used the before to achieve similar scenario as you asked.

1- commerce node checkout:

allow you to charge users to create nodes. It is possible to have multiple different product offerings for each node type, so the user can pick the product they want to purchase when creating the node. An example use-case would be a classifieds site that charges people to post listings

2- commerce account balance:

enables a -per user- account balance to which you can deposit money and which you can use for purchasing things on your website.

You could use any payment method like paypal to charge balance.

I think both two modules will do most of the job for you, if you don't need to use **commerce** which is required by the two modules try to patch them and customize or even get the main ideas and build your own solution.

**Edit:** payment forms may help if none of the above fits your needs.

---
Tags: 7, payment-gateways
---


# Question
Title: Setting data values in a paragraphs field with multiple values via rules?
Over the last few days I've been investigating and experimenting on how to use rules to alter fields within a paragraphs bundle on a node. The paragraph field on the node allows for multiple values(to a maximum of 6). In the paragraph bundle there is a radio button field where users select a "type" which then triggers the visibility of a corresponding field. The 'Conditional Fields' module has an option to 'reset to default value' when a dependency is not triggered, but this fails to work for me(needs a patch I believe). In place of that I am using rules to clean the form on submit. This worked perfectly with normal node fields, however it's not so simple when the fields I need to clean are inside a paragraph entity and there are multiple instances of the entity within the field.

In my experimentation I was able to reset the **first** and *only* the first paragraph bundle isntance with a data selector that looks like this:

node:field-paragraphs-categories:0:field-select-service

The problem here(*I think*) is that I'm selecting only the first 'row' in the paragraphs field thanks to the :0: in the data selector? I'm only guessing at the meaning of that number, the labeling of data selectors is cryptic to me.

Without that 0 or any of the other numbers(ex: 1,2,3) shown in the data selector options I can't even access the appropriate field I want to alter.

Screenshot of available data selectors

I figured that the right direction is to loop through the paragraphs field and select each 'row' individually and then, through the current list item of the loop, select the appropriate field to alter it that way but so far have been completely unsuccessful.

I believe I need a component(of type rule) and a standard rule to do this, right?

### The rule:

**Condition =** Entity has field - Parameter: Entity: \[node\], Field: field\_paragraphs\_categories

**Loop =** node:field-paragraphs-categories & add component as an action

**Action =** Fetch entity by id - current-paragraph:item-id

### The component(type rule):

**Condition =** Data comparison - current-paragraph:item-id(from loop):field-service-type

**Action =** Set a data value - current-paragraph:item-id(from loop):field-select-service

I can't seem to simply pass the id of the current item of the loop to the data comparison or action in the component so i can drill down to the fields it contains. This is where I'm getting stumped. Perhaps my entire method is wrong though, I don't know.

The closest instruction I've been able to find is in this thread https://www.drupal.org/node/1699712 @ #9 but, while similar, offers no insight into the parts I'm having difficulty with.

The short version of this support request is:

**How do I loop through a paragraphs field with multiple values, set a data comparison condition on 'service-type', and then set a data value for 'select-service' if the condition evaluates to true.**

**CLARIFICATION:**

In trying to add any data comparisons or actions such as "set a data value" I am unable to find a way to iterate over each row and then alter a field in that row like so:

First iteration = node:field-paragraphs-categories:0:field-select-service -\> set value

Second iteration = node:field-paragraphs-categories:1:field-select-service -\> set value

Third iteration = node:field-paragraphs-categories:2:field-select-service -\> set value

fourth iteration = node:field-paragraphs-categories:3:field-select-service -\> set value

And so on.

As far as I understand right now, without automatically looping through that index number I cannot set data values for fields inside "paragraphs-categories" unless I manually make a rule(or action within a rule) for each possible index number(0,1,2,3,4,5,etc).

***Final Findings***

After some further testing it appears that the issue is that paragraphs does not make the current list item fields available for manipulation within the loop(you can, however, access them for creating messages and maybe other actions). The **field collection module** *DOES* expose field collection fields in a rules loop and the refinements outlined by Pierre.Vriens work perfectly with that module instead.

# Answer
Your question requires addressing multiple Rules issues, as further detailed below ...

### 1. You may not need a Rules Component

It seems you're familiar enough with using "Loops" in Rules, so that part is fine. But what you not seem to be aware of, is that you could use the Conditional Rules module to verify your condition like:

> **Condition** = Data comparison - current-paragraph:item-id(from loop):field-service-type

By using this extra module, you don't need the additional Rules Component, and you have access to everything you need in the (single) rule itself.

### 2. Passing data to/from your Rules Component

However, using a Rules Component should be a valid alternative also. If that's what you prefer, then I suggest these refinements to your rule (and Rules Component):

* Make sure to use 2 variables in your Rules Component (using "Parameter", not "Provided"!), defined like so:

+ 1st variable with data type that matches your `current-paragraph:item-id(from loop):field-service-type`. Say you call the variable V1.
    + 2nd variable with data type that matches your `current-paragraph:item-id(from loop):field-select-service`. Say you call the variable V2.
* In your rule, when you invoke the Rules Component:

+ pass a data value for variable V1, which should be your `current-paragraph:item-id(from loop):field-service-type`.
    + pass a data value for variable V2, which should be your `current-paragraph:item-id(from loop):field-select-service`.
    + perform the Rules Condition and Rules Action, using the variables V1 and V2. I'm about sure that, after the Rules Component finished executing, the updated value for V2 will also be reflected in its corresponding `current-paragraph:item-id(from loop):field-select-service` in the Rules where you invoked the Rules Component. If it's not, then try to use "Provided" instead of "Parameter" for V2 (when defining the Rules Component).

### 3. Don't use 'Set a data value' to manipulate lists

The typical mistake in using Rules is that someone incorrectly uses a Rules Action like "Set a data value" (for a multi value field), which will remove all existing values for that field. The correct way is to use a Rules Action "Add to list" (for the new value to be used). This will preserve existing values. Refer to the List and loops video for more details about this.

However, for your scenario, you probably also need to use "Remove from list" (for the old value to be repaced).

PS: I'm assuming this question is about D7.
> 2 votes

---
Tags: rules, paragraphs
---


# Question
Title: Custom Options Value of Views Grouped Filter?
How do I change the select values of a Views groups filter? By default, they are 1,2,3... **Default**

```
<select>
<option value="all">all</option>
<option value="1">Group A</option>
<option value="2">Group B</option>
</select>

```

Desired Result

```
<select>
<option value="all">all</option>
<option value="mycustomname">Group A</option>
<option value="mycustomname2">Group B</option>
</select>

```

# Answer
> 1 votes
I just did something similar for some data I'm exposing in Views for my custom module (it's kinda the same process no matter where views is getting its data).

To do this in the most efficient/easy way possible, you should create your own filter handler.

For a really simple example:

```
<?php
class custom_handler_filter_countries extends views_handler_filter_string {
  /**
   * Shortcut to display the exposed options form.
   */
  function value_form(&$form, &$form_state) {
    $form['value'] = array(
      '#type' => 'select',
      '#title' => t('Countries'),
      '#options' => function_that_returns_options_you_want(),
    );

    return $form;
  }
}
?>

```

Then, in your module's .info file, add the file containing this class (in this example, 'custom\_handler\_filter\_countries.inc') to the .info file's files array (`files[] = includes/custom_handler_filter_countries.inc`).

To make your particular view use this views handler instead of the default handler, you should be able to change the handler in `hook_views_pre_view()`, I think. (On my particular site, since I defined the views data table myself, I just set my custom handler for fields that needed it. For your site, since the normal handler is already defined by Address Field, you need to override the filter handler.

This discussion may also have a possible solution:

Custom Options Value of Views Grouped Filter?

---
Tags: 7, views
---


title: How do I connect to Adsense Account?

text:
# Question
Title: How do I connect to Adsense Account?
I have to add a script section to the head section on the website. I am modifying the html.html.twig file like this:

```
<!DOCTYPE html>
<html {{ html_attributes }}>
  <head>
    <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
    <script>
        (adsbygoogle = window.adsbygoogle || []).push({
            google_ad_client: "ca-pub-6243578269823283",
            enable_page_level_ads: true
        });
    </script>
    <head-placeholder token="{{ placeholder_token|raw }}">
    <title>{{ head_title|safe_join(' | ') }}</title>
    <css-placeholder token="{{ placeholder_token|raw }}">
    <js-placeholder token="{{ placeholder_token|raw }}">--
  </head>
  <body{{ attributes.addClass(body_classes) }}>
    <a href="#main-content" class="visually-hidden focusable skip-link">
      {{ 'Skip to main content'|t }}
    </a>
    {{ page_top }}
    {{ page }}
    {{ page_bottom }}
    <js-bottom-placeholder token="{{ placeholder_token|raw }}">
  </body>
</html>`

```

This seems to not work. Google responded and said I still have to connect my site to Adsense for verification. How do I do this? I have the Adsense module installed but I can't use it until I have an account. This script is for verification so that I can have an account with my website.

# Answer
> 0 votes
Did you already look into dedicated modules for this? There is

Google AdSense integration and Simple AdSense. The first one is more advanced, the second is simpler, but less flexible.

For both, you just have to copy over some values, and the module will take carte of the rest.

---
Tags: google-search-console
---


# Question
Title: D8 - How to create a view to show content with a field that is a User Reference to currently logged in user only
In Drupal 8, I have a content type `Medical Records` that has a field that is an Entity Reference to `Users`. I want to create a View which will display `Medical Records` with that field for the currently logged in user.

How can I do that?

# Answer
you have to create a contextual filter, which will take current user as default value, you can find nice explanation and screenshots here:

http://redcrackle.com/blog/adding-contextual-filter-view-drupal-8

Just filter on **Content: your field name** instead of **Content: Authored by**
> 2 votes

---
Tags: 8, entities, views
---


# Question
Title: Commerce - selecting attribute results in ajax error when product has many attributes
I've got a commerce store running well on a Windows IIS server. The only problem is on certain products which contain many attributes (e.g. around 10 or more) the ajax doesn't work when an attribute is selected. The js error in the console is vague as ever:

```
An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /system/ajax
StatusText: OK
ResponseText:

```

There is nothing untoward in watchdog or in error logs.

The fact that this happens on products with many attributes suggests some sort of PHP limit is being hit, but there are no errors to suggest this. Also worth noting that this is working fine on local/staging server so it's something server based that is the problem here.

Any ideas?

# Answer
> 0 votes
Experienced the same issue. Apache error log "PHP Warning: Unknown: Input variables exceeded 1000. To increase the limit change max\_input\_vars in php.ini."

Editing php.ini and setting max\_input\_vars to a suitable figure fixes this.

---
Tags: commerce, ajax
---


# Question
Title: How to set node author based on a field's values?
**I have an entityreference field that references a redhen\_contact entity. I want to set the node's author to be the user associated with the contact referenced in this field.**

This is part of a (I think, rather basic) custom rendition of the node form via `hook_menu()` and `drupal_get_form`.

I can get the user from the entityreference field and I can print its `name`, `uid`, `email` etc. with `drupal_set_message`. And when I print `$node->uid` with `drupal_set_message` it shows up as if I was successful, but it gets overridden apparently and I have no idea where. The saved nodes always show that I'm the author (as I'm the one submitting the form).

I first tried using `hook_form_alter()`, then I tried using `hook_node_presave()`, then `hook_node_insert()`. I don't know of any hooks that fire later. But maybe one of these hooks would work if I did it right?

Here's most of what I've tried:

```
<?php
function mymodule_register_existing_adult_submit($form, &$form_state) {
  $registrant_id = $form['#node']->field_registrant['und'][0]['target_id'];
//  $contact_wrapper = entity_metadata_wrapper('redhen_contact', $registrant_id);
//  $registrant_name = $contact_wrapper->label();
//  $registrant_email = $contact_wrapper->email->value();
//  $registrant_user = $contact_wrapper->user->value();
//  $registrant_url = $contact_wrapper->user->value();
//  drupal_set_message(t("Hey this works! " . "ID=" . $registrant_id . " " . $registrant_name . " " . $registrant_email . "<br>" . $registrant_user->uid));
//  sdpm($form);
  //$form['additional_settings']['group']['#groups']['additional_settings'][0]['name']['#value'] = $registrant_user->uid;
  //$form['additional_settings']['group']['#groups']['additional_settings'][0]['name']['#default_value'] = $registrant_user->uid;
  //$form['author']['name']['#default_value'] = $registrant_user->uid;
  //$form['author']['name']['#value'] = $registrant_user->uid;
  //$form_state['complete form']['uid']['#value'] = $registrant_user->uid;
  //$form_state['complete form']['uid']['#value'] = $registrant_email;
  //$form_state['values']['uid'] = $registrant_user->uid;
  //$form_state['build_info']['args'][0]->uid = $registrant_user->uid;
  //$form['uid'] = $registrant_user->uid;
//  $form['#node']->uid = $registrant_user->uid;
  //dpm($contact_wrapper->getPropertyInfo());
  $form_state['redirect'] = 'redhen/contact/' . $registrant_id . '/view/edit';
}
function mymodule_node_presave($node) {
  if ( $node->type == 'program_registration' ) {
    $registrant_id = $node->field_registrant['und'][0]['target_id'];
    $contact_wrapper = entity_metadata_wrapper('redhen_contact', $registrant_id);
    $registrant_user = $contact_wrapper->user->value();
    $node->author = $registrant_user->name;
    drupal_set_message('Hook implemented successfully.<br>User ID: ' . $registrant_user->uid);
    drupal_set_message($node->author);
    sdpm($registrant_user);
  }
}
function mymodule_node_insert($node) {
  $path = current_path();
  if ( $path == 'admin/register-existing-adult' ) {
    drupal_set_message('hook_node_insert author: ' . $node->author . '<br>Path: ' . $path);
    $registrant_id = $node->field_registrant['und'][0]['target_id'];
    $contact_wrapper = entity_metadata_wrapper('redhen_contact', $registrant_id);
    $registrant_user = $contact_wrapper->user->value();
    $node->author = $registrant_user->uid;
    $node->uid = $registrant_user->uid;
  }
}

```

---

Edit:

Where I'm at now is I've cleaned up the code to see more precisely what's going one:

```
<?php
function mymodule_node_presave($node) {
  if ( $node->type == 'program_registration' ) {
    $registrant_id = $node->field_registrant['und'][0]['target_id'];
    $contact_wrapper = entity_metadata_wrapper('redhen_contact', $registrant_id);
    $registrant_user = $contact_wrapper->user->value();
    $node->author = $registrant_user->name;
  }
}
function mymodule_node_insert($node) {
  $path = current_path();
  if ( $path == 'admin/register-existing-adult' ) {
    drupal_set_message('author: ' . $node->author);
  }

```

Here `hook_node_insert()` is successfully printing the email address for the user associated with the contact entity. So it seems that the code in `hook_node_presave()` works, except that it must then be overwritten by Drupal afterwards? Or maybe the email address is not a valid value for the node author?

# Answer
The hook depends on what you want to do and when. I don't think that you need to implement the code in `hook_form_alter` as will be executed every time you access that form. Try in your `hook_node_insert` to use `field_attach_update('node', $node);` in order to update your node. Also check https://www.drupal.org/node/2453099. In similar situation (I had to change the author after submit) I created a callback for the specific form where I was changing the author. Finally, keep in mind that when you altering a node you need to save/update it.
> 2 votes

# Answer
Thanks to the link in the accepted answer by Ismini, I figured out how to do this in a form submit callback function.

```
<?php
/**
 * Implements hook_form_FORM_ID_alter().
 * Use this to call your submit function below.
 */
function roots_reg_form_program_registration_node_form_alter(&$form, $form_id, $form_state) {
  $path = current_path();
  if ($path == 'admin/register-new-adult/program') {
    $form['actions']['submit']['#submit'][] = 'mymodule_register_existing_adult_submit';
  }
}

function mymodule_register_existing_adult_submit($form, &$form_state) {
  $registrant_id = $form['#node']->field_registrant['und'][0]['target_id'];
  $contact_wrapper = entity_metadata_wrapper('redhen_contact', $registrant_id);
  $registrant_user = $contact_wrapper->user->value();
  // the following lines made the critical difference
  $nid = $form_state['values']['nid'];
  $node = node_load($nid);
  $node->uid = $registrant_user->uid;
  // calling node_save() is necessary but not at all obvious.
  node_save($node);
}

```
> 0 votes

# Answer
Another solution, alternate to doing it in the form submit callback, is to add `$node->uid = $registrant_user->uid;` to `hook_node_presave()`. In this case I had simply missed the needle in the haystack. So the function could look like:

```
function mymodule_node_presave($node) {
  $path = current_path();
  if ( $path == 'admin/register-existing-adult' ) {
    $registrant_id = $node->field_registrant['und'][0]['target_id'];
    $contact_wrapper = entity_metadata_wrapper('redhen_contact', $registrant_id);
    $registrant_user = $contact_wrapper->user->value();
    // $node->author = $registrant_user->name;
    // doesn't seem to work
    // but...
    $node->uid = $registrant_user->uid;
    // does :)
  }
}

```
> 0 votes

---
Tags: nodes, hooks
---


title: Can't save node using batch

text:
# Question
Title: Can't save node using batch
When I'm trying to save a node using batch processing, I'm getting this error:

> PDOException: in drupal\_write\_record() (line 7383 of C:\wamp64\www\drupal7\includes\common.inc).

Here is my complete code:

```
function custom_node_import_form_submit($form, &$form_state) {
  $csvFile = file_load($form_state['values']['csv_file']);
  $csvFilepath = drupal_realpath($csvFile->uri);
  $file = fopen($csvFilepath, "r");

  $batch = array(
    'operations' => array(),
    'finished' => 'node_import_finished',
    'title' => t('Node import'),
    'init_message' => t('Importing is starting...'),
    'progress_message' => t('Imported @current out of @total.'),
    'error_message' => t('Node importer has encountered an error.')
  );

  fgetcsv($file, 0, ",");
  while($line = fgetcsv($file)) {
    $batch['operations'][] = array('node_import_progress', array(array_map('base64_encode', $line)));
  }

  batch_set($batch);
  batch_process('admin/node/custom-node-import');
  fclose($file);
}

function node_import_progress($line, &$context) {
  $line = array_map('base64_decode', $line);
  saveNode($line);
  $context['message'] = t('Importing %title', array('%title' => $line[0]));
}

function node_import_finished($success, $results, $operations) {
  if ($success) {
    drupal_set_message(t('Node importing is complete!'));
  }
  else {
    $error_operation = reset($operations);
    $message = t('An error occurred while processing %error_operation with arguments: @arguments', array(
      '%error_operation' => $error_operation[0],
      '@arguments' => print_r($error_operation[1], TRUE)
    ));
    drupal_set_message($message, 'error');
  }
}
function saveNode($param = []) {
  global $user;

  $node = new stdClass();
  $node->title = $param[0];
  $node->type = "article";
  node_object_prepare($node);
  $node->language = LANGUAGE_NONE;
  $node->uid = $user->uid;
  $node->status = 1;
  $node->promote = 0;
  $node->comment = 1;
  $node->body[$node->language][]['value'] = $param[3];

  $node = node_submit($node);
  node_save($node);
}

```

I have debugged and found that the line which gives this error is the last line where the node is getting saved. i.e **node\_save($node);**

# Answer
> 1 votes
The issue was with the non-English characters in the CSV file like ö, ä etc

So the solution was to use utf8\_encode() for the values:

```
$node->title = utf8_encode($param[0]);
$node->body[$node->language][]['value'] = utf8_encode($param[3]);

```

Hope it helps somebody.

---
Tags: 7, nodes, batch-operations
---


# Question
Title: D8, how to make node template aware of entity reference parent
I have a multivalue entity reference field, referencing basic content. The content (node) view is controlled via display modes (display modes is probably not relevant to the question)

Right now the entity reference field template is 'boilerplate' and just outputs the content in a for loop.

```
{% for item in items %}
    {{ item.content }}
{% endfor %}

```

My display node template, node--\[content type\]--\[display mode\].tpl.twig has custom markup, and granular output of field values.

However somewhere 'deep' in this template I need to alter the markup in accordance with the position this node has in the parent referencing entity.

i.e.

* entity reference field:
    + node 1
    + node 2
    + node 3 \<-- pass this list position value somehow into the child node template, so i can change the markup inside
    + node 4

I've been stepping through preprocessor variables in node\_preprocess and field\_preprocess, but I'm not really clear if the child node is 'aware' of its parent field, or more importantly the hierarchy of the parent field, and its position in it.

Any help or pointers much appreciated!

# Answer
well, this seems to be working.

```
function THEME_preprocess_node(&$variables) {
$nid  = $variables['node']->id();

if ($variables['elements']['#view_mode'] === 'VIEW_MODE') {
// Get the node ID.
    $variables['nid'] = $nid;
    $parent   = $variables['elements']['#node']->_referringItem->getEntity();
    $items = $parent->get('FIELD_NAME')->getValue();

    foreach ($items as $key => $item) {
        if ($item['target_id'] == $nid) {
            $variables['tree_position'] = $key;
        }
    }
  }
}

```

Not sure this is the best way. So any suggestions still welcome.
> 2 votes

---
Tags: theming, 8, entities
---


# Question
Title: How to import beans using the migrate module?
The migrate module allows you to migrate many different kinds of content with what it calls Destination Classes. However i don't see support for beans in there.

I've searched in https://drupal.org/project/migrate\_extras and https://drupal.org/project/issues/migrate\_extras?categories=All to no avail. So my question is how would i go about importing beans into my DB?

For the moment i've been using bean\_create, however I believe an implementation that hooks into migrate would be better.

The default Destination Classes are https://drupal.org/node/1006988

# Answer
> 1 votes
This forum post shows an example DestinationHandler and Migration

https://drupal.org/node/2141211

# Answer
> 0 votes
In case someone is looking to do this from Drupal 7 to Drupal 8, this is how it can be done: https://github.com/npinos/d7migrate

---
Tags: migrations, blocks
---


# Question
Title: How to create a Size field on Commerce product content fields?
I am new to Drupal Commerce and I have set up a store. But the problem is that adding variations for each product is a pain, especially when the product has more than 5 colors and 4 sizes.

What I want to do is to have a size Field in Content type instead of product type's fields so that I add the sizes only once (like choosing the categories or collection).

And then customers can select a radio button or so to be able to add the item to the Shopping Cart.

How can I make it work or is there another solution for it?

# Answer
> 0 votes
I'd go for another solution/approach, as detailed below ...

# Commerce Bulk Product Creation

You may want to use the Commerce Bulk Product Creation module. Excerpt from its project page:

> ... facilitates the creation of groups of related products in bulk. Product administrators can select a number of options for various fields, and a product will be created for all possible combinations of these values. Out of the box, only list fields are supported for this, but an API exists to enable other types of fields for 'combination creation'.

**Attention**: this module doesn't have an official release yet (only an RC6), though with over 1.200 reported installs, it seems it is pretty stable / trustworthy.

# Commerce Backoffice

Another option is to use the Commerce Backoffice module, e.g. because of the ***auto creation of product display nodes***. It provides the backoffice functionality present in Commerce Kickstart (V2), and contains these sub-modules:

* Commerce Backoffice **Product** (commerce\_backoffice\_product).
* Commerce Backoffice **Order** (commerce\_backoffice\_order).
* Commerce Backoffice **Content** (commerce\_backoffice\_content).

This module (and a few dependencies) provides the rich store owner experience that has made Commerce Kickstart 2 so popular (and prevents that you have to install the entire Commerce Kickstart distribution). And there is a great video introduction about it also.

**Note**: if you use Commerce Backoffice, you most probably also want to use the Shiny administration theme, also used in Commerce Kickstart (V2).

---
Tags: commerce
---


# Question
Title: Get referenced node fields in twig where reference is on remote node only
I have a reference field with reference on `node 2` to `node 1`.

On `node 1` I want to find those nodes `node 2` with reference to node 1.

How can I access those in twig?

# Answer
Your node is unaware of the fact that it is referenced by other nodes. So you need to query the nodes that are referencing your node in a preprocess hook:

```
/**
 * Implements hook_preprocess_HOOK() for node templates.
 */
function mytheme_preprocess_node(&$variables) {
  $node = $variables['node'];
  $storage = \Drupal::entityTypeManager()->getStorage('node');
  $nodes2 = $storage->loadByProperties(['field_reference' => $node->id()]);
  $variables['nodes2'] = $nodes2;
  $variables['#cache']['tags'][] = 'node_list';

}

```

Then you can use the nodes you've found in Twig directly:

```
{% for node2 in nodes2 %}
  <p>This node is referenced by {{ node2.label }} ({{ node2.id }})</p>
{% endfor %}

```

**Rendering of the nodes**

Or better build a entity view of those nodes by specifying a custom view mode, which you have configured to display the fields you want:

```
if ($nodes2) {
  $view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
  $nodes2_rendered = $view_builder->viewMultiple($nodes2, 'custom_view_mode');
  $variables['nodes2_rendered'] = $nodes2_rendered;
}

```

and render those nodes in Twig:

```
{{ nodes2_rendered }}

```

---

Edit:

You can now use a content type specific node\_list cache tag to make caching more efficient. See this change record https://www.drupal.org/node/3107058
> 4 votes

---
Tags: theming, 8
---


# Question
Title: Why doesn't my first blog entry show up on my last page?
On a site that I created a few years ago, my very first blog post does not show up when I browse from the front page to the last page. All my other blog entries seem to show up there. When I manually enter the URL of the first blog post, it loads fine. And when I edit that first blog post it shows as "published".

Why isn't it showing up in the paginated list from the front page?

**Note**: I'm using the default front page display, with Blog module content set to "Promoted to front page". I checked the publication date and it looks fine. I'm not sure what else I can specify. It's basically Drupal showing blog posts on the front page but the very first one for some reason doesn't show up.

# Answer
> 2 votes
It turns out that for some reason this particular blog entry had lost its selection of "Promoted to Front Page" in "Publishing". The content type is set to go to front page by default, and this entry used to be on the front page, so it probably got deselected by accident at some point. Restoring the checkmark fixed the problem.

---
Tags: paging, nodes
---


title: Views: Combine Fields Filter "OR"?

text:
# Question
Title: Views: Combine Fields Filter "OR"?
How do I combine two fields using the Views Global: Combine Fields Filter using an "Or" statement? For example, if my filter combines Field A and Field B and my content is has Field A-\>Option A, Field B-\> option C, it would show up when my filter is set to A OR C.

Desired results:

Field A \- **Option A** \- Option B \- Option C

Field B \- Option A \- Option B \- **Option C**

Combined Filter select Menu: **Option A** Expected result, content shows.

The default behavior seems to require that value is present in both field not either.

# Answer
> 0 votes
This was accomplished using Operator "CONTAINS" vs default "IS EQUAL TO"

I set a custom group and inputted values manually and had the operator set to contains, so for example if I select "Option A" in my filter and piece of content with either field a or field b with "option a" selected would show up.

---
Tags: 7, views
---


# Question
Title: An illegal choice has been detected. Please contact the site administrator
I have a taxonomy list of 'make' of vehicle say 'Toyota'. The second list would be models of the make selected make - 'Corolla', 'Hilux', 'Land Cruiser' etc. I'm using the http://www.drupal8.ovh/en/tutoriels/244/create-a-custom-content-entity-on-drupal-8-full. I have tried different options on the vehicleForm.php. I can't get past this error when I click to save the vehicle entity. if I comment "'#validated' =\> TRUE," the error changes to "Argument 1 passed to Drupal\Core\Field\WidgetBase::massageFormValues() must be of the type array, string given...". I have googled these 2 errors without success. Please help. So far here is my code:

```
namespace Drupal\vehicle\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\ContentEntityForm;
/**
 * VehicleForm.
 */
class VehicleForm extends ContentEntityForm {
//  class VehicleForm extends FormBase {
  /**
   * The term Storage.
   *
   * @var \Drupal\taxonomy\TermStorageInterface
   */
  protected $termStorage;

  /**
   * {@inheritdoc}
   */
  public function __construct(EntityTypeManagerInterface $entity) {
    $this->termStorage = $entity->getStorage('taxonomy_term');
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    // Instantiates this form class.
    return new static(
    // Load the service required to construct this class.
    $container->get('entity_type.manager')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'vehicle_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $params = NULL) {

    $form = parent::buildForm($form, $form_state);
    $entity = $this->entity;

    $terms = $this->termStorage->loadTree('make', 0, NULL, TRUE);
    $options = [];
    if ($terms) {
      foreach ($terms as $term) {
        $options[$term->getName()] = $term->getName();
      }
    }
    $form['make'] = array(
      '#type'    => 'select',
      '#title'   => $this->t('make'),
      '#options' => $options,
      '#ajax'    => array(
        'callback' => [$this, 'selectModelsAjax'],
        'wrapper'  => 'model_wrapper',
      ),
    );

    $form['model'] = array(
      '#type'      => 'select',
      '#title'     => $this->t('Model'),
      '#options'   => ['_none' => $this->t('- Select a make first -')],
      '#prefix'    => '<div id="model_wrapper">',
      '#suffix'    => '</div>',
//      '#validated' => TRUE,
    );

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

  }

  /**
   * {@inheritdoc}
   */

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $status = parent::save($form, $form_state);
    //dpm($status);
    $entity = $this->entity;
    if ($status == SAVED_UPDATED) {
      drupal_set_message($this->t('The contact %feed has been updated.', ['%feed' => $entity->toLink()->toString()]));
    } else {
      drupal_set_message($this->t('The contact %feed has been added.', ['%feed' => $entity->toLink()->toString()]));
    }

    $form_state->setRedirectUrl($this->entity->toUrl('collection'));
    return $status;
  }

  /**
   * Called via Ajax to populate the Model field according make.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return array
   *   The form model field structure.
   */
  public function selectModelsAjax(array &$form, FormStateInterface $form_state) {
    $options = [];

    $vocabulary = 'title';
    switch ($form_state->getValue('make')) {
      case 'Benz':
        $vocabulary = 'benz';
        break;
      case 'BMW':
        $vocabulary = 'bmw';
        break;
      case 'Toyota':
        $vocabulary = 'toyota';
        break;
    }

    $models = $this->termStorage->loadTree($vocabulary, 0, NULL, TRUE);
    if ($models) {
      foreach ($models as $model) {
        $options[$model->id()] = $model->getName();
      }
    }
    $form['model']['#options'] = $options;

    return $form['model'];
  }
}

```

# Answer
> 1 votes
You cannot make changes to the $form array in ajax callback functions, as the form has already been cached. When Drupal later compares the submitted values to the cache, they don't exist, and you see the error you are seeing.

All changes to the form need to be made in the form definition (or a \_form\_alter() hook). Use values in the form state to determine if you are in an ajax submit or the initial form build.

---
Tags: entities, ajax
---


# Question
Title: How do I programmatically log in a user?
I am looking for the API that will let me login a user by passing it the username and password. Does anyone have experience with this?

To clarify, I am trying to make an AJAX login box that appears as a popup on the home page, and do not refresh the page in case of wrong credentials, but only if the log in is correct. So here is what i have done so far:

### Update

I now load the login form on my homepage, then on submission I launch an AJAX request that sends credential to this script:

```
function user_login_submit_try() {
  global $user;

  $uid = user_authenticate($_POST['name'],$_POST['pass']);
  $arr = array ('name'=>$_POST['name'],'pass'=>$_POST['pass']);
  if ($uid){
    $user = user_load($uid);
    user_login_finalize($arr);
  }

  echo drupal_json_encode($uid);
  exit;
};

```

So far it works, but my worries are (as mentioned by googletorp) security issues; it seems that none of the API I used in this script sanitized the data in anyway.

Would anyone see a better way to do so?

# Answer
> 34 votes
This might help someone:

```
function mymodule_user_login_credentials($username, $password)
{
    if(user_authenticate($username, $password))
    {
      $user_obj = user_load_by_name($username);
      $form_state = array();
      $form_state['uid'] = $user_obj->uid;
      user_login_submit(array(), $form_state);
      return true;
    }
    else
    {
        return false;
    }
}

```

A better version based on the comment:

```
function mymodule_user_login_credentials($username, $password)
{
    if($uid = user_authenticate($username, $password))
    {
      user_login_submit(array(), array('uid' => $uid));
      return true;
    }
    else
    {
        return false;
    }
}

```

# Answer
> 20 votes
There is not a simple API function for that.

You can do what Drupal does:

1. Test the password by querying the database see:

> user\_login\_name\_validate()
> user\_login\_authenticate\_validate()
> user\_login\_final\_validate()

2. Overwrite the `global $user`.

```
global $user;
$user = user_load($uid);

```
3. Handle sessions

> `user_login_finalize($form_state);`

For step two and 3 see `user_login_submit()`

All these functions are based on being called from a form. The normal flow is that the validate handlers test the users input and returns the uid of the user if validation passes. The submit handler then handles the actual login of the user and calling user hook.

# Answer
> 7 votes
If you need to get the user object for the user account for which you know username and password, then you can use the following code:

```
function mymodule_get_user(name, $password) {
  $account = FALSE;

  if ($uid = user_authenticate($name, $password)) {
    $account = user_load($uid);
  }

  return $account;
}

```

`$account` will be `FALSE` if the user object cannot be found or loaded.

You should use this code when, for example, your module gets the username and password as input from a user, it verifies if they are correct, and then it does something with the user object.
If you are writing a module that needs to impersonate a user to write a comment, or doing something else that needs to result as done by a user, which is what the Project issue tracking module does when closing an issue report that has been in the *fixed* status for two weeks (in that case, it adds the comment "Automatically closed -- issue fixed for 2 weeks with no activity" which results written by the "System Message" user), then you don't need username and password. You just load the user object for which you know the user ID.

As far as I know, there aren't any security issues with the code I reported.
You could want to limit the number of failed logins; or to temporary block the IP which tries to log in without success, or tries different logins in short time.

# Answer
> 3 votes
This code really works

```
//login
$uid = user_authenticate($username, $password);
global $user;
$user = user_load($uid);
//login finalize
watchdog('remote_user', 'Session opened for %name.', array('%name' => $user->name));
$user->login = REQUEST_TIME;
db_update('users')
  ->fields(array('login' => $user->login))
  ->condition('uid', $user->uid)
  ->execute();
drupal_session_regenerate();

```

# Answer
> 2 votes
Cleaned up answer from the above. Checking user and password is an additional feature. Also, the fake form\_state needs to be a variable to be passed by reference to the function or it throws an error.

Hence we have:

```
function mymodule_log_in_by_uid($uid) {
    $faux_form_state = array('uid' => $uid);
    user_login_submit(array(), $faux_form_state);
}

```

# Answer
> 1 votes
The user will receive the session and will also be logged on to other pages:

```
function custom_log_in_by_uid($uid) {
    $form_state = array('uid' => $uid);
    user_login_submit(array(), $form_state);
}

```

# Answer
> 0 votes
Sometimes we need quick login from URL or Forgot admin password. Just implement below two functions to login as user 1 in Drupal.

```
function mymodule_menu(){
    $items['login/as/admin'] = array(
        'title' => 'Login as admin account',
        'page callback' => 'mymodule_login_as_admin',
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
    );
    return $items;
}
function mymodule_login_as_admin(){
    global $user;
    $user = user_load(1);
    return "Global user set as admin. Please refresh page ";
}

```

---
Tags: 7, users
---


# Question
Title: How do I set the absolute path for an image?
I use image upload default ckeditor and IMCE module for drupal 8. But both of them return relative paths.

Output code actual relative path:

```
<img src="/sites/default/files/Images/image1.jpg">

```

Output code expected absolute path:

```
<img src="http://example.com/sites/default/files/Images/image1.jpg">

```

How to correct it?

# Answer
> 1 votes
IMCE has a checkbox setting to enable absolute paths in configuration page

# Answer
> 1 votes
Step to set absolute path of image in ckeditor.

1. Firstly install and enable  Module.
2. Go to the editor setting "admin/config/content/formats/manage/basic\_html" In CKEditor plugin settings disable "Enable image uploads Disable to use IMCE file browser." checkbox.

3.Go to IMCE setting page "admin/config/media/imce" and "Enable absolute URLs" checkbox in conman settings section.

---
Tags: 8, media, wysiwyg
---


# Question
Title: Disabling language prefix for route in module
How can I disable the automatic redirect to the language prefixed URL for a URL defined in a `routing.yml` in my module?

I'm developing a custom sitemap.xml module, because the Simple Sitemap XML module does not have the options I need. I've got it just about working, except the URL `/sitemap.xml` 301 automatically redirects to the URL `/lang/sitemap.xml` \- and it really shouldn't. How can I disable this redirect?

# Answer
> 6 votes
Yes, has to be redirect.module, core doesn't do that. See https://www.drupal.org/node/2854462#comment-12047347, just add the '\_disable\_route\_normalizer' flag to your route and you should be fine.

module\_sitemap.routing.yml:

```
module_sitemap.sitemap:
  path: '/sitemap.xml'
  defaults:
    _controller: '\Drupal\module_sitemap\Controller\SitemapController::view'
    _title: 'View Site Map'
    _disable_route_normalizer: 'TRUE'

```

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


title: How do I add elements to a node view?

text:
# Question
Title: How do I add elements to a node view?
In Drupal 8 routes like entity.node.webform.user.submissions (path such as /node/2/submissions), entity.node.webform\_submission.canonical (path such as /node/2/submission/118) etc etc display entity view in the main content block. My question how would I append/pre-append/insert html elements (such as link tag,submit button, textfield etc etc) in the entity view.For example if the view shows a table listing submissions how to pre-append a link button at the top right corner of the table. I have tried:

```
function my_module_entity_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display){
    kint($build);
    kint($entity);
    }

```

In `kint($build)` and `kint($entity)` I can't see any part where to add HTML markup. How and where should I add it?

# Answer
The Webform module for Drupal 8 does not fully support display modes. To alter a submission's HTML or text you will need to use hook\_preprocess\_webform\_submission\_html() and hook\_preprocess\_webform\_submission\_text().

I created a ticket on D.O. to look into this issue.
> 0 votes

---
Tags: views, nodes, webforms
---


title: Can't print path field in view twig

text:
# Question
Title: Can't print path field in view twig
I have custom twig for a view (views-view--new-blogs--page-1.html.twig) where i can't print the path field for read more link. How to print the path field in the above twig.

# Answer
Enable debugging by these commands:

https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates

When debugging is enabled and you go to the subpage with this view, you will see a full link in the comments.
> 0 votes

---
Tags: views
---


# Question
Title: Why does Drupal constantly reload front page when caching for anonymous users is enabled?
Drupal 7 constantly reloads the front page when caching for anonymous users is enabled, no matter which caching engine I use.

I use nginx + php7.0-fpm. Current cache backend is Redis. I cannot catch the error.

I have following behaviour: when caching for anonymous users is enabled, the front page loads completely and then refreshes again and again until I disable caching or clean it all both in Drupal admin interface and in redis cli interface. If the cache changed or expired, then series of reloads start once again. Watchdog does not show any error, so as nginx log.

Any hints?

My settings: Nginx vhost:

```
server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;
    root /var/www/example.com;

    return 301 https://$host$request_uri;

 }

 server {
    listen 443 ssl;
    listen [::]:443 ssl;

    ssl on;
    ssl_certificate /etc/letsencrypt/live/jobmens.ru/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/jobmens.ru/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot

    server_name example.com www.example.com;
    root /var/www/example.com;

    index  index.html index.htm;

    access_log /var/log/nginx/example.com.access.log;

    error_log /var/log/nginx/example.com.error.log;

    include acme;

    ssi on;
    ssi_silent_errors on;

    location ~ (^|/)\. {
       return 403;
    }

    location ~ /sites/.*/private-files/ {
       deny all;
       return 403;
    }

    location ~ /sites/.*/files/styles/ {
       try_files $uri @drupal;
       expires 31d;
       log_not_found off;
    }

    location ~* \.(eot|otf|ttf|woff|woff2)$ {
       try_files $uri =404;
       expires 31d;
       log_not_found off;
       add_header Access-Control-Allow-Origin *;
    }

    location ~* ^(?!/phpmyadmin/).+\.(png|gif|jpg|jpeg|css|js|ico|swf|flw|cgi|bat|pl|dll|exe|asp|eot|woff|ttf|swg|gz)$ {
       try_files $uri =404;
       expires 31d;
       log_not_found off;
    }

    location ~ (?<upload_form_uri>.*)/x-progress-id:(?<upload_id>\d*) {
       rewrite ^ $upload_form_uri?X-Progress-ID=$upload_id;
    }

    location ^~ /progress {
       upload_progress_json_output;
       report_uploads uploads;
    }

    # Dynamic requests goes here.
    location / {
       error_page 404 502 = @drupal;
       try_files $uri @drupal;
       if ($http_host ~* "^www\.(.+)$"){
          rewrite ^(.*)$ https://example.com$request_uri redirect;
       }
    }

    location @drupal {
       fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
       fastcgi_index  index.php;
       fastcgi_read_timeout 600;
       fastcgi_param  SCRIPT_FILENAME      $document_root/index.php;
       fastcgi_param  QUERY_STRING         q=$uri&$args;
       fastcgi_param  REQUEST_METHOD       $request_method;
       fastcgi_param  CONTENT_TYPE         $content_type;
       fastcgi_param  CONTENT_LENGTH       $content_length;
       fastcgi_param  REDIRECT_STATUS      200;
       fastcgi_param  SCRIPT_NAME          /index.php;
       fastcgi_param  REQUEST_URI          $request_uri;
       fastcgi_param  DOCUMENT_URI         $document_uri;
       fastcgi_param  DOCUMENT_ROOT        $document_root;
       fastcgi_param  SERVER_PROTOCOL      $server_protocol;
       fastcgi_param  GATEWAY_INTERFACE    CGI/1.1;
       fastcgi_param  SERVER_SOFTWARE      nginx/$nginx_version;
       fastcgi_param  REMOTE_ADDR          $remote_addr;
       fastcgi_param  REMOTE_PORT          $remote_port;
       fastcgi_param  SERVER_ADDR          $server_addr;
       fastcgi_param  SERVER_PORT          $server_port;
       fastcgi_param  SERVER_NAME          $server_name;
       fastcgi_param  HTTPS                'on';

       fastcgi_buffers 16 32k;
       fastcgi_buffer_size 32k;

       track_uploads uploads 60s;
    }

 }

```

Nginx conf:

```
user webserver;
error_log /var/log/nginx/error.log debug;
# access_log /var/log/nginx/access.log
pid /var/run/nginx.pid;
worker_rlimit_nofile 80000;
worker_processes auto;

events {
    worker_connections 2048;
    use epoll;
}

http {
    server_names_hash_bucket_size 64;
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    log_format main ‘$remote_addr – $remote_user [$time_local] $status ‘
        ‘«$request» $body_bytes_sent «$http_referer» ‘
        ‘«$http_user_agent» «http_x_forwarded_for»‘;
    access_log /var/log/nginx/access.log main;
    aio threads;

    client_max_body_size 10M;
    client_body_buffer_size 256k;
    upload_progress uploads 1m;

    sendfile on;
    tcp_nopush on;
    server_tokens off;
    keepalive_timeout 300;

    gzip on;
    gzip_static on;
    gzip_vary on;
    gzip_min_length 1100;
    gzip_buffers 64 8k;
    gzip_comp_level 9;
    gzip_http_version 1.1;
    gzip_proxied any;
    gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript application/atom+xml application/rdf+xml application/x-font-ttf application/x-font-otf application/font-woff application/font-woff2 application/vnd.ms-fontobject;
    gzip_disable "MSIE [1-6]\.(?!.*SV1)";

    include /etc/nginx/conf.d/*.conf;
}

```

php7.0-fpm: only username and socket address modified

Drupal 7 settings:

```
<?php

$databases = array (
  'default' =>
    array (
      'default' =>
         array (
           'database' => 'dbname',
           'username' => 'dbuser',
           'password' => 'dbpass',
           'host' => 'dbhost',
           'port' => '',
           'driver' => 'mysql',
           'prefix' => '',
           'charset' => 'utf8mb4',
           'collation' => 'utf8mb4_general_ci',
         ),
    ),
);

$update_free_access = FALSE;

$drupal_hash_salt = 'salt';

$base_url = 'https://example.com';  // NO trailing slash!

ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 100);

ini_set('session.gc_maxlifetime', 200000);

ini_set('session.cookie_lifetime', 2000000);

$conf['reverse_proxy'] = TRUE;

$conf['reverse_proxy_addresses'] = array('IPs',);

$conf['404_fast_paths_exclude'] = '/\/(?:styles)|(?:system\/files)\//';
$conf['404_fast_paths'] = '/\.(?:txt|png|gif|jpe?g|css|js|ico|swf|flv|cgi|bat|pl|dll|exe|asp)$/i';
$conf['404_fast_html'] = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL "@path" was not found on this server.</p></body></html>';

$conf['redis_client_interface'] = 'PhpRedis'; // Can be "Predis".
$conf['redis_client_host']      = '127.0.0.1';  // Your Redis instance hostname.
$conf['redis_cache_socket']     = '/var/run/redis/redis.sock';
$conf['lock_inc']               = 'sites/all/modules/redis/redis.lock.inc';
$conf['path_inc']               = 'sites/all/modules/redis/redis.path.inc';
$conf['cache_backends'][]       = 'sites/all/modules/redis/redis.autoload.inc';
$conf['cache_default_class']    = 'Redis_Cache';

```

uname -a:

```
4.10.0-36-generic #40~16.04.1-Ubuntu SMP Tue Sep 19 15:26:00 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

```

# Answer
Solution found. Suddenly, it was a problem with IPGV&M module. There is no unexpected behaviour after disabling this module.
> 0 votes

---
Tags: 7, caching
---


# Question
Title: How do I create relevant keyword search?
I created a view and fetched the content from a content type. I created an exposed filter with two fields (*title* and *body*) using contextual filters.

Search works for exact match keywords, but it doesn't work with similar keywords. For example, for *timesheet* and *application* it works fine, but if I search using the wrong spelling (for example, *timeshet* or *appliction*), it doesn't work.

How do I create a keyword relevant search?

# Answer
You would need Search API and Search API Solr for this, along with a Solr instance to get relevancy scoring and support for fuzzy searching (e.g. iphone iphane etc).

It is mostly configurable from the Drupal UI.
> 1 votes

---
Tags: views, search
---


title: Migration Group Not showing in UI

text:
# Question
Title: Migration Group Not showing in UI
I am trying to migrate users table from drupal 7 to drupal 8 for that i have created custom migration module and create two file in config/install folder with the following names

> custom\_migration.migration\_group.open.yml
>
> custom\_migration.migration.custom\_user.yml

and **User.php** in `Plugin/migrate/source` for mapping fields.

The following showing content for `custom_migration.migration_group.open.yml`

```
id: open
label: Open Migration
description: Custom Migration user table form drupal 7 to drupal 8.
source_type: Drupal 7
source:
  key: drupal_7
dependencies:
  enforced:
    module:
      - custom_migration

```

Following Content is from `custom_migration.migration.custom_user.yml`

```
id: custom_user
label: Custom user migration
migration_group: open
source:
 plugin: custom_user
destination:
 plugin: entity:user
process:
 uid: uid
 name: name
 pass: pass
 mail: mail
 status: status
 created: created
 changed: changed
 access: access
 login: login
 timezone: timezone
 langcode: language
 preferred_langcode: language
 preferred_admin_langcode: language

```

When i enable the module it should show migration group in `Structure->Migration` . But it is not showing. Any idea why?

# Answer
> 3 votes
The filenames are wrong - they need to be migrate\_plus.migration.\*, not custom\_migration.migration.\*. The first component of a configuration entity filename is the module that defines the entity *type*, not the module defining the entity *instance*.

---
Tags: 8, migrations
---


# Question
Title: How to remove any data "http_proxy" module added or changed?
I have a serious problem with a broken XML-Feed, that occurred after I installed http\_proxy module. I have uninstalled the module, cleared the cache several times and even truncated the cache tables of the database manually. (I have to admit i didn't made a database backup before the installation). The XML feed is flawless, actually it didn't change at all.

I have following error messages:

in the drupal log:

> Notice: Undefined offset: 1 in http\_request\_get() (Zeile 239 von /example.com/sites/all/modules/feeds/libraries/http\_request.inc).

The error message above is 2 times in the log with the same timestamp. Then more recent:

> Warning: simplexml\_import\_dom(): Invalid Nodetype to import in FeedsExXpathDomXpath-\>\__construct() (Zeile 393 von /example.com/sites/all/modules/feeds\_ex/src/FeedsExXml.inc).

followed by from the feeds module log:

> Start tag expected, '\<' not found on line 1. Error code: 4

So i guess this comes from the http\_proxy module. How can i remove any trace of it? Does someone have another idea where to look?

Thanks!

# Answer
Uninstalling the HTTP proxy module appears to *not* uninstall its configuration. So the proxy configuration is likely still in place in your case. I assume that the reason the HTTP proxy module does not remove the configuration is that it doesn't explicitly "owns" the configuration: it exposes hidden settings from Drupal core.

There is an issue about this reported in the http\_proxy issue queue: https://www.drupal.org/node/2592461
> 1 votes

---
Tags: 7, feeds, http-request
---


title: How do you alter a form error?

text:
# Question
Title: How do you alter a form error?
How do you alter or remove a form error produced by Drupal or another module on node insert/save, for a particular content type. I'm looking for a method which I can use in a module.

I've tried hook\_node\_validate(), but all I was able to do is to get errors and set errors.

# Answer
## Altering strings

To change the text of a single string, the simplest method is to use the String Overrides module. That would allow you to replace the string:

> "!name field is required."

with (for example):

> "The field '!name' is required."

## Altering form fields

If you want to make a field not required, use a normal hook\_form\_alter() implementation:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_node_form_alter(&$form, &$form_state) {
  $node = $form['#node'];
  if ($node->type == 'my_custom_type') {
    $form['title']['#required'] = FALSE;
  }
}

```

## Changing the way a form is validated

Forms have validation functions specified in the `$form['#validate']` array. And form elements have functions specified in `$form['element_key']['#element_validate']`.

You can specify your own like this:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_node_form_alter(&$form, &$form_state) {
  $form['title']['#element_validate'][] = 'mymodule_validate_node_title';
}

/**
 * Validate the node title to prevent ALL CAPS.
 */
function mymodule_validate_node_title($element, &$form_state, $form) {
  if (preg_match('/^[A-Z]+$/', $element['#value'])) {
    form_error($element, t('You may not enter titles in ALL CAPS.'));
  }
}

```
> 13 votes

# Answer
Since the string used for that error message is "!name field is required." using the String Overrides module or changing the string to use in the settings.php file would have the effect to change the string used for every required form field.

If you want to alter the error string shown for the title when the title has not been entered, you can:

* Add a form validation handler to the node edit form, using `hook_form_alter()`
* In that form validantion handler:

+ Verify the content of `$form['title']` (where `$form` is set using `$form = &drupal_static('form_set_error', array());`, and change it to the string you want when it is `'Title field is required.'`
    + Verify `$_SESSION['messages']['error']` (an array) contains the string `'Title field is required.'` and change it to the string you want to show

Avoiding to show the error is easier: Just set the `#required` property to `FALSE`, and Drupal will not show that error message.
> 6 votes

# Answer
For drupal 7 you can download this module http://drupal.org/node/1209450 in zip it will give you this hook.

```
message_alter(&$messages) {
}

```
> 4 votes

# Answer
You can customize form error messages by using Field validation per entity field.

To do that, edit field settings, go to Validation and add a new validation rule (*Required field*). There, you should have textfield to set-up *Custom error message* for that field.
> 1 votes

# Answer
For Drupal 8, I was able to add a custom validate function that can actually examine the existing errors, and change the markup of the errors on a per case basis. In my case, I wanted to alter the error message from an entity\_autocomplete field that was referencing users. If an invalid user was added, the validation error read, "There are no entities matching %name". Instead of the word "entities", I wanted to have it say "users", to be less scary and potentially confusing to users.

First, I use hook\_form\_alter() to add my validate function:

```
/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {

      if (in_array($form_id, ['whatever_form_id_you_need_to_alter'])) {
        // Add entity autocomplete custom form validation messages alter.
        array_unshift($form['#validate'], 'my_module_custom_user_validate');
      }

```

Then, in the 'my\_module\_custom\_user\_validate' function:

```
/**
 * Custom form validation handler that alters default validation.
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
*/
function my_module_custom_user_validate(&$form, FormStateInterface $form_state) {
      // Check for any errors on the form_state
      $errors = $form_state->getErrors();
      if ($errors) {
        foreach ($errors as $error_key => $error_val) {
          // Check to see if the error is related to the desired field:
          if (strpos($error_key, 'the_entity_reference_field_machine_name') !== FALSE) {
            // Check for the word 'entities', which I want to replace
            if (strpos($error_val->getUntranslatedString(), 'entities') == TRUE) {
              // Get the original args to pass into the new message
              $original_args = $error_val->getArguments();
              // Re-construct the error
              $error_val->__construct("There are no users matching the name %value", $original_args);
            }
          }
        }
      }
    }

```

Hope this helps!
> 0 votes

---
Tags: 7, forms
---


# Question
Title: How to load node object in node preview page?
In drupal 8, how do you load the node object in hook\_preprocess\_page() when on *the node preview page*?

I had a bug come up where this standard way of loading the current node object was failing on the preview page:

```
$node = \Drupal::routeMatch()->getParameter('node');

```

# Answer
> 10 votes
If you need to use the node object in hook\_preprocess\_page() on the preview page, you need to use the "node\_preview" parameter, instead of the "node" parameter:

```
function mymodule_preprocess_page(&$vars) {

  $route_name = \Drupal::routeMatch()->getRouteName();

  if ($route_name == 'entity.node.canonical') {
    $node = \Drupal::routeMatch()->getParameter('node');
  }
  elseif ($route_name == 'entity.node.preview') {
    $node = \Drupal::routeMatch()->getParameter('node_preview');
  }

```

---
Tags: 8, nodes
---


# Question
Title: User migration not setting custom field values correctly
I have a User migration in Drupal 8 which is coming from custom SQL tables. The user entity in Drupal 8 has a bunch of custom fields on it (First Name, Last Name, About, etc).

When I run the migration I can go into the field data tables in Drupal 8 and see that all of the values are there in the table where they should be, meaning they migrated into the new database correctly.

If I go to the users' edit pages (/user/#/edit), the fields are completely empty. If I then click save and wait for the page to reload, all of the migrated values magically appear in the form.

I tried running a post-migration script to manually save the users, but it still does not make the fields show up and I have to manually save the empty form for the values to show.

Here is the post-migration script I tried:

```
$ignored_users = [0, 1];
$uids = db_select('users', 'u')
  ->condition('uid', $ignored_users, 'NOT IN')
  ->fields('u', ['uid'])
  ->execute()
  ->fetchCol();

$users = user_load_multiple($uids);

foreach ($users as $user) {
  $user->save();
}

```

This is my config for the migration:

```
id: my_users
label: User Migration
migration_group: users
source:
  plugin: migrate_users
destination:
  plugin: entity:user
process:
  uid: uid
  name: name
  pass: pass
  mail: mail
  status: status
  created: created
  changed: changed
  access: access
  login: login
  langcode: language
  preferred_langcode: language
  preferred_admin_langcode: language
  init: init
  roles: roles
  user_picture:
    plugin: migration
    migration: my_files
    source: field_image_fid
  'field_about/value': body_value
  'field_about/summary': body_summary
  'field_about/format':
    plugin: default_value
    default_value: full_html
  field_first_name: field_first_name_value
  field_last_name: field_last_name_value
migration_dependencies:
  required:
    - my_files
dependencies:
  enforced:
    module:
      - my_migrate

```

Here is my user migration plugin:

```
class Users extends Nodes {

  /**
   * {@inheritdoc}
   */
  public function query() {
    return $this->select('users', 'u')
      ->fields('u', array_keys($this->baseFields()))
      ->condition('uid', 0, '>');
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
    $fields = $this->baseFields();
    $fields['field_about/format'] = $this->t('Format of body');
    $fields['field_about/value'] = $this->t('Full text of body');
    $fields['field_about/summary'] = $this->t('Summary of body');
    $fields['field_first_name'] = $this->t('First Name textfield');
    $fields['field_last_name'] = $this->t('Last Name textfield');

    return $fields;
  }

  /**
   * {@inheritdoc}
   */
  public function getIds() {
    return [
      'uid' => [
        'type' => 'integer',
        'alias' => 'u',
      ],
    ];
  }

  /**
   * Returns the user base fields to be migrated.
   *
   * @return array
   *   Associative array having field name as key and description as value.
   */
  protected function baseFields() {
    return [
      'uid' => $this->t('User ID'),
      'name' => $this->t('Username'),
      'pass' => $this->t('Password'),
      'mail' => $this->t('Email address'),
      'created' => $this->t('Registered timestamp'),
      'access' => $this->t('Last access timestamp'),
      'login' => $this->t('Last login timestamp'),
      'status' => $this->t('Status'),
      'language' => $this->t('Language'),
      'picture' => $this->t('Picture'),
      'init' => $this->t('Init'),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    $uid = $row->getSourceProperty('uid');
    $profile_nid = $this->getProfileData($uid);

    $row->setSourceProperty(
      'body_value',
      $this->getFieldValue($profile_nid, 'field_data_body', 'body_value')
    );
    $row->setSourceProperty(
      'body_summary',
      $this->getFieldValue($profile_nid, 'field_data_body', 'body_summary')
    );

    $row->setSourceProperty(
      'field_first_name_value',
      $this->getFieldValue($profile_nid, 'field_data_field_first_name', 'field_first_name_value')
    );

    $row->setSourceProperty(
      'field_last_name_value',
      $this->getFieldValue($profile_nid, 'field_data_field_last_name', 'field_last_name_value')
    );

    return parent::prepareRow($row);
  }

  /**
   * Gets the profile data node in Drupal 7 associated with a User account.
   *
   * @param int $uid
   *   Drupal user Id.
   *
   * @return int
   *   Team Member node Id.
   */
  private function getProfileData($uid) {
    return $this->select('field_data_field_drupal_user', 'fdp')
      ->fields('fdp', ['entity_id'])
      ->condition('field_drupal_user_target_id', $uid)
      ->execute()
      ->fetchField();
  }

}

```

# Answer
The problem was the 'langocde' map in the config. The Drupal 7 langcode did not match the Drupal 8 langcode format.

When I set a default value for langcode in the migration config the fields showed as normal.

```
  langcode:
    plugin: default_value
    default_value: en

```
> 1 votes

---
Tags: 8, users, entities, migrations
---


title: blocks are null on admin theme

text:
# Question
Title: blocks are null on admin theme
I made a sub-theme of the admin theme "Seven" and called it Seven2 Because I wanted to customize the node-edit-form.twig.html file. That works.

My next step, I want to add a block I made in a custom module, to that node-edit-form.twig.html. There are several ways of doing that, and one I chose is preprocess page (or node for that matter), where I want to load my block.

The preprocess functions can either be in Seven2 .theme file or the custommodule.module file.

When I execute:

```
$block = \Drupal\block\Entity\Block::load('checkmark_block');

```

The $block is NULL when I do kint($block). Its like it can't find the damned block!! I have spent like 4 hours trying to make this thing work, in different ways, but no matter what, I can't load that block in my preprocess function. I don't know why but I think it's because it's an admin theme? Or... please help.

One of the blocks located in custommodule/src/Plugin/Block:

```
<?php
namespace Drupal\custommodule\Plugin\Block;
use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'CheckMark' Block.
 *
 * @Block(
 *   id = "checkmark_block",
 *   admin_label = @Translation("CheckMark block"),
 *   category = @Translation("CheckMarks"),
 * )
 */
class CheckMark extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $markup = 'Test test';

    $build = array(
      '#type' => 'markup',
      '#markup' => $markup,
      '#cache' => array('max-age' => 0),
    );

    return $build;
  }

}

```

# Answer
> 0 votes
Ok, I made it work by the answer from this post: How can I programmatically display a block?

And rendered it by adding this in hook\_form\_alter:

```
if ($form_id == 'node_article_edit_form') {
  ... code from the other post here ...
  $block = $plugin_block->build();
  $form['checkmark_block'] = $block;
}

```

And then in the twig file:

```
{{ form.checkmark_block }}

```

I find it way to difficult for a small task like this, and annoying to spend so much time on it, but one hopefully learns by it.

---
Tags: 8, blocks, theming
---


# Question
Title: How to create an editable table (by users) from Webform submission data?
I'm using D7 and creating a system to manage information about a specific game's characters. I have been advised to use webforms to collect the data from the character's, and I want the user that fills out those webforms be able to edit the data, just like they would on an Excel table.

I've been looking and looking and haven't been able to find an answer to how to get it done.

Any help?

# Answer
You could use Editable Views

Drupal Editable Views demo
> 1 votes

# Answer
You could use Editable Fields

How To Edit Fields On Node's Display And Within Views (Drupal Tutorial)
> 1 votes

---
Tags: users, webforms
---


# Question
Title: Use a twig variable inside a twig render
I am rendering a node field (which is an url to an image) in the node template file like bellow

```
<section class="bg" style="background-image: url({{ file_url(node.field_picture_bg.entity.fileuri) }});">

```

Works as its supposed to, but i have some logic which tests which exact image field to render and i would like to render the field name from a variable, like so bellow (WHICH DOESNT WORK obviously :) ).

```
<section class="bg" style="background-image: url({{ file_url(node.MYVARIBLE.entity.fileuri) }});">

```

Where `MYVARIBLE` is the name of the field. Is this even possible in twig? I know i can archive this with an conditional clause since there are only 2 possibilities for the field name, but this way is more

# Answer
> 2 votes
You can use the variable inside of the method get():

```
{{ node.get(MYVARIBLE).entity.fileuri }}

```

---
Tags: theming, entities
---


# Question
Title: Pass user_register form field values to Pardot for extra processing
I need to pass the values submitted during registration to Pardot using a form handler.

How can I accomplish the task?

# Answer
First you'd want to add an additional submit handler to your form...

```
function pardotpost_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'your_form_id_goes_here') {
    $form['#submit'][] = 'send_to_pardot';
  }
}

```

Then in your new submit handler you post the data to their form handler

```
function send_to_pardot(&$form, &$form_state) {
  $url = 'http://pardot.com/your/form/handler/url/goes/here';
  $data = $form_state['values']['submitted_tree'];
  $options = array(
    'method' => 'POST',
    'data' => http_build_query($data, '', '&'),
    'timeout' => 15,
    'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
  );
  $result = drupal_http_request($url, $options);
}

```

Lastly you check $result for any errors. Cheers
> 3 votes

# Answer
Add an additional submit callback to the form.
> 1 votes

# Answer
I have developed a module for this Pardot User Register

Advantage of using this module over adding additional submit callback is site builders / users can easily add the form handler URL in the Drupal admin interface. No coding work involved and the users can check Watchdog for any errors generated from this integration.

Please feel free to create an issue on the project page if you find any. I would be more than happy to fix or enhance the module provided it is a generic bug or suggestion.
> 0 votes

---
Tags: forms, users
---


# Question
Title: How to change the order number in drupal commerce?
I want to change the order number to reflect the year-month-order-id. Is there any way to do that?

I tried the commerce\_order\_counter module, however the base counter resets to the one from the table every time a new order is placed. I also tried to alter the commerce\_order table from myPHPAdmin to change the auto increment value. This changed the order\_id but not the order\_number. I also tried to change the default value inside the table for order\_number but nothing happened. Finally, I tried to create a rule to update the order\_number after an order is placed in the cart, still no success. It seems like whatever value I add to this rule is overridden by some other rule.

What else can I try?

Thanks

# Answer
You can use hook\_commerce\_checkout\_complete that is called when the order is placed.

```
/**
 * Implements hook_commerce_checkout_complete().
 */
function MY_MODULE_commerce_checkout_complete($order) {
  // Create a customised order number. We do not need to save the order here, it
  // is done by the checkout module.
  $order->order_number = date('Y-m') . '-' . $order->order_id;
}

```
> 0 votes

---
Tags: commerce
---


# Question
Title: How do I show the publishing date instead of the creation date?
When I create an article and I don't publish it, so I could edit the article later and publish it when it's finished, I notice Drupal shows the creation date, not the publishing date.

Is there a way to change it so the items on the front page show their publishing date and not the creation date? Is there a different field in the database for that functionality?

I am using the Workbench module, which gives draft nodes. If nodes are not published, it will display them in a draft list.

# Answer
> 0 votes
The Publication Date module adds a field on every node that shows when a node was published.

> The Publication Date module adds a "Published on" date for each node, containing the date when it was first published.
>
> Without this, the only dates available for nodes are their created date and changed date, but these are often insufficient to meet the needs of publishing workflows. Sorting nodes by their created date doesn't account for content which is held in draft form for a time while being readied for publication. Sorting nodes by their changed date fails to account for content needing minor corrections after being published.

For nodes published before the module was installed, the module will use the node creation date, as the project page itself says.

> For nodes that were published **before** the installation of this module, we can not know the exact date of publication, so `$node->published_at` will initially contain the creation date.

---
Tags: 7
---


title: How do I get file ID from node?

text:
# Question
Title: How do I get file ID from node?
How can I get file ID like I got, for instance, file URI:

```
$getFile = $entity->get('field_file')->entity->getFileUri();

```

I need it to send an email (swiftmailer)

```
$file_one = file_load(1);

```

# Answer
The file ID is the property `target_id` of the file field:

```
$fid = $entity->get('field_file')->target_id;

```
> 2 votes

# Answer
If you are having $file object then you can get id from

```
$fid = $file->id();

```

and for loading purpose you can use the following

```
\Drupal\file\Entity\File::load($fid);

```
> 0 votes

---
Tags: 8, files
---


# Question
Title: Bootstrap and require a method from a separate module
I have a script that runs outside of my module, which bootstraps Drupal.

```
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
use Drupal\smart_ip\SmartIp;

chdir('../..');

$autoloader = require_once 'autoload.php';

$request = Request::createFromGlobals();
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();

$ip = $request->getClientIP();

$location = SmartIp::query($ip);

```

My problem is that using the Smart IP query method (`SmartIp::query($ip)`) throws an error:

```
TypeError: Argument 1 passed to Drupal\Core\Session\SessionConfiguration::getOptions() must be an instance of Symfony\Component\HttpFoundation\Request, null given, called in /var/www/drupalvm/sitelog/core/lib/Drupal/Core/Session/SessionManager.php on line 111 in Drupal\Core\Session\SessionConfiguration->getOptions() (line 40 of /var/www/drupalvm/sitelog/core/lib/Drupal/Core/Session/SessionConfiguration.php)
#0 /var/www/drupalvm/sitelog/core/lib/Drupal/Core/Session/SessionManager.php(111): Drupal\Core\Session\SessionConfiguration->getOptions(NULL)
#1 /var/www/drupalvm/sitelog/vendor/symfony/http-foundation/Session/Storage/NativeSessionStorage.php(278): Drupal\Core\Session\SessionManager->start()
#2 /var/www/drupalvm/sitelog/vendor/symfony/http-foundation/Session/Session.php(87): Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage->getBag('attributes')
#3 /var/www/drupalvm/sitelog/modules/smart_ip/src/SmartIp.php(100): Symfony\Component\HttpFoundation\Session\Session->get('smart_ip')
#4 /var/www/drupalvm/sitelog/modules/smart_ip/src/SmartIpLocation.php(167): Drupal\smart_ip\SmartIp::getSession('smart_ip')
#5 /var/www/drupalvm/sitelog/modules/smart_ip/src/SmartIpLocation.php(133): Drupal\smart_ip\SmartIpLocation->getData(false)
#6 /var/www/drupalvm/sitelog/core/lib/Drupal/Component/DependencyInjection/Container.php(264): Drupal\smart_ip\SmartIpLocation->__construct()
#7 /var/www/drupalvm/sitelog/core/lib/Drupal/Component/DependencyInjection/Container.php(177): Drupal\Component\DependencyInjection\Container->createService(Array, 'smart_ip.smart_...')
#8 /var/www/drupalvm/sitelog/core/lib/Drupal/Component/DependencyInjection/Container.php(494): Drupal\Component\DependencyInjection\Container->get('smart_ip.smart_...', 1)
#9 /var/www/drupalvm/sitelog/core/lib/Drupal/Component/DependencyInjection/Container.php(236): Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters(Array)
#10 /var/www/drupalvm/sitelog/core/lib/Drupal/Component/DependencyInjection/Container.php(177): Drupal\Component\DependencyInjection\Container->createService(Array, 'smart_ip.get_lo...')
#11 /var/www/drupalvm/sitelog/core/lib/Drupal.php(158): Drupal\Component\DependencyInjection\Container->get('smart_ip.get_lo...')
#12 /var/www/drupalvm/sitelog/modules/smart_ip/src/SmartIp.php(36): Drupal::service('smart_ip.get_lo...')
#13 /var/www/drupalvm/sitelog/modules/sitelog/sitelog.php(23): Drupal\smart_ip\SmartIp::query('192.168.88.1')
#14 {main}.

```

I hoped that by putting `use Drupal\smart_ip\SmartIp;`, at the top of my script, I would have access to the module's methods, but I don't.

I don't understand what is required to make the Smart IP query function available to my script?

# Answer
> 1 votes
For this case you have to add one additional step to your bootstrap code.

Put `$kernel->preHandle($request);` right below the `$kernel->boot();`

---
Tags: 8
---


# Question
Title: Adding content to Paragraph Date Field Drupal 8
I'm programmatically creating paragraphs using the following code, but I'm unable to get the date value to store correctly within the date field. It seems to store within the database, yet on the edit page/form for the node, it remains as a blank field.

Any suggestions or insight would be appreciated.

```
//SET THE DATE
$date = new DrupalDateTime('2017-10-24 13:30:00');

//CREATE THE NEW PARAGRAPH
$paragraph = Paragraph::create([
    'type' => 'event_venue',
    'field_tickets' => [
        ["value"  =>  'Adult Update 1|£30'],
        ["value"  =>  'Adult Update 2|£130']
        ],
    'field_date' => array($date->format('Y-m-d H:i:s')),

]);

//SAVE THE PARAGRAPH SO WE CAN ADD THE ENTITY ID TO THE NODE
$paragraph->save();

//LOAD THE NODE
$node = entity_load('node', $nid);

//ADD PARAGRAPH TO THE NODE
$node->field_dates = array(
    array(
      'target_id' => $venue_information->id(),
      'target_revision_id' => $venue_information->getRevisionId(),
    )
);

//SAVE THE NODE
$nid = $node->save();

```

# Answer
Use the global constant DATETIME\_DATETIME\_STORAGE\_FORMAT to format the date:

```
// If the time is in a different timezone then adjust it to UTC before you save it
$date->setTimezone(new \DateTimezone(DATETIME_STORAGE_TIMEZONE));

$paragraph = Paragraph::create([
  ...
  'field_date' => [
    'value' => $date->format(DATETIME_DATETIME_STORAGE_FORMAT),
  ],
]);

```

**Edit**

For Drupal \>= 8.5: Global constants in datetime.module are deprecated and DateTimeItemInterface has been introduced.
> 1 votes

---
Tags: 8, entities, datetime, paragraphs
---


# Question
Title: Exposed filter - based on first three number in Zipcode?
I have been using Basic Exposed Filter for filtering the zipcode(Number) field.

Now, I want to filter based on the first three number, though the 5 digits number is entered.

How do I achieve this ?

# Answer
Please check this link

Is has an example how to implement query alter having exposed filters.

```
function hook_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  // (Example assuming a view with an exposed filter on node title.)
  // If the input for the title filter is a positive integer, filter against
  // node ID instead of node title.
  if ($view->id() == 'my_view' && is_numeric($view->exposed_raw_input['title']) && $view->exposed_raw_input['title'] > 0) {
    // Traverse through the 'where' part of the query.
    foreach ($query->where as &$condition_group) {
      foreach ($condition_group['conditions'] as &$condition) {
        // If this is the part of the query filtering on title, chang the
        // condition to filter on node ID.
        if ($condition['field'] == 'node.title') {
          $condition = array(
            'field' => 'node.nid',
            'value' => $view->exposed_raw_input['title'],
            'operator' => '=',
          );
        }
      }
    }
  }
}

```
> 0 votes

---
Tags: 8, views
---


# Question
Title: How can I raise the maximum upload file size?
I set up private file directory at /var/www/private to keep upload files from webform and setup permission on directory and files (664 for files, 775 for directories). When I click on upload button and select file, it throw an exception -
**"An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (32 MB) that this server supports."**

Solution is running on Drupal 8.3 on VM (Vagrant). Below is screen capture of error message

Appreciate if you have an answer of this bug

# Answer
> 0 votes
This is not particular to the Drupal site but is caused by the hosting (local Vagrant) environment's PHP configuration.

Try increasing these values in php.ini:

```
upload_max_filesize = 64M
post_max_size = 64M
memory_limit = 64M

```

**NOTE**: If you are using Webform for anonymous file upload to your site and you are setting high limits on file size like this you are quickly going to fill up a lot of disk space (most likely with spam).

**NOTE**: After modifying php.ini file(s), you need to restart your HTTP server to use new configuration

See answer on Stackoverflow.

---
Tags: 8, webforms
---


# Question
Title: Checking for custom view mode inside twig template!
I am using {% if teaser %} .... {% endif %} To change structure of content type according to its view mode.

But it looks like I cannot check for custom view modes created using Drupal 8, Such as:

```
{% if medium_teaser %}
  <div id="product-teaser">
     {{ content.field_image }}
     <a class="buy-now-btn" href="{{ path('entity.node.canonical', {'node':
     node.id}) }}">Buy now</a>
  </div>
{% endif %}

```

Is there a way to check for custom view modes in twig templates?

# Answer
> 4 votes
Assuming that's the node template, you have a `view_mode` variable available:

```
{% if view_mode == 'foo' %}

{% endif %}

```

---
Tags: theming, 8
---