# Question
Title: White screen of death: Fatal error: Allowed memory size of X bytes exhausted
I have a issue with my Drupal installation, for example:

* when I enable or disable the modules, It redirects me to a blank page,
* when I create a new content type and save it, redirects me to a blank page,
* when I add a new view and save it, it redirects me to a blank page,
* when I try to clear the cache, it redirects me back to a blank page,
* or in similar cases.

Basically all the confirmation pages redirect me to a white screen. When I refresh it again, it shows me the page. I tried to increase the PHP memory value but it doesn't help.

Are there any other solutions for this?

The error which I'm having:

> **Fatal error: Allowed memory size of 100663296 bytes exhausted (tried to allocate 8192 bytes) in sites/all/modules/views/plugins/views\_plugin\_localization\_none.inc on line 1**

# Answer
> 20 votes
I know this may be late, but it helped me. Most times a module causes WSOD, I couldn't just disable modules to test which it was, since I may have lost data in the process. What I did was to temporarily edit this function in `module.inc`, in the core `includes` directory

```
function module_invoke_all($hook) {
  $args = func_get_args();
  // Remove $hook from the arguments.
  unset($args[0]);
  $return = array();
  foreach (module_implements($hook) as $module) {

        print "Starting loading $module <br />";

        $function = $module . '_' . $hook;
        if (function_exists($function)) {
          $result = call_user_func_array($function, $args);
          if (isset($result) && is_array($result)) {
            $return = array_merge_recursive($return, $result);
          }
          elseif (isset($result)) {
            $return[] = $result;
          }
        }

        print "Finished loading $module <br />";

  }

  return $return;
}

```

And I added those 2 print statements in the code above, then refresh the page, the module which didn't reach the "Finish loading $module" statement is the one with the problem... it was devel in my case.

After finding the module, you can go into the system table and look for that module, set it's status = 0 and bootstrap = 0 or run the query:

```
UPDATE system SET status = 0, bootstrap = 0 WHERE name = 'module_name' LIMIT 1

```

Reference: Debugging Drupal White Screen of Death (WSOD)

# Answer
> 12 votes
Paste this code in your `index.php` file. It will show you the error message instead of blank page. At least the root of the problem can be known. Paste it right after php tag.

```
    error_reporting(E_ALL);
    ini_set('display_errors', TRUE);
    ini_set('display_startup_errors', TRUE);

```

Hope it will show you the way!.

http://drupal.org/node/158043

# Answer
> 11 votes
Reason of blank white screen of death is the error reporting turned off, to check the error add the following lines in your setting.php file:

```
error_reporting(E_ALL);
$conf['error_level'] = 2;
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```

For the error you are facing("Allowed memory size of XXX bytes exhausted"), you can try the following things:

1. Truncate the cache manually and check if it fixes the problem ( It is probably be a good to backup your DB before doing that):

`Access phpMyAdmin and truncate all tables starting by cache_ from the database`.
2. Increase the memory limit (as the main reason of the above error is the memory exhausted by the server which caused the partial loading of the modules and that is causing the problem) by adding the following line in your settings.php file: `ini_set('memory_limit', '-1');`
Adding `ini_set('memory_limit', '-1');` overrides the default PHP memory limit.
If you want to restrict the memory than instead of `-1` you can provide memory size like '256M' OR '512M'.

# Answer
> 9 votes
The error:

> Fatal error: Allowed memory size of X bytes exhausted (tried to allocate Y bytes)

To convert bytes X into MB, divide by 1024\*1024 or check at Wolfram.

happens when PHP tries to allocate Y bytes, but there is hard limit on X bytes set by PHP `memory_limit` configuration settings.

The current limit can be checked by going to *Administration » Reports » Status report » PHP* (URL: `/admin/reports/status/php`) or by printing `ini_get('memory_limit')` in PHP (note that limit be different for UI and CLI).

In order to fix it, you need to lower your resource usage, for example:

* disable any development modules which you're not using currently (recommended),

This includes: Devel, Devel Themer (if enabled).
* disable any modules which you're not using,
* disable certain debug variables which can impact on your memory resources, e.g. few examples with `drush`:

```
drush -y vset rules_debug 0
drush -y vset rules_debug_log 0

```
* disable certain PHP extensions, such as XDebug,
* enable redis/memcached caches and some PHP caches (e.g. OPCache/XCache),
* finally if above won't help - **increase `memory_limit` in your PHP configuration**.

If you decide on increasing memory limit, a lot of people here advising to actually hack your core by pasting the PHP code into your `index.php` to increase your PHP memory - never do that! It's a very bad practise.

Instead edit your `settings.php` (or `settings.local.php` if you have it included) and paste the following code there at the end:

```
ini_set('memory_limit', '512M');

```

or a better way of doing this is to edit your PHP config file (`php.ini`) and changing the following line:

```
memory_limit = 512M  ; Maximum amount of memory a script may consume

```

If you're not sure where is your `php.ini`, check by:

* `drush status` command
* or by going at `/admin/reports/status/php`.

To investigate further which pages/components are using the most memory, you've the following possibilities:

For further information, check:

# Answer
> 7 votes
It could very well be that one of your modules is running out of memory.

You can add one line of code to your index.php file to allow Drupal to run with more memory than the default setting:

```
ini_set('memory_limit','256M');

```

Add the above code on the line after the ?php in your /drupal/index.php file. If everything starts working fine, then you can identify what is causing the memory problem (highly likely it's a module).

Disable a module, and then comment out the ini\_set('memory\_limit','256M'); and see if it loads now.

It is not recommended to leave the ini\_set('memory\_limit','256M'); in place as a solution, but it can at least allow you to get to your module listing page.

You may find it helpful to do a debug\_backtrace() to determine what was using the memory.

# Answer
> 2 votes
You can use a module to control this memory limit. PHP Runtime Configurator module provides many options to configure without changing your php.ini file and restart Apache.

You can configure following parameters:

*** File Upload Limit
* Memory Limit
* Maximum Execution Time Limit
* Maximum Input Variable Limit**

---
Tags: 7, wsod
---


# Question
Title: What conditions may cause "The content on this page has either been modified by another user..."?
I'm working on a website which has multiple admins, some creating contents, some editing and some tagging...

I know editing one node at the same time will cause this error, is there anything else cause this error?

> The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved.

# Answer
Another cause might me the fact that you save a form, then hit the back button and try to save it again
> 2 votes

# Answer
I just managed to create this error with a FireFox setting. I told FF never to save history and cleared my browser cache and then could not submit changes to nodes. When I turned 'save history' back on, the issue resolved. Probably related to a change in how FF was handling cookies.

Site is Drupal 7 with OpenPublish, IDK much more than that as I'm new to the project.
> 1 votes

# Answer
If the problem is related to two users editing the same record (node), it can be related to max\_input\_vars in your php.ini

There are two solutions to solve the problem (I recommend trying both of them):

1. Edit phpi.ini and increase max\_input\_vars (find max\_input\_vars = ... and increase it). php.ini can be found in different locations for example in an ubuntu conventional setup it can be at /etc/php5/apache2/php.ini
2. Clear cache (depend on your browser this is a pretty easy routine and you already do not know it, just google it).

Check https://www.drupal.org/node/1933120
> 1 votes

# Answer
I got this error across my entire site and I'm not sure of the root cause.

If I edited and saved a page and then clicked the edit tab to edit the page and tried to save again, I would get the error.

I was banging my head against the wall trying to fix it until I fixed it by rebuilding the site permissions: admin/reports/status/rebuild

Another solution that others pointed to was to increase the max\_input\_vars in your php.ini file.
> 0 votes

# Answer
It may be due to Maximum Input Variable Limit. You can use a module to control it. PHP Runtime Configurator module provides many options to configure without changing your php.ini file and restart Apache.

You can configure following parameters:

*** File Upload Limit
* Memory Limit
* Maximum Execution Time Limit
* Maximum Input Variable Limit**
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Varnish 4.0 - Drupal says it is working successfully but it isn't in my headers
I have a very basic Varnish setup:

```
backend default {
    .host = "127.0.0.1";
    .port = "8080";
}

```

And that's about it.

I have the Varnish module installed as well with the standard defaults and flush cache on cron.

However when I try to find X-Varnish: HIT, I find absolutely nothing in my header.

Here's my header:

```
HTTP/1.1 200 OK
Date:   Wed, 08 Nov 2017 23:22:00 GMT
Server: Apache
X-Drupal-Cache: HIT
Content-Language:   en
X-Frame-Options:    SAMEORIGIN
X-UA-Compatible:    IE=edge
X-Generator:    Drupal 7 (http://drupal.org)
Link:   <http://ifollosports.com/>; rel="canonical",<http://ifollosports.com/>; rel="shortlink"
Cache-Control:  public, max-age=86400
Expires:    Sun, 19 Nov 1978 05:00:00 GMT
Vary:   Cookie,Accept-Encoding
Content-Encoding:   gzip
Set-Cookie: bb2_screener_=1510183320+147.75.99.51; path=/
Etag:   "1510183079-1"
Last-Modified:  Wed, 08 Nov 2017 23:17:59 GMT
Content-Type:   text/html; charset=utf-8

```

What would be causing Varnish to not work? Is there some other configuration setting that Drupal needs? I want to be very clear - the module is reporting that Varnish IS working.

I am going based off this link:

https://www.cloudways.com/blog/install-varnish-on-drupal-7/

# Answer
> 1 votes
`Set-Cookie: bb2_screener_=1510183320+147.75.99.51; path=/`

Varnish will not save a page to the cache if there is a `Set-Cookie` header on the response.

---
Tags: proxies, caching
---


# Question
Title: How to create a rule to perform a redirect if user is already logged in and visits the homepage?
I have a Drupal 7 installation. In my homepage I have only two forms (login and register) so I need when someone leaves the site and the user is logged in, when he visits it again that he redirect to another page (similar to Facebook functionality).

Currently the user is redirected to user profile page.

I tried to use Rules and I put in Rules Event 'Drupal is initializing', in Rules Condition path to 'check=\[site:url\]' to be redirected but with no effect.

Any ideas?

# Answer
Not sure if it will be your only problem to be fixed, but you seem to be using the wrong token in your condition path. Try again using either of these tokens:

* `[site:current-page:path]`.
* `[site:current-page:url]`.

Below is an example of a rule (in Rules Export format) which illustrates how to use either of these tokens:

```
{ "rules_redirect_logged_in_user" : {
    "LABEL" : "Redirect logged in user",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      },
      { "OR" : [
          { "data_is" : { "data" : [ "site:current-page:path" ], "value" : "node\/123" } },
          { "text_matches" : { "text" : [ "site:current-page:url" ], "match" : "something" } }
        ]
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Using the path [site:current-page:path] (or url [site:current-page:url]) makes no sense for authenticated users, which is why you are redirected ..." } },
      { "redirect" : { "url" : "somewhere_else" } }
    ]
  }
}

```

Some more details about the above Rule:

* Rules Event: Drupal is initializing.
* Rules Conditions:
    + the user should NOT be anonymous, AND
    + either (or both) of these conditions must be true:
    + the **path** is `node/123` (assuming your homepage is a node with `nid=8`, adapt to fit your case, or omit this condition if the next condition is sufficient for your case).
    + the **url** `contains` the text `something` (adapt to fit your case, or omit this condition if the previous condition is sufficient for your case). Instead of using Comparison operation `contains` you could also use `starts with`, `ends with` or even a `regular expression`.
* Rules Actions:
    + Show an appropriate message (adapt to fit your needs, or just omit it if you don't want such message at all, I like it for debugging purposes ...).
    + Perform a redirect to `somewhere_else` (adapt to fit your needs).

If you have the Rules UI enabled, you should be able to import the above rule in your own site. Then adapt it to fits your needs and you should be good to go.

***Easy, no?***
> 1 votes

---
Tags: 7, users, rules, redirection
---


title: Migrate multi-value paragraph field

text:
# Question
Title: Migrate multi-value paragraph field
I'm doing a D7 to D8 custom migration. In Drupal 7, I have a multi-value formatted text field that I am trying to map to a Drupal 8 multi-value Paragraph entity reference field.

I've separated this into two migrations. One for the paragraphs, and one for the nodes themselves. I've got the multi-value field to paragraph migration working (although I think there might be an issue with the way that I have done the IDs). I have the node migration working as well, with the exception that none of the references to the already migrated paragraph entities are being migrated.

I realize that right now, this seems unnecessary, but it's part of a feature upgrade.

Below is the code from my migration classes/plugins.

This is from `migrate_plus.migration.presentation_node.yml`. Field\_slide is the paragraph reference field.

```
'field_slide/target_id':
  plugin: migration
  migration: presentation_slide
  source: entity_id

```

This is the getIds function from `PresentationSlide.php`. This is the plugin for the paragraph migration.

```
public function getIds() {
  return [
    'entity_id' => [
      'type' => 'integer',
      'alias' => 'lt',
    ],
  ];
}

```

This is also from `PresentationSlide.php`. Here I am combining the entity\_id and delta to form a unique id. I realize that this is a terrible way to do this, but I couldn't figure out anything better. Any tips on this are welcome.

```
public function prepareRow(Row $row) {
  $nid = $row->getSourceProperty('entity_id');
  $delta = $row->getSourceProperty('delta');
  $slide_id = (string) $nid . (string) $delta;
  $slide_id = (int) $slide_id;
  $row->setSourceProperty('entity_id', $slide_id);

  return parent::prepareRow($row);
}

```

And this is from `PresentationNode.php`. Here I am fetching all of the referenced fields, and passing that as an array to the migration class.

```
public function prepareRow(Row $row) {
  $nid = $row->getSourceProperty('nid');
  $query = $this->select('field_data_field_learning_text', 'lt')
    ->condition('entity_id', $nid);
  $query->addExpression('CONCAT(entity_id, delta)', 'target_id');

  $slides = $query->execute()->fetchCol();

  if (!empty($slides)) {
    $row->setSourceProperty('entity_id', $slides);
  }

  return parent::prepareRow($row);
}

```

The main issue here is that I can't figure out how to properly use a multiple column key. It seems to me that all of my issues are due to my doing this improperly.

Thanks in advance. I realize this is a lot.

**\[Edit\]**

Thanks Berdir for the help. I've taken a stab at implementing your processing plugin. However, I'm having an issue where the migration seems to be skipping right over and ignoring the process plugin.

```
field_slide:
  plugin: paragraph_process_base
  source: field_body_value

```

Feel like there is something super simple that I'm missing here.

**\[Edit 2\]** And I had a typo... Thanks a ton!

# Answer
> 4 votes
This is not directly an answer, but it is also too long for a comment :)

When I migrated something that wasn't actually paragraphs into paragraphs, I just wrote a custom process plugin that created paragraphs on the fly, then I didn't have to bother about trying to figure out some kind of mapping/made up ID's. What you're doing definitely seems like a bad idea, as 1010 could either be delta 10 from node 10 or delta 0 from node 101.

Put two classes I used for that into a gist: https://gist.github.com/Berdir/8a650a29a670fe283589f8946354086c.

It is both a bit hacky and a fairly complicated as I needed to support importing multiple translations for separate nodes in 6.x to a single node with a single paragraph with translations in 8.x.

Also created a to-do for me to write a blog post about this. ;)

# Answer
> 0 votes
Related blog post: https://deninet.com/blog/2017/06/18/building-custom-migration-drupal-8-part-5-paragraphs

> There is a very popular post on Stack Overflow that suggests you write a custom process plugin. While this method can work, it's no longer recommended for Entity Reference Revisions 1.2 or higher.

Drupal.org handbook page would be really useful now..

---
Tags: 8, migrations
---


title: Custom registration twig template

text:
# Question
Title: Custom registration twig template
What would be the best way to make a custom registration twig template ?

I have implemented the hook :

```
function THEMENAME_theme_suggestions_form_alter(array &$suggestions, array $variables) {
    $suggestions[] = 'form__' . $variables['element']['#form_id'];
}

```

Si I get form twig template suggestions such as form--user-register-form.html.twig

Then I can call every value I want using "element" :

```
{{ element.field_name }}

```

My only problem is that I'm facing error with fields validation with ajax i.e for the picture field, when uploading a picture I got an error message that the picture size overpass the php limitsize from the server (which is obviously not the case).

So I have to call `{{ children }}`in my twig template to get it working properly. The only bad point is that calling {{ children }} actually call the whole form ......

Am I doing something wrong ? Is it the best way to accomplish stuff above ? Is it `{{ children }}` that I have to call to get the form working ?

# Answer
> 4 votes
**For simple forms ...**

... you can theme a `form` template by using `{{ element }}` instead of `{{ children }}`, see How to Create twig template files in drupal 8 for customizing user login,profile edit and forget password forms?.

But this is not always the best approach, because it's difficult to include all form elements and metadata the form needs to operate.

**For complex forms ...**

... it might be easier to add an additional template level, which only has to render the inner form elements, not the complete form:

```
/**
 * Implements hook_form_FORM_ID_alter() for \Drupal\user\RegisterForm.
 */
function mytheme_form_user_register_form_alter(&$form, FormStateInterface $form_state) {
  $form['#theme'] = 'user_register_form';
}

```

The custom template needs to be registered in `hook_theme`. See How to render specific form elements from the \*.theme file for a step-by-step example.

---
Tags: theming, 8, forms, users
---


# Question
Title: What do I add to template.php so I can render regions in a page created in hook_menu()?
I need to recreate a lot of pages after removing Panels from a site.

In order to print regions in node tpls, I added this to `theme_preprocess_node`. That's fine but it doesn't work for custom pages.

```
// Get a list of all the regions for this theme
  foreach (system_region_list($GLOBALS['theme']) as $region_key => $region_name) {

    // Get the content for each region and add it to the $region variable
    if ($blocks = block_get_blocks_by_region($region_key)) {
      $variables['region'][$region_key] = $blocks;
    }
    else {
      $variables['region'][$region_key] = array();
    }
  }

```

I tried adding that to `theme_preprocess_page` but it doesn't do anything.

Here is my module. The divs print fine but the regions don't get printed.

```
function custom_pages_menu() {

    $items['classes-admin/%'] = array(
        'title' => t('Classes'),
        'page callback' => 'page_sidebars',
        'access arguments' => array('edit field_diary_date'),
    );
    return $items;
}

function page_sidebars() {
    $page_return = "";
    $page_return .= '<div class="container-fluid">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="panel-pane">';
    $page_return .=                     render($region['sidebar_left']); // or $page
    $page_return .=             '</div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="panel-pane">';
    $page_return .=                     render($region['sidebar_right']); // or $page
    $page_return .=                 '</div>
                                   </div>
                                </div>
                            </div>';

    return $page_return;
}

```

This seems like a pretty common thing to do but google isn't giving me anything to work with. I don't want to add them to page.tpl because it's a very complex site and I only want it this way, if possible. Any help appreciated.

# Answer
Well, replace this line

```
render($region['sidebar_left']);

```

with

```
render(block_get_blocks_by_region('sidebar_left'));

```

and replace this line

```
render($region['sidebar_right']);

```

with

```
render(block_get_blocks_by_region('sidebar_right'));

```

hope it will work for your case :)
> 1 votes

---
Tags: 7, theming
---


# Question
Title: Client Side Validation for a views exposed filter in ajax mode
I tried this using bootstrap theme Create a view for a content type Add an exposed filter using one of the fields of that particular content type Make the filter field as required Now on visiting the view page, the exposed filter rendered as a textbox with an outer red border, which normally should appear after hitting the submit button of the filter. Someone help me explain this behavior. Secondly edit the same view, click on the filter field and uncheck the required checkbox. Then Under Advanced, Enable use Ajax to make the filter work in ajax mode. Now if i try to write a client side validation for the filter textbox using jquery( say i check for an empty and return an error msg div or even return false, it is being ignored) and all the results are displayed.

Any suggestions are welcome. I'm not making any errors in my validation script if needed i can post the script too.

# Answer
```
     $('.catalog-submit').on('click', function() {
  var textVal = $(".catalog-search").val();
  if(textVal == "") {
    $(".catalog-search").css('border-color', 'red');
    $(".err-msg").remove();
    $(".catalog-submit").append("<p class='err-msg'>Please Enter your City and State, or Zip Code</p>");
    return false;
  }
});

```

The above code by default should append the err-msg div and return nothing. However this code appends the err-msg and returns every single result. I mean the return false has no effect. A simple return also did the same. And this is the js I have used for my case.
> 0 votes

---
Tags: views, bootstrap-theme
---


# Question
Title: Problem updating from Drupal Core 8.3.7 to 8.4.0 with composer
I am having trouble updating from Drupal 8.3.7.

When running `composer why-not drupal/core 8.4.0` I get the following results:

```
drupal/core 8.4.0 requires symfony/class-loader (~3.2.8)
andeersg/bouvet-d8-project dev-Stinis does not require symfony/class-loader (but v2.8.28 is installed)
drupal/core 8.4.0 requires symfony/console (~3.2.8)
andeersg/bouvet-d8-project dev-Stinis does not require symfony/console (but v2.8.28 is installed)
drupal/core 8.4.0 requires symfony/dependency-injection (~3.2.8)
andeersg/bouvet-d8-project dev-Stinis does not require symfony/dependency-injection (but v2.8.28 is installed)
drupal/core 8.4.0 requires symfony/event-dispatcher (~3.2.8)
andeersg/bouvet-d8-project dev-Stinis does not require symfony/event-dispatcher (but v2.8.28 is installed)
drupal/core 8.4.0 requires symfony/http-foundation (~3.2.8)
andeersg/bouvet-d8-project dev-Stinis does not require symfony/http-foundation (but v2.8.28 is installed)
drupal/core 8.4.0 requires symfony/http-kernel (~3.2.8)
andeersg/bouvet-d8-project dev-Stinis does not require symfony/http-kernel (but v2.8.28 is installed)
drupal/core 8.4.0 requires symfony/process (~3.2.8)
andeersg/bouvet-d8-project dev-Stinis does not require symfony/process (but v2.8.28 is installed)
drupal/core 8.4.0 requires symfony/routing (~3.2.8)
andeersg/bouvet-d8-project dev-Stinis does not require symfony/routing (but v2.8.28 is installed)
drupal/core 8.4.0 requires symfony/serializer (~3.2.8)
andeersg/bouvet-d8-project dev-Stinis does not require symfony/serializer (but v2.8.28 is installed)
drupal/core 8.4.0 requires symfony/translation (~3.2.8)
andeersg/bouvet-d8-project dev-Stinis does not require symfony/translation (but v2.8.28 is installed)
drupal/core 8.4.0 requires symfony/validator (~3.2.8)
andeersg/bouvet-d8-project dev-Stinis does not require symfony/validator (but v2.8.28 is installed)
drupal/core 8.4.0 requires symfony/yaml (~3.2.8)
andeersg/bouvet-d8-project dev-Stinis does not require symfony/yaml (but v2.8.28 is installed)

```

Trying to update one of the mentioned packages just results in composer telling me I can't because Drupal 8.3.7 needs a lower version. So I can't update the packages and I can't update Drupal. Am I stuck in a catch22?

Does anybody know what the problem might be? When I run `composer update drupal/core --with-dependencies` it says that everything is up to date even though it is still at 8.3.7.

# Answer
I had the same issue and here is what worked for me

**Requirement :** PHP 7.1
**Explanation :**
1. Doctrire, a dependancy of Drupal core, requires PHP 7.1. Doctrine uses the latest PHP 7.1 syntax to declare the methods' return type eg. `function my_function() : void {...}`. There is a core bug concerning this issue with status "Needs work". Even if this bug is patched, 8.4 requires PHP 7.
2. webflo breaks the chain of dependencies
3. Drupal 8.4 requires Drush 9.0

If you have PHP 7.1 on your server you can do the following:

1. edit the `composer.json` file: `"drupal/core": "~8.4"` and `"drush/drush": "~9.0"`
2. delete `composer.lock`
3. delete `vendor`
4. update webflo: `composer require "webflo/drupal-finder ~1.0.0"`
5. update the database: `../vendor/bin/drush updb -y`
6. update the entities schemas: `../vendor/bin/drush entup -y`

Applied on three different production servers (Linux + Apache) and on local environments (macOS + Apach, Ubuntu + Apache). Not tested with Vagrant.

The two entity updates are concerning "*paragraph entity type*" : (1) The Published field needs to be updated. (2) The Behavior settings field needs to be updated.
> 3 votes

# Answer
Try something like this:

`composer require drupal/core:^8.4.0 drush/drush:^8.1.15 drupal/console:^1.0 --update-with-dependencies`

Also: Drupal 8.4 requires drush newer than 8.1.12 or so, not 9.0. Some people have reported issues with drush 9 in some environments YMMV.
> 1 votes

---
Tags: updating, composer
---


# Question
Title: Drupal Commerce 2 Promote Product to Front Page
I am using drupal commerce 2 to create an ecommerce website. Need to promote some products to front page but there is no option in product types to promote the product to front page. In Drupal Commerce 1 we use to reference the product in product display node and that can be easily promoted to front page. Is there any different method to do that ?

# Answer
> 1 votes
"Promoted to front page" is an archaism from the early days of Drupal, so it wasn't transferred into Commerce. Nowadays you can create any number of fields, and filter on them:

1) Go to your product type. 2) Create your own boolean field called "Promoted to front page" 3) Use it from your View.

---
Tags: 8, commerce
---


# Question
Title: Adding CSS to specific nodes doesn't work
I'm new to Drupal 8 themes and am trying to edit CSS on individual pages. I've read how to do it, and have attempted to implement, but when I clear my sites cache and try to view the page, the new CSS (or JS on some pages) does not seem to get utilized.

### What I have done

1. In my .theme file I have this code

```
function odyssey_preprocess_node(&$variables) {
  // find node object
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node) { //ensure object is a node
    if ($node->id() == 1 ) { //grab specific node (R&D page)
      //attach the library
      $variables['#attached']['library'][] = 'odyssey/research-devel';
    }
    elseif ($node->id() == 3 ) {//CR Calc node
      $variables['#attached']['library'][] = 'odyssey/cr-calc';
    }
  }
}

```
2. In my .libraries.yml file I have the following code

```
research-devel:
  css:
    theme:
      css/research-devel.css: {}

cr-calc:
  css:
    theme:
      css/cr-calc.css: {}
  js:
    js/cr-calc.js: {}
  dependencies:
    - core/jquery

```
3. I uploaded the named files from .libraries.yml into the appropriate folders (I have my global CSS and JS files working, so I know the locations are correct.)

Does anyone see any glaring errors? Am I going about this the wrong way? Like I said, fairly new to the game and I'm sure that adding specific page stylings to the global CSS is the "Non-Drupal" way to go about it, so any advice would be appreciated.

# Answer
> 0 votes
See if the hook is being called or not. Try printing some of the node variables inside the hook. Also try adding the libraries based on path alias which is configurable anytime unlike nids which differ based on the instances. If you are to follow path approach,

```
function themename_preprocess_page(&$variables) {

   /*Get Url based on the url alias of current path */
    $current_path = \Drupal::service('path.current')->getPath();
    $Url = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
    /*Attached calendar script for this page alone */
   if($Url =="/contact/open-office-hour"){
     $variables['#attached']['library'][] = 'themename/calendar';
   }
}

```

---
Tags: theming
---


# Question
Title: No schema for my_module.global error on unit test
I got an existing Drupal 8.2.x project with existing unit tests. When I run a sample unit test, I get the error (real module name redacted):

```
No schema for my_module.global

```

This doesn't seem to be related to the `my_module.schema.yml` file, or any DB schema that I can tell. Drilling down, I got this output for the `$definition` variable in `\Drupal\Core\Config\TypedConfigManager.php`, which the unit test calls up (among others):

```
array (
  'label' => 'Undefined',
  'class' => 'Drupal\\Core\\Config\\Schema\\Undefined',
  'definition_class' => '\\Drupal\\Core\\TypedData\\DataDefinition',
  'type' => 'undefined',
)

```

For core modules the class is `Drupal\\Core\\Config\\Schema\\Mapping`. Note that the error complains about a schema for `my_module.global`, which is one of the YAML config files for this module (can't tell how else it's related).

The question is, what does this schema mean exactly, and where do I set it for my module?

# Answer
> 7 votes
Turns out that it *is* related to the my\_module.schema.yml. Looks like every YAML file under `my_module/config/install` must have a corresponding schema in the `my_module.schema.yml` file in order to set up a unit test, even if this is not actually required for the module to work. It needs to look something like this (assuming the config/install file name is `my_module.global.yml`):

```
my_module.global:
  type: mapping
  label: 'My label'
  mapping:
    property:
      type: text
      label: 'Property label'

```

If unsure which properties need to go there, running the unit test without them will give a list as part of the error. I'm sure there is a better way to find this, but that's the way I found so far.

**Edit** – the whole schema verification mechanism can be turned off: In `drupal/core/lib/Drupal/Core/Test/TestSetupTrait.php`, `$strictConfigSchema` needs to be set to FALSE.

**Edit 2** – here is a module that provides a neat UI for schema validation: https://www.drupal.org/project/config\_inspector

---
Tags: 8, testing
---


# Question
Title: How do I customize hierarchical breadcrumbs?
The breadcrumbs I get are like the following ones.

* Home / services
* Home / service 1
* Home / service 2

I want to change them to the following ones.

* Home / services
* Homes / services / service 1
* Homes / services / service 2

How can I change the breadcrumbs to be the way I want them?

# Answer
> 4 votes
In D8 the hierarchy of breadcrumbs is by default path based, so you have to change the path for the second level from `/service1` to `/services/service1`

Or install a module to build the hierarchy based on menus or taxonomy terms:

https://www.drupal.org/project/menu\_breadcrumb https://www.drupal.org/project/taxonomy\_breadcrumb

---
Tags: 8, navigation, breadcrumbs
---


# Question
Title: How do I see the names of all view fields in the formatter option form?
I am extending the StylePluginBase to make a custom views formatter. I would like to add a select box in the option menu with a list of all the fields currently listed within the view. How do I pull the list of fields into the buildOptionsForm function? Does the FormStateInterface have the view buried in it somewhere that I need to do something like:

```
$options = [];
$view = $form_state->view;
foreach($view->fields as $field){
  $options[] = $field->name;
}

```

# Answer
A little late, but maybe still helpful for someone. You can use `$fields = $this->displayHandler->getFieldLabels(TRUE);` to get an array of all currently chosen fields in the view.
> 1 votes

---
Tags: views, 8
---


title: Hook into node/entity creation/insert

text:
# Question
Title: Hook into node/entity creation/insert
Functionally, what I want to achieve is to duplicate a node (with a different node-type) when creating/inserting.

To be more precise: I have two content types: news and press-release. What I want to achieve is that when a press-release is made in admin, a news item is automatically created as well.

I looked into D8 hooks (hook\_ENTITY\_TYPE\_insert to be specific), but can't get it to work, the documentation is confusing to me. This is what my .theme file looks like:

```
<?php
/**
 * @file
 * Bootstrap sub-theme.
 *
 * Place your custom PHP code in this file.
 */

/*
 * Implements hook_ENTITY_TYPE_insert().
 */
function hook_persbericht_insert(Drupal\Core\Entity\EntityInterface $entity)
{
    if (isset($entity->field_duplicate_to_news) && $entity->field_duplicate_to_news[0] === 'on')
    {
        // create a new news-article here
    }
}

```

Any help and suggestions are welcome

# Answer
Whenever in drupal documentation it says to use "hook\_" it means to replace "hook\_" with the name of your module or theme. Often on this site, you'll see "mymodule\_" used as an example. When you see "ENTITY\_TYPE" in a hook description that is usually going to be "node" "taxonomy\_term", "user", etc., it is not the bundle, or subtype of an entity. Drupal nodes are labelled as "Content Types", which is synonymous with bundle. Bundle is the term used across many different entities and is a backend term, while they are labelled different things on the front-end for different entity types. For nodes, they are "Content types", for taxonomy, they are "Vocabularies".

You wouldn't want to use the bundle in your hook if it's looking for "ENTITY\_TYPE", so "persbericht" ("press release") isn't correct. You'd want to use node.

Themes can only implement a small number of hooks, such as alter hooks. They can't implement CRUD operations. So you'd want to put this in a custom module.

```
use Drupal\node\Entity\Node;
/**
 * Implements hook_ENTITY_TYPE_insert().
 */
function mymodule_node_insert(Node $node) {
  if ($node->bundle() == 'press_release') {
    $copy = Node::create([
      'title' => $node->getTitle() . ' copy!',
      'type' => 'article',
      'status' => 0,
    ]);
    foreach ($node as $key => $value) {
      // Copy values from all fields (fields start with "field_").
      if (strpos($key, 'field_') === 0) {
        if (isset($copy->{$key})) {
          $copy->{$key}->setValue($node->{$key}->getValue());
        }
      }
    }
    $copy->save();
  }
}

```
> 6 votes

---
Tags: nodes, 8, hooks
---


title: Inline Entity Form validation

text:
# Question
Title: Inline Entity Form validation
Created a content type and add taxonomy form in it using Inline entity Form module.

So, the rendered taxonomy add term looks like :

What I want to do is **ADD CUSTOM VALIDATION** to the "**NAME**" field.

I tried:

```
function hook_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
  //kint($form_state->getStorage('inline_entity_form'));die;
  // $entity = $form_state->getFormObject()->getEntity();
  //   $nid = $entity->get('name')->getValue();
  $userInput = $form_state->getUserInput();
 // kint($form_state->getUserInput()['field_plan_features']['form']['inline_entity_form']['name']);die;
 // $form_state->setErrorByName('name', t('Term already exists in taxonomy blah'));
}

```

How it can be done.. please suggest some way.

# Answer
I suggest you implement hook\_form\_alter(&$form, \Drupal\Core\Form\FormStateInterface $form\_state, $form\_id) function.

```
    function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
      // Check if the $form_id is your node type add form.
             if ($form_id == 'article') {
                // Add a custom validation function. Example:
                $form['#validate'][] = 'custom_form_test';
              }
    }

```

Then you need to implement the custom function where you will put your logic.

```
function custom_form_test(&$form, FormStateInterface $form_state) {
  // Get value of the field which use the inline entity form display.
 $tags_value = $form_state->getValue('field_tags');

}

```

See the screenshot of the $form\_state dump and also with the field\_tags taxonomy term reference values:

So you can access all the values from the inline form display. For example to access name value:

```
$name = $tags_value[0]['inline_entity_form']['name'][0]['value'];

```

Just looping into arrays. Once you get the value that you want you cand restrict finishing the submision of a node by write a message error. Example:

```
 $form_state->setErrorByName(
                'field_tags',
                'The name is WRONG!'
              );

```

Hope to help you!
> 0 votes

---
Tags: 8, forms, taxonomy-terms
---


# Question
Title: What is the best method for getting vendor files on the server?
I'm fairly new to Drupal 8 development, and I've been a little frustrated with the complications that Composer has added. Nonetheless, I'm trying to determine the best way to get the necessary **/vendor** files on the server.

I understand that Composer recommends that you ignore the **/vendor** directory. However, if you don't have a build server in place, what's the best method to getting the **/vendor** files on the server? Is it common practice to load and run Composer on the server, or is that a big no-no?

# Answer
> 2 votes
You have two options.

1. Commit the entire project with Git.
2. Use Acquia BLT.

The first method is not preferred because it makes the repository size massive and unwieldy, but if you have no build server you have no build server. But not having a build server isn't necessarily the end, because...

The second choice would allow you to *build locally and deploy to remote* using a command BLT provides.

Here is an example. I want to build my develop branch and put it on the server. I can enter the repository url in my project.yml file (provided by BLT), and run this command:

```
blt deploy -Ddeploy.branch=develop-build -Ddeploy.commitMsg='PROJECT-000: Generating new build for PROJECT.'

```

This will generate a build artifact (which is *not committed* into your canonical repository), but instead committed to the remote repository being deployed to as `develop-build` or whatever you name the branch. You then switch your dev environment to run that branch instead of `develop`. For instance, my canonical repo lives on GitHub, my remote repo is on Acquia. GitHub won't ever have the `-build` branches committed to it, and the Acquia repo won't ever have `develop` or `master` \- it will have the build artifacts of deployed branches. You could use the same repository for both, but its a drag IMO because you (or I, anyway) want the canonical repo to be clean and not be dragging around artifacts of this size.

It *is* easier with a CI server to automate all of this, but Acquia BLT is a viable option when you don't have a CI service to use because you can run the commands yourself from your machine.

Another option would be to build your own scripts to do this as well, but I'd say you are better off starting with BLT. It can be added to existing projects, and it is straight-forward to configure via project.yml.

So no, you do not need to run Composer on the production server. Most hosting companies would never allow this anyway.

---
Tags: 8, installation, composer
---


# Question
Title: How do I separately get label and field?
For form fields, we have label and field (Text/Select/...).

How do I get the field title and its value separately in a template file?

```
{{ form.title }}

```

I need both separately, so I can properly style.

# Answer
To access separately labels and values for fields in twig template (example in node twig template: node.html.twig) I propose to loop all the node variable.

My example: Instead of print all content with this line {{ content }} loop the content object

```
    {% for item in node %}
        {# Print the label of the field #}
        {{ item.fieldDefinition.label }}

        {# Print the value of a field text/simple field #}
        {{ item.fieldDefinition.value }}

        {# Print the value of a field reference  #}
        {{ item.value[0]['target_id'] }}
    {% endfor %}

```

Other way is to use this module: https://www.drupal.org/project/twig\_field\_value
> 2 votes

---
Tags: 8
---


title: Error installing CiviCRM

text:
# Question
Title: Error installing CiviCRM
Following the amazing work @david-snopek posted:

I spent the better part of last evening trying to get CiviCRM up and running on a Drupal 8.4 BLT project.

After trying a few different approaches, unfortunately I'm now seeing the following error when trying to enable the `CiviCRM Core` Module

> CiviCRM must be downloaded into the libraries folder.

No matter what I try, I can't seem to get the module to recognize that civicrm is installed.

### Other things I've tried:

1. manually copying the `[project_root]/vendor/civicrm-core` into `[project_root]/docroot/libraries/civicrm-core`
2. Renaming `libraries/civicrm-core`to `libraries/civicrm`
3. Modifying `composer.json` to try and install CiviCRM into the libraries folder:
4. Creating symbolic links to the folder (my least favorite attempt)

Here is the composer.json update for number 3 above:

```
    "require": {
    "acquia/blt": "^8.3",
    "phpoffice/PHPWord": "dev-zend-version as 0.13.0",
    "civicrm/civicrm-core": "4.7.25"
},

```

...

```
"repositories": {
    "phpword": {
        "type": "vcs",
        "url": "https://github.com/dsnopek/PHPWord.git"
    },
    "zetacomponents-mail": {
        "type": "vcs",
        "url": "https://github.com/civicrm/zetacomponents-mail.git"
    },
    "civicrm": {
        "type": "package",
        "package": {
            "name": "civicrm/civicrm-core",
            "version": "4.7.25",
            "type": "drupal-library",
            "source": {
                "url": "https://github.com/civicrm/civicrm-core.git",
                "type": "git",
                "reference": "origin/master"
           }
        }
    }
}

```

source: https://gist.github.com/mortenson/a5390d99013b5b8c0254081e89bb4d47

I *think* this has to do with an autoloader issue perhaps seeing that BLT does not use the Drupal composer.json file and the instructions @david-snopek posted were for the traditional Drupal installation method.

I was able to trace the error to `modules/custom/civicrm-drupal/civicrm.install:125`.

```
/**
 * Returns the path to where CiviCRM is installed.
 *
 * @return string|void
 *
 * Recommended location for civicrm is in /libraries/civicrm [citation needed].
 * We also allow /modules/civicrm, which seems to work fine.
 */
function _civicrm_find_civicrm() {
  if ($path = drupal_get_path('module', 'civicrm')) {
    if (file_exists($path . '/CRM/Core/ClassLoader.php')) {
      return \Drupal::service('file_system')->realpath($path);
    }
  }

  $path = 'vendor/civicrm/civicrm-core';
  if (file_exists($path . '/CRM/Core/ClassLoader.php')) {
    return \Drupal::service('file_system')->realpath($path);
  }

  return NULL;
}

```

---

### Notes on my process:

I ran into a couple snags with the Gist David posted.

1. When running `$ composer require 'phpoffice/PHPWord:dev-zend-version as 0.13.0'`, I noticed that Composer was trying to add the dependency as:

```
"require": {
    "phpoffice/PHPWord": "dev-zend-version",
    "as 0.13.0"
},

```

This failed but I was able to get past the issue by manually adding the dependency to the composer.json file as:

```
    "require": {
        "acquia/blt": "^8.3",
        "phpoffice/PHPWord": "dev-zend-version as 0.13.0",
    },

```

Unfortunately, I then got stuck on the next step requiring civicrm-core until I read the comment a bit closer. I believe this step is now incorrect as `civicrm-core 4.7.25` has been released.

> ```
> #Require civicrm-core at the requested version.
> #TODO: Need to keep using my fork until 4.7.25 is released!
> #composer require civicrm/civicrm-core:$CIVICRM_VERSION
> composer require "civicrm/civicrm-core:dev-roundearth-$CIVICRM_VERSION as $CIVICRM_VERSION"
>
> ```

I was able to get past that issue by updating the additional repository via: `composer config repositories.civicrm-core vcs https://github.com/civicrm/civicrm-core.git`

Reference: https://www.mydropwizard.com/blog/how-install-civicrm-drupal-8-and-why-choose-it-over-pure-drupal-crm

# Answer
Following literally the instructions for manual installation as given by David Snopek (https://www.mydropwizard.com/blog/how-install-civicrm-drupal-8-and-why-choose-it-over-pure-drupal-crm) I succeeded in installing civicrm 4.7.27 under Drupal 8.4.2.

One caveat: I installed Drupal with composer (https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies), using option B on that page "drupal/drupal" as using this option put vendor under the document root, something that is necessary according to David's blog post. In the Drupal documentation it is indicated that with option B one must manually add some lines to the composer.json file but, at least with 8.4.2, it is all there. But the error code about the libraries folder may indicate that these lines are not available in your composer.json file.

I cannot provide additional help but at least, the instructions from David seem to work still with the latest versions of both Drupal and Civicrm.
> 0 votes

---
Tags: 8, composer, civicrm
---


# Question
Title: How do I know if JS Injector is applying script correctly to page?
I am trying to get some accordian drop downs working on this page: https://www.permaculture.org.uk/education/organising-courses

I have basically copied W3schools CSS and JS and pasted them in to CSS injector and JS injector respectively. From here: https://www.w3schools.com/w3css/w3css\_accordions.asp

But the drop down accordian function does not seem to work - how can I tell if it's even being applied?

Thanks!

# Answer
> 0 votes
> But the drop down accordian function does not seem to work

You can put an `alert('it works!');` to make sure the jQuery code is indeed running.

Probably it's because you're not wrapping the code in Drupal jQuery syntax.

Assuming **Drupal 7**.

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

    // w3schools code goes here

  }
};
})(jQuery);

```

For more info, see Working with JavaScript and jQuery

# Answer
> 0 votes
You can tell if JS is working by viewing the element in Inspector...

In the below screenshot, yours shows no JS, but on the right which is from my site, you can see an icon that shows that element has some JS attached to it.

Also, from Debugger, I can see your CSS is added but not the JS. As far as I remember, JS Injector's folder is in /files.

Even if you get JS Inspector working, you need to add this to the top and the bottom.

```
jQuery(document).ready(function($){

// code

});

```

And to test in your browser, you should know that typing `jQuery` is the same as `$`. So for testing, you can use `jQuery` all the time, or start with `$ = jQuery;` .

Anyways, here's some basic jQuery that will work for your site. (But you need to make it more accurate.. Your p should have a class, or the parent structure should have a class so you can narrow it down.

```
$('p').click( function() {
  $(this).next('.panel').toggle();
});

```

To get it to work in browser Inspector, first type `$ = jQuery;`, then copy the above code.

---
Tags: theming
---


# Question
Title: No Ajax gets initialised from inside the modal
I've got a bunch of forms that are opening inside a modal so that the user is not redirected off the page. I've then got a few Ajax calls on form items inside the form. They all work when using the form in a page instead of a modal, however when in a modal it just gets an Ajax error.

The simplest Ajax functionality is the following:

```
function hook_form_alter(&$form, $form_state, $form_id) {
  $form['field_rate']['widget']['#ajax'] = array(
    'callback' => 'changeActualRate',
    'event' => 'change',
    'wrapper' => 'rates-wrapper'
  );
}

function changeActualRate(array &$form, FormStateInterface $form_state) {
  // Get rate from taxonomy term
  $rate = $form_state->getValue('field_rate');
  if (!empty($rate)) {
    // Instantiate an AjaxResponse Object to return.
    $ajax_response = new AjaxResponse();

    $rate = taxonomy_term_load($rate[0]['target_id']);
    $cost = $rate->get('field_cost')->getValue();
    $cost = $cost[0]['value'];
    $ajax_response->addCommand(new InvokeCommand('#edit-field-actual-rate-0-value', 'val' , array($cost)));

    // Return the AjaxResponse Object.
    return $ajax_response;
  }
}

```

It's a pretty simple bit of functionality but it seems no Ajax gets initialised from inside the modal. Anyone have any ideas on how to initialise Ajax once the modal is open. Modals are being opened via links using `class="use-ajax" data-dialog-type="modal"`.

# Answer
> 1 votes
It could be that your behaviors aren't processing the newly added modal elements because of an internal JS error.

I determined this because that was the problem discussed in this D7 answer:

How to trigger Drupal.attachBehaviors after successful Ajax

---
Tags: forms, 8, ajax
---


title: Prefill Registration Form Fields

text:
# Question
Title: Prefill Registration Form Fields
* Entity Registration
* Commerce Registration
* Drupal 7

Our site connects with Salesforce to input Entity Registration data as Contacts. I'm building in the ability to have users login and have their registration forms prefilled with the data I grab from Salesforce.

I have the data, but the prefill isn't working. Commerce Registration buries the forms a bit, as you will see below in my code example. I decided to step out of using the Salesforce data and just use a static value and try to set it. Both default\_value and placeholder do nothing. If I try to touch \['value'\] the site crashes.

Here is the trimmed down version of what I have:

```
<?php
function createFieldMap(){
    $fieldMapping = array(
        "LastName" => "field_last_name",
        "FirstName" => "field_first_name",
        "Salutation" => "field_prefix"
    );
}
function custom_module_form_commerce_checkout_form_registration_alter(&$form, &$form_state, $form_id) {
    $fieldMap = createFieldMap();
    foreach ($form['registration_information']['register_entities'] as $name => $data) {
        foreach($form['registration_information'][$name] as $subname => $subdata) {
            foreach ($fieldMap as $salesforceKey => $drupalMachine) {
                if($drupalMachine == 'field_last_name'){
                   $form['registration_information'][$name][$subname]['field_last_name']['#default_value'] = "Johnston";
                   $form['registration_information'][$name][$subname]['field_last_name']['#attributes']['placeholder'] = t("Johnston");
               }
            }
        }
    }
}

```

Just to point out, **$form\['registration\_information'\]\[$name\]\[$subname\]** is valid and is done that way because if you have multiple forms, the productID is used as the form ID, twice. I can access **$form\['registration\_information'\]\[$name\]\[$subname\]\['field\_last\_name'\]** if I var\_dump it out. **\['value'\]** represents entity data for some reason, which is probably why it crashes if I try to adjust that.

I can get this to work fine by setting the default\_value of select lists. But the text fields don't do anything.

# Answer
Fixed it. I had to work with \['und'\]\[0\]\['value'\]\['#default\_value'\]

So my new code is:

```
<?php
    $fieldMap = createFieldMap();
    foreach ($form['registration_information']['register_entities'] as $name => $data) {
        foreach($form['registration_information'][$name] as $subname => $subdata) {
            foreach ($fieldMap as $salesforceKey => $drupalMachine) {
                $form['registration_information'][$name][$subname][$drupalMachine]['und'][0]['value']['#default_value'] = $contact[$salesforceKey];
            }
        }
    }

```
> 0 votes

---
Tags: 7, forms, commerce
---


# Question
Title: Do not install core when installing modules with composer
I want to manage my modules with composer, so I created a *composer.json* file in my *sites/my\_site* directory that looks like this:

```
{
    "repositories": {
        "drupal": {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    },
    "require": {
        "composer/installers": "~1.0",
        "drupal/addtoany": "^1.8",
        "drupal/workbench": "^1.0",
    },
    "extra": {
        "installer-paths": {
            "libraries/{$name}": ["type:drupal-library"],
            "modules/contrib/{$name}": ["type:drupal-module"],
            "profiles/contrib/{$name}": ["type:drupal-profile"],
            "themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/{$name}": ["type:drupal-drush"],
            "modules/custom/{$name}": ["type:drupal-custom-module"],
            "themes/custom/{$name}": ["type:drupal-custom-theme"]
        }
    }
}

```

The problem is that when I run "composer install" or "composer update", I get a "**core**" directory with Drupal core created in my *sites/my\_site* directory. Is there any way to avoid pulling in the core and only get the modules using composer from my *sites/my\_site* directory?

# Answer
Did not try this personally, but should work. Add this to your composer.json root:

`"name": "drupal/core",
 "version": "8.4.2",`

(adjust version number to your installed core version)

Be aware though this is not considered a clean solution, the recommended way is for drupal composer is "all or nothing". And I really recommend the "all" way, you do get the comfort of dependency *and* version *and* patch management.

More info about this hack: https://github.com/composer/composer/issues/5024
> 1 votes

---
Tags: composer
---


# Question
Title: How to create a membership using rules, using membership entity module
I'm using the membership entity module, and the membership entity commerce module.

I am trying to create a membership using rules, without success yet.

There is one membership action available..to activate the membership but thats all.

EDIT: This is the rule I used for checking out a membership:

```
    { "rules_at_listing_import_create_user_and_membership" : {
    "LABEL" : "At listing import create user and membership",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [
      "rules",
      "commerce_cart",
      "commerce_checkout",
      "membership_entity_commerce",
      "feeds"
    ],
    "ON" : { "feeds_import_listing_import" : [] },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "user",
            "param_name" : "[node:field-first-name][node:field-last-name]",
            "param_mail" : [ "node:field-user-email" ]
          },
          "PROVIDE" : { "entity_created" : { "user_created" : "Created user" } }
        }
      },
      { "user_unblock" : { "account" : [ "user-created" ] } },
      { "entity_save" : { "data" : [ "user-created" ], "immediate" : "1" } },
      { "commerce_cart_product_add_by_sku" : {
          "USING" : {
            "user" : [ "user-created" ],
            "sku" : "Listingmember-1y",
            "quantity" : "1",
            "combine" : "1"
          },
          "PROVIDE" : { "product_add_line_item" : { "product_add_line_item" : "Added product line item" } }
        }
      },
      { "commerce_checkout_complete" : { "commerce_order" : [ "product-add-line-item:order" ] } },
      { "membership_entity_commerce_activate_term" : { "commerce_order" : [ "product-add-line-item:order" ] } }
    ]
  }
}

```

Using this rule, I assume that the membership is created automatically because of the membership product being checked out.

Alternatively, I tried the method without using the membership product, by straight away creating an entity of type membership using rules. That does not work, the membership is not created.

# Answer
I did a good comparison of the Commerce membership entity module and the Commerce Licenses module, and the commerce licences can do te same, and has a lot more extra features, is more flexible. So switching to that module was my solution.
> 0 votes

---
Tags: 7, commerce, rules
---


# Question
Title: I am not understanding how to use cache context
In search result page I need to change url of title field based on permission assigned to user . If user has permission then show url 1 else show url 2 .

We need to cache all renderable array. I am creating

```
$data = [
  '#type' => 'link',
  ' #href' => $url,
]

```

I am confused with cache context and cache tags.

Please suggest which one to use?

# Answer
> 2 votes
Cache context - https://www.drupal.org/docs/8/api/cache-api/cache-contexts \- is how the cached content varies. In your case you want it to vary - be different for - users based on if they have a permission or not. i.e. you want it to be cached one way if they have the permission, and another way if they don't have the permission. So you probably want `user.permissions:<your_permission>`.

Cache contexts need to be something Drupal can work out *before* it gets to the level where it's rendering content and etc so that's why you can have a context on `route` (cheap to inspect because Apache just gives it to you) but not `node` (expensive to vary on because to work out the node Drupal needs to run SQL) - because hopefully Drupal can just serve content out of cache before it even gets to the point of working out if the current `route` matches a `node` in the database or not.

Cache tags - https://www.drupal.org/docs/8/api/cache-api/cache-tags \- are for what your cached data is *dependent* on. In your case, URL probably points to something right? So if it points to e.g. a node, your cache tag would be `node:<nid>`, and Drupal will know that if node *nid* ever changes it should delete those cache entries, because the URL might have changed.

You *shouldn't* just manually set the cache tag to `node:<nid>` though - the more generic way to do it is to use addCacheableDependency.

---
Tags: caching
---


# Question
Title: How can I change the label for the vote button?
I am using poll module in my site. Everything is working fine. But the submit button(label) is "vote", I want to change it to "Submit". How can i change this? And this is a block.

# Answer
You need to implement `hook_form_alter()` for altering the *poll\_view\_voting* form and change `#value` from *Vote* to *Submit*.

```
function mymodule_form_poll_view_voting_alter(&$form, &$form_state, $form_id) {
  $form['vote']['#value'] = t('Submit');
}

```
> 2 votes

---
Tags: 7, polls
---


# Question
Title: /sites/default/files images not showing up
This is for a Drupal 6 site, but I've seen this problem with Drupal 7 before too.

I migrated my site from a main domain (www.domain.org, let's say), to a development domain, with a subdirectory, (www.devlin.domain2.com/domainupgrade).

That breaks the images located in /sites/default/files, but not the files located in /sites/all/themes/themename

How can I fix this? I've tried changing file permissions (shot in the dark) as well as the base url setting (but I perhaps didn't change it to the correct value?)

How can I get images to show up in this context on the development site?

# Answer
I appreciate that this is an old post but after days of trying to resolve the problem I have seen many of these posts and want to update with my solution.

My web host is classed as a shared web host which means for me that I don't have as much access to the server side as with other hosts. The control area for the admin on my host is custom and lots of stuff that I have with another host and previous hosts id missing.

I resolved the images not showing by adjusting the .htaccess file. There are 2 that I have found so far in Drupal 7.24 (one in the site root and one in sites/default/files/) and I had to adjust both of them by commenting out the options section and the symlinks section. There is info on this by googling "one.com Drupal Installation".

Once both htaccess files had been edited and the permissions had been changed on the "files" folder in "sites/default/" to "755" the extra folders where created when I uploaded my images and the images started to show fine. If like me you are unable to change permissions within your website hosts control panel you will need to do it with either an ftp client or via ssh.
> 1 votes

# Answer
Try changing +FollowSymLinks to +SymLinksIfOwnerMatch in .htaccess file inside /sites/default/files/
> 1 votes

# Answer
I had this same problem when I cloned my D 7.5 site from a hosting account to my local XAMPP server. None of the above suggestions worked. However, when I removed the leading slash in the image location path HTML it worked.

So, my HTML source as running fine on remote hosting account works as

```
/sites/default/files/Complicated.png

```

Have to change that to

```
sites/default/files/Complicated.png

```

(removed leading slash) to get it to work on my local migrated site.

So, while this is an answer I still don't know what in my setup/environment would cause this to be different for two identical D7 sites? I don't want to have to manually go through my large site editing image paths.
> 0 votes

---
Tags: media, files, migrations
---


# Question
Title: How do I translate/change the text of the order receipt email in Commerce 2?
The Commerce 2 documentation describes how to send a an order confirmation receipt:

1. Go to the Commerce admin page.
2. Choose order types.
3. Click edit for the relevant order type and check the box to email a receipt.

However, how do I translate the text of this receipt? There appears to be no UI for this.

# Answer
> 0 votes
You can find the **Subject** on the UI translate page (/admin/config/regional/translate). Search for *Order #*.

The rest can be found in a twig template:

`/modules/contrib/commerce/modules/order/templates/commerce-order-receipt.html.twig`

Copy this template to your theme and then edit as desired. You can also use the template as a guide for what to search for on the translation UI screen to translate everything.

---
Tags: commerce
---


title: Using the URI to highlight menu items

text:
# Question
Title: Using the URI to highlight menu items
* I have a content type on my site called "Articles".
* I created a view that lists the nodes of this content type. It's path is "/articles"
* For that view, I created a menu item in my main menu, "Articles".
* I used the pathauto module for all my nodes of this content type to have the path `articles/[node:title]`

My question is, **I want the menu item to remain highlighted if the user is viewing a single article node, or if the user is viewing the view**.

I solved the issue by using `theme_menu_link()` function in my template.php file for my theme (code below). Being new to the Drupal API, is there a better way to do it?

What I did:

```
function mytheme_menu_link(array $variables) {

  //Some variables, we're using
  $element = $variables['element'];
  $sub_menu = '';

  //#href is an element inside the item
  $the_path = drupal_lookup_path('alias', $element['#href']) ?: $element['#href'];

  //Compare the path to the actual URI (using sub-function), and if they match, then add a new CSS class
  //either: 'uri-active' or 'uri-active-trail'
  switch(mytheme__menu_detect_uri($the_path)) {
    case 1:  $element['#attributes']['class'][] = 'path-active'; break;
    case -1: $element['#attributes']['class'][] = 'path-active-trail'; break;
  }

  //If there are sub-menu items under this, render those too
  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }

  //Return the output
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

/**
 * Detect if a given path matches the current URI, as detected
 * from reading the current_path() alias from Drupal
 *
 * @param string $path_to_check  The path to check
 * @param string $check_against  The path to check against (leave blank for current path)
 * @reutrn int   1 = Matches, 0 = No Match, -1 = In Active Path
 */
function mytheme__menu_detect_uri($menu_item_path, $actual_path = NULL)
{
  if (is_null($actual_path))
    $actual_path = drupal_lookup_path('alias', current_path()) ?: current_path();

  //Compare em
  if (strcasecmp($menu_item_path, $actual_path) == 0)
   return 1;
  elseif (strlen($actual_path) > strlen($menu_item_path) && strcasecmp(substr($actual_path, 0, strlen($menu_item_path)), $menu_item_path) == 0)
    return -1;
  else
    return 0;
}

```

# Answer
> 1 votes
the context module allows you to highlight a menu item if certain condition (like a path) has been met.

# Answer
> 1 votes
Context works but is a bit overkill if you only want to highlight the menu items. The Menu Trail By Path module does this automatically according to your path aliases. There is also the Menu Position module which offers some more functionality and settings.

# Answer
> 1 votes
If this is meant sole for user experience on the website, as far as I know, there's a possibily to do so via CSS. Using menu attributes module, you can add a class to that particular list item. Then, any view page should have a class for the body element and you can style the right classes for the view, same with the attributes for single article style format. No need to write a bunch of php code insead of one or two lines via CSS.

# Answer
> 1 votes
```
/**
 * Implements hook_node_view().
 */
function MY_MODULE_node_view($node, $view_mode) {

  // Just make a blog menu item active during viewing blog post detailed page.
  if ($view_mode == 'full' && !empty($node->type) && $node->type == 'blog_post') {
    menu_tree_set_path('main-menu', 'blog');
  }
}

```

# Answer
> 0 votes
To make any menu active on certain content type use menu\_set\_active\_item($path) function.

```
/**
 * Implements hook_node_view().
 */
function hook_node_view($node, $view_mode) {

  if ($view_mode == 'full' && !empty($node->type) && $node->type == 'article') {
    menu_set_active_item('[MENU_PATH]');
  }
}

```

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


title: Unable to recognize mysqlnd host

text:
# Question
Title: Unable to recognize mysqlnd host
I have installed mysqlnd when I try to use the drush command `drush cc all`, I get the following message.

> No Drupal site found, only 'drush' cache was cleared.

and when I run the command `drush ws` I get the following message.

> PHP Fatal error: Call to undefined function module\_exists() in phar:///usr/local/bin/drush/commands/core/drupal/environment\_7.inc on line 187 Drush command terminated abnormally due to an unrecoverable error.
> \[error\]
> Error: Call to undefined function module\_exists() in phar:///usr/local/bin/drush/commands/core/drupal/environment\_7.inc, line 187

If I try to run the above commands without the mysqlnd plugin, they work fine.

Also, if I run `drush status` I get the following:

```
 Drupal version         :  7.43
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  myapp
 Database port          :
 Database username      :  drupal
 Database name          :  web1
 PHP configuration      :  /etc/php.ini
 PHP OS                 :  Linux
 Drush script           :  /usr/local/bin/drush
 Drush version          :  8.1.3
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :  /root/.drush/aliases.drushrc.php
 Drupal root            :  /var/www/html/site2
 Drupal Settings File   :  sites/default/settings.php
 Site path              :  sites/default

```

The above won't show the theme name. Also if I try to run `drush mysql-cli` I get the following message:

> ERROR 2005 (HY000): Unknown MySQL server host 'myapp' (0)

I wonder if I can get the above commands running using the mysqlnd plugin.

# Answer
> 2 votes
The solution was adding the following code in settings.php. It will allow Drush to connect to mysqlnd.

```
if (drupal_is_cli() || basename($_SERVER['PHP_SELF']) == 'update.php') {
  $databases['default']['default'] = $databases['default']['ms'];
}

```

# Answer
> 1 votes
The solution is adding the following path to system environment.

It is because of mysql.exe it not found globally.

> C:\xampp\mysql\bin;

The PATH environment variable should be assigned by going to My Computer \> Right-click any blank area inside window \> Properties \> Advanced tab \> Environment Variables \> System Variables \> select PATH & edit as described.

---
Tags: database, drush
---


# Question
Title: Create a zip file from a list of selected files and make the zipped file downloadable in Drupal 8
How to create zip file programatically based on the files selected in Drupal 8? Is there any class already existing in Drupal 8?

As per below answer I'm using following code to generate zip file:

```
$file = \Drupal\file\Entity\File::load($fileId);
$fileUri = \Drupal::service('file_system')->realpath($file->getFileUri());

$zip = \Drupal::service('plugin.manager.archiver')->getInstance(['filepath' => '/foo/bar.zip']);
$zip->add($fileUri);

```
* The bar.zip file above should exist in the referenced path above: `/foo/bar.zip`.
* Also how do I flatten the the zip file folder structure so that the file `sites/default/files/myimage.png` is `myimage.png`?

# Answer
Use the ArchiverManager and get the instance by calling the `getInstance()` method. A Zip class is returned. The Drupal `Zip` class uses PHP's ZipArchive class to perform the heavy lifting.

**Example (edited after remark @Clive):**

```
$file = \Drupal\file\Entity\File::load($fileId);
$fileUri = \Drupal::service('file_system')->realpath($file->getFileUri());

$zip = \Drupal::service('plugin.manager.archiver')->getInstance(['filepath' => '/foo/bar.zip']);
$zip->add($fileUri);

```
> 7 votes

# Answer
Below sample code is working fine to create zip file in Drupal 8.

```
$file = File::load($file_id);
$filename = $file->getFilename();
$file_path = \Drupal::service('file_system')->realpath($file->getFileUri());
$destination = \Drupal::service('file_system')->realpath('public://foldername');
$zip = new \ZipArchive;
$zip->open($destination . "\dump.zip", constant("ZipArchive::CREATE"));
$zip->addFile($file_path, $filename);
$zip->close();

```

Please check Backup and Migrate module soruce code for more reference.

Note :

1. Create the destination folder before execute this above code.
2. Please make sure php zip and gd libraries should be installed and enabled in the server.
3. Recommended to use external zip creation library when the server doesn't support **zipArchive** class.
> 1 votes

---
Tags: 8, files
---


# Question
Title: Calculate percentage based on two fields, one of which is an embedded view
I am trying to calculate a percentage based on two fields in my table. I am using views and I have a table which has 2 fields, one field is an aggregation of of all records and the other is an embedded view which has another number - I used the Views Field View module for embedding the field.

How can i get a percentage between these 2 fields. The Math Expression field is not supported in drupal 8 and I have also tried the views\_simple\_math\_field and it didn't help me at all. Please help!

# Answer
i tried in output code:

```
<?php
echo count($row->field_a) + count($row->field_a) ;
?>

```

and the result is:

I modified the view, and used aggregation.

I modified the field a:

I modified the field b:

I modified the field php:

And the code:

And result:
> 0 votes

# Answer
if you want ***sum*** two field, you install the module: https://www.drupal.org/project/views\_php

As an example, add two fields in your content "***basic pages***":

1. field\_a
2. field\_b

I create a content of example: nid = 43

Please create a new view as is the image.

in your field "**Global: PHP (php)**" in the section: "**Output code**".

sum two fields please use the following code

```
<?php
echo $row->field_a +$row->field_a ;
?>

```

preview
> -1 votes

---
Tags: views, 8
---


# Question
Title: How we can make weekly calendar block with ajax?
How we can make weekly calendar in drupal 7 module same as attach screenshot?

**My R&D**

I am using jQuery week calendar (https://github.com/themouette/jquery-week-calendar) .

# Answer
> -1 votes
I have achieved weekly calendar functionality using the php date function .

```
  $date = date('m/d/Y');
  // parse about any English textual datetime description into a Unix timestamp
  $ts = strtotime($date);
  // find the year (ISO-8601 year number) and the current week
  $year = date('o', $ts);
  $week = (int)date('W', $ts);

```

# Answer
> 0 votes
Use calendar module (requires views module). Calendar module comes with bunch of blocks (block views) available and you can set for them to use AJAX instead of refreshing page. With views you can do a lot of customization.

---
Tags: datetime
---


# Question
Title: How to alter default redirect after Entityform delete
By default, entityform delete form action is hardcoded in file `entityform.admin.inc` to the following value:

```
$form_state['redirect'] = "admin/structure/entityform_types/manage/{$entityform->type}/submissions";

```

As this function is a submit callback, it is executed AFTER invoking hook form alter, so this approach won't work.

# Answer
The solution is to add another submit callback. This one will run after the one Entityform uses for the redirect. This way, we will be able to overwrite that hardcoded value:

```
/**
 * Implementation of hook_form_FORM_ID_alter()
 * Makes sure it redirects to results on Delete.
 */
function MYMODULE_form_entityform_delete_form_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = '_MYMODULE_form_delete_redirect';
}

function _MYMODULE_form_delete_redirect($form, &$form_state) {
  $form_state['redirect'] = 'MY_REDIRECT';
}

```
> 0 votes

---
Tags: forms
---


title: Taxonomy terms disappearing

text:
# Question
Title: Taxonomy terms disappearing
I'm working with Drupal 8 Taxonomy terms. I'm managing them in the backend through the default taxonomy pages.

I'm doing this for a project where I need to label rows in a custom added table.

This all worked pretty fine until suddenly, just out of nowhere, the terms disappeared. I added terms, and when I returned to the list page of the specific taxonomy library, they where gone. They were still in the database, and `\Drupal\taxonomy\Entity\Term::loadMultiple()` still returns them.

I've done a lot of digging, but I'm out of ideas. I need some pointers to continue my search.

# Answer
I found the issue. The taxonomy terms where stored without the taxonomy\_term\_hierarchy information. This info is needed for the list of terms in the admin list to determ the relations between the terms.

This was caused by me, I've removed the hierarchy field from the form. This caused Drupal to not save this information at all. There are no default values or something like that here.

https://www.drupal.org/files/drupal7-db-schema.png
> 1 votes

# Answer
Working with a script migrating terms to Drupal 8 I ran into this exact same issue. Thanks @jivanrij for pointing that out! I'd like to add upon that:

All taxonomy terms need a corresponding `taxonomy_term_hierarchy` record. Even when their belonging vocabulary is being marked as NON-hierarchical. All terms will either have a record with an actual parent `tid` value or a `0` value.

Adhering to the above fixed the terms from disappearing in my case.
> 0 votes

---
Tags: 8, taxonomy-terms
---


title: removing stylesheet from base theme

text:
# Question
Title: removing stylesheet from base theme
In our Drupal 8 theme we are using the `classy` base theme. `themes/mytheme/mytheme.info.yml`:

```
base theme: classy

```

Using the information from drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme I am trying to remove some stylesheets from the base theme - but I cannot figure out the right way to do so. For instance, I want to remove the `css/components/form.css` stylesheet from the base theme. So far I tried:

```
libraries-override:
  base:
    css:
      component:
        css/components/form.css: false

```

```
libraries-override:
  core/base:
    css:
      component:
        css/components/form.css: false

```

```
libraries-override:
  core/classy:
    css:
      component:
        css/components/form.css: false

```

None of which is working. Removing the stylesheet with `stylesheets-remove` would work fine - but this is deprecated and I would rather use the new intended way for Drupal 8+.

What is the correct way of removing/addressing/extending a library from the base theme?

# Answer
> 4 votes
It's `classy/base`:

```
libraries-override:
  classy/base:
    css:
      component:
        css/components/form.css: false

```

Which is defined in the `classy.info.yml`.

---
Tags: 8, theming
---


title: How to create a Search API block?

text:
# Question
Title: How to create a Search API block?
I have a search view based on "Search API", I want to replace the default search block of the drupal core with a block "Search API".

1) How to modify the search block of the heart so that it uses search api instead ?

or

2) How to create a custom block /structure/block/block-content to use "Search API" ?

# Answer
> 3 votes
You should create an exposed filter for the View page, probably based on the full text search field, and then set the filter form to show in a block.

All can be done from within the Views UI on the edit form for the search page.

# Answer
> 1 votes
Regarding "enter your search" you can use Better exposed filter module.(see https://www.drupal.org/project/better\_exposed\_filters)

---
Tags: 8, blocks, search
---


# Question
Title: No results view filtering on newly added field of content type
I have a content type called Parts. I just added a new boolean field called `is_accessory` with the default value being false. I added a filter on an existing view to show only Parts where `is_accessory` is false. When I run the view, no parts show up.

If I go to a Part page, select edit, then select save (without changing anything) that part will show up.

Do I need to write a hook\_update\_N function that loads and saves all the Part records?

# Answer
> 2 votes
You can set the views filter operation to `Is not equal to` and the value as `true`.

This should work for new entities that have the value as `false` and old entities where it just isn't set.

---
Tags: 7, views
---


# Question
Title: Is it possible to include extra arguments when migrating via command line?
Is it possible to include extra arguments when migrating via command line?

I have a custom migration which migrates XML content into Drupal as entities. However, each XML document of migrated entities need to be associated with a different node.

I'm successfully doing this entities to node association via the following code:

```
function complete($entity, stdClass $row) {
    $node = node_load(1);
    $node->field_questions[$node->language][ sizeof($node->field_questions[$node->language]) ]['target_id'] = $entity->id;
    node_save($node);
}

```

As you can see from the code, the NID is hardcoded. Of course, the NID could be extracted from the XML input but it is unknown in advance of the migration.

So, I just wonder if running `drush migrate Questions` could be run with custom arguments where I could specify the target NID to associate my migrations with? Something like, `drush migrate Questions --nid=10`

# Answer
In the URL below you can find Dush arguments for migrations. Following the documentation you need --idlist argument.

See here https://www.drupal.org/node/1561820

Hope that helps.
> 1 votes

---
Tags: 7, nodes, migrations
---


# Question
Title: Video displays on views results but not on node
I created a view that renders a list of video descriptions like title, speakers, speaker picture and a View Video link. The title and View Video link the direct user to the video page. But, the video does not render on that page. Instead, only the title of the video in form of a link renders.

Field Formatter is set to Render file and View Mode set to Default. I've also tried Full content. Also, I created a template using

```
render($content['field_webinar_video']);

```

But in that case, it only renders the title/link as well. How do I get the video to render?

# Answer
After some research, I found that I needed to change the display of the field within the content type. Content Type \> Manage Display. For the video field, I changed the format to Render file. It was previously set to Generic file.
> 0 votes

---
Tags: views
---


title: Redirect does not work on nginx

text:
# Question
Title: Redirect does not work on nginx
I'm migrating an old site to Drupal (using migrate module), and I've managed directly in code all old urls to redirect to new Drupal urls using redirect module, for example:

www.mysite.com/UserProfile.php?user=5

Redirects to:

www.mysite.com/it/community/peoples/mr-max

This works very fine on my dev environment with apache, but doesn't works on live environment with nginx.

At first try with old url, I received a blank page with the message "No input file specified."

So I've changed virtual host conf from:

```
location ~ \.php$ {
  #fastcgi_split_path_info ^(.+\.php)(/.+)$;
  #NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
  include fastcgi_params;
  fastcgi_param SCRIPT_FILENAME $request_filename;
  fastcgi_pass php-fpm;
}

```

to:

```
location ~ \.php$ {
  #fastcgi_split_path_info ^(.+\.php)(/.+)$;
  #NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
  include fastcgi_params;
  fastcgi_param SCRIPT_FILENAME index.php;
  fastcgi_pass php-fpm;
}

```

RESULT: no more "No input file specified." blank page, but redirect doesn't works and my front page is shown for all old urls.

Here's other settings from my virtual host, if can help:

```
location ~ \..*/.*\.php$ {
  return 403;
}
location ~ ^/sites/.*/private/ {
  return 403;
}
location ~ (^|/)\. {
  return 403;
}
location / {
  try_files $uri @drupal;
}
location @drupal {
  # For D7 and above:
  # Clean URLs are handled in drupal_environment_initialize().
  rewrite ^ /index.php;
}
location ~ \.php$ {
  #fastcgi_split_path_info ^(.+\.php)(/.+)$;
  #NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
  include fastcgi_params;
  fastcgi_param SCRIPT_FILENAME index.php;
  fastcgi_pass php-fpm;
}

```

What kind of setting I have to change/add to the above conf to make redirect working correctly?

# Answer
Finally, someone redirected me to the right place

Here's the missing code that does the trick:

```
location ~ \.php$ {
            error_page 418 = @rewrite;
            recursive_error_pages on;

            fastcgi_split_path_info ^[^=](.+\.php)(/.+)$;
            include fastcgi_params;

            if ( $uri = /index.php ) {
                    break;
            }

            if ( !-e $document_root$fastcgi_script_name) {
                    return 418;
            }

            #NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_intercept_errors on;
            fastcgi_read_timeout 240;
            fastcgi_pass  127.0.0.1:9000;
}

```

Source: http://wiki.nginx.org/Drupal

(link suggested in https://groups.drupal.org/node/405038)
> 3 votes

# Answer
I got a similar problem : migrating old site with php extension in Urls, and using Redirect module to preserve SEO, nginx returned "*File not found*".

The above solution did not work for my config. Instead that one did the trick :

```
location ~ \.php$|^/update.php {
    #old urls with php extension redirect
    if ($request_uri ~ .*.php.*) {
      error_page 404 =  @rewrite;
    }

    fastcgi_split_path_info ^(.+?\.php)(|/.*)$;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $request_filename;
    fastcgi_intercept_errors on;
    fastcgi_read_timeout 60;
    include fastcgi_params;
    fastcgi_pass 127.0.0.1:9000;
}

```
> 0 votes

---
Tags: 7, redirection
---


title: Change the used PHP version

text:
# Question
Title: Change the used PHP version
I have PHP 5.6 and 7.1 on my system. I want to use PHP 5.6 for the Drupal 7 projects, and PHP 7.1 for the Drupal 8 projects.

I am having problems getting this setup. In the documentation I found that I should set an alias like this in my ~/.zshrc.

```
 alias drush='DRUSH_PHP=/usr/bin/php56 /usr/bin/drush'

```

The problem is that when I start a new terminal and run `drush ev 'print PHP_VERSION'`, it still prints out 7.1.6.

I tried to alias PHP to /usr/bin/php56 but that also did not work.

I also tried the following suggestions (and many others), but they didn't work.

I think this changed in more recent Drush versions, like version 8.1.12 I am using.

Can anyone help me find the correct way to do this in more modern Drush versions?

# Answer
> 0 votes
Did you try in your .profile:

```
export DRUSH_PHP='usr/bin/php56'

```

I think you are mixing up alias with setting an environment variable.

---
Tags: drush
---


title: Auto fill title

text:
# Question
Title: Auto fill title
I'm trying to auto-fill the title a content creation form in Drupal 8 with the user ID of the person creating the node, but I can't seem to get past step 1, which is having the title default to anything. I've made a module and added this code to it:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "new_content_type_node_form") {
    $form['title']['#default_value'] = 'Test12';
  }
}

```

On the creation screen I'm using `dpm` to look at the `$form` var, and it's showing that the title does have a value in #default\_value, and it is Test12, but when the form renders the title field is blank.

It seems like the way to do this in Drupal 7 and earlier was `drupal_set_title()`, but I can't find the equivalent for Drupal 8. Any ideas?

# Answer
The preferred way to do this is to use the create hook.

```
use Drupal\node\NodeInterface;

function mymodule_node_create(NodeInterface $node) {
  if ($node->getType() == 'node_type') {
    $node->title = 'Test12';
  }
}

```

Your code, at least without also additionally checking whether the node is new, will replace the title when editing nodes as well.
> 4 votes

# Answer
Solved by digging a little deeper into the form array:

```
$form['title']['widget'][0]['value']['#default_value'] = 'Test12';

```
> 3 votes

# Answer
You can check also Automatic Entity Label module. (Maybe look through the code)

With this module, you have access to the tokens. https://www.drupal.org/files/images/auto-entity-labels.png
> 1 votes

---
Tags: forms, nodes, 8
---


# Question
Title: How do I get the Commerce order type programmatically?
I have two Commerce **order types**, *order\_a* and *order\_b*, which I created at `/admin/commerce/config/order-types`.

I'm using Commerce 2 on Drupal 8.

I want to process them differently in **hook\_commerce\_order\_presave()**.

How can I programmatically get the order type? When I check the entity type, it only has `commerce_order`, but I want to know what type of commerce order it is. I can't find a method to get the order type specifically.

Here's the code I am using:

```
function MYMODULE_commerce_order_presave(\Drupal\commerce_order\Entity\OrderInterface $entity) {
  if ($entity->isNew()) {
    kint($entity->getEntityTypeId());
    die();

```

# Answer
> 3 votes
The order type is the bundle so you can use `EntityInterface::bundle()` to get that info:

```
$type = $entity->bundle();

```

---
Tags: 8, commerce
---


# Question
Title: Adding multiple buttons on node submit form - every button submits the form
I am adding several buttons to a node form. The result is something that looks like this pastebin. The pastebin is a somewhat truncated version, here is the real short one:

```
$form = [
  '#submit' => [],
  '#actions' => [
   'submit' => [
     '#type' => 'submit',
     '#submit' => ['node_form_submit']
   ],
   'skip_done' => [
     '#type' => 'submit',
     '#submit' => ['skip_done_handler']
   ],
];

```

I *thought* that if `$form['#submit']` was empty then the only submit handlers that would be called are the ones on the respective buttons. I'm either completely wrong in my understanding or I've misconfigured something.

Should this work they way I'm expecting it to? If so, what am I doing wrong?

# Answer
If you leave `$form['#submit']` unset or empty then drupal\_prepare\_form will try to replace it with a submit handler provided by the base form:

```
if (!isset($form['#submit'])) {

// Ensure that modules can rely on #submit being set.
$form['#submit'] = array(

);

// Check for a handler specific to $form_id.
if (function_exists($form_id . '_submit')) {
  $form['#submit'][] = $form_id . '_submit';
}
elseif (isset($form_state['build_info']['base_form_id']) && function_exists($form_state['build_info']['base_form_id'] . '_submit')) {
  $form['#submit'][] = $form_state['build_info']['base_form_id'] . '_submit';
}

```

If you're submitting a node form then `$form_state['build_info']['base_form_id'] . '_submit'` will be equal to `node_form_submit`, which is why it's being called.

In order to prevent `node_form_submit` from being called, you'll need to provide a `$form['#submit']` handler, or define `FORMID_form_submit`, which takes the form `NODETYPE_node_form_submit` for nodes.
> 0 votes

---
Tags: 7, forms
---


# Question
Title: How do I add fields to the email field contact form?
Using Drupal 7, I have a content type that uses the email field module(CCK) so that the page author can enter an email address for readers to mail them. With display suite module together with views contact form module, the saved page displays the site wide contact form. The emailed responses are delivered to the email address that was entered by the content author. That works great.

I wanted to add extra fields and managed to do this with the code below which I added to the template.php file but the code only works with the site wide contact form on example.com/contact

My question: *How can I add those fields to the email field module's contact form as well?*

This is the code I'm using to include the fields in the contact form display:

```
function MYTHEME_form_alter( &$form, &$form_state, $form_id ) {
if( $form_id == 'contact_site_form' ){
    $form['message']['#weight'] = 6;
    $form['copy']['#weight']    = 7;
    $form['phone'] = array(
        '#type' => 'textfield',
        '#title' => t('Phone'),
        '#required' => TRUE,
        '#weight' => 4
    );
    $form['province'] = array(
        '#type' => 'textfield',
        '#title' => t('Province'),
        '#required' => TRUE,
        '#weight' => 5
    );
}
}

```

This is the code I'm using to include the field responses in the email that gets delivered:

```
function MYTHEME_mail_alter(&$message) {
if ($message['id'] == 'contact_page_mail' ||
$message['id'] == 'contact_page_autoreply') {
$message['body'][2] = t('My Phone Number') . ': "' . $message['params'][phone'] . '"';
$message['body'][3] = t('My Province') . ': "' . $message['params']    ['province'] . '"';
}
}

```

# Answer
> 0 votes
You'll need to replace `email_mail_page_form_submit` with your own submit handler, because the Email module doesn't add extra form items to `params` automatically.

Firstly, copy the code from the function `email_mail_page_form_submit` in `email.module` and add phone and province to the params:

```
function MYMODULE_email_mail_page_form_submit($form, &$form_state) {
    // ...

    $params['object'] = $object;
    $params['subject'] = $form_state['values']['subject'];
    $params['name'] = $form_state['values']['name'];
    $params['message'] = $form_state['values']['message'];
    // Add your extra params
    $params['phone'] = $form_state['values']['phone'];
    $params['province'] = $form_state['values']['province'];

    // ...
}

```

Secondly, replace the submit handler on the form:

```
function MYMODULE_form_alter( &$form, &$form_state, $form_id ) {
    // contact form alterations
    // ...

    // email page form alterations
    if ($form_id == 'email_mail_page_form') {
        // add your phone and province fields
        // ...

        // override the email module's submit handler
        $form['submit']['#submit'] = array('MYTHEME_email_mail_page_form_submit');
    }
}

```

Then you can add them to the message as needed in `HOOK_mail_alter`.

---
Tags: forms, emails
---


title: How to hook into user authentication?

text:
# Question
Title: How to hook into user authentication?
I have a 2FA option users can enable. I am currently writing an API layer where I want to preserve this functionality. So far, I haven't been able to hook into authentication. `\Drupal\user\UserAuth` doesn't invoke any hook or event.

Is replacing the *user.auth* service with a custom implementation the only solution?

# Answer
You need to:

1. Create a service provider in your custom module that extends ServiceProviderBase. The name of this class must be your module name, in camel case, with *ServiceProvider* appended. The class must implements `alter()`, which changes the class for the *user.auth* service.

```
public function alter(ContainerBuilder $container) {
  $definition = $container->getDefinition('user.auth');
  $definition->setClass('Drupal\my_module\AuthenticationClass');
}

```
2. `Drupal\my_module\AuthenticationClass` needs to extend `\Drupal\user\UserAuth` and define an `authenticate($username, $password)` method, which returns `TRUE` when the authentication is successful.
> 3 votes

---
Tags: 8
---


# Question
Title: How do I display the domain owner of a node in a view?
I have a view that's generating a block showing upcoming events. On the main site those events might be coming from multiple domains (the site is using Domain Access) and I'd like to show the domain owner as a link to their site sub-domain.

Example:

```
Aug. 14 - Sample Event
Domain Owner (http://owner.mydomain.com)

```

Is there a way that I can add this directly to the view? If not, what is the most effective/correct method for coding that into a view template override?

# Answer
I believe that's relatively straight forward to achieve directly in your view without having to touch templates.

All you need to do is in your view, add a relationship of "Domain Source: Domain Node". This will then provide domain information against your nodes. Then in your fields you will be able to add relevant domain information against the node (using the relationship). So in your case I believe you would want to add the field "Domains: Site Name" and select the relationship in the dropdown. You should then have your site name displayed against your events which would link to the domain.

hope thats helps. Cheers
> 1 votes

# Answer
I know this is an older post but this might be helpful to someone down the line. In the latest version of Drupal, Views and Domain Access as of this posting. **No relationship was required in views.**

1. \****Add the field: Domain Source: Domain Source ID\**** (A little deceiving because it does allow the display of the domain name)
2. Configuring the field there is a "Display As" Dropdown that lets you select either \[Domain ID, Site Name, or Sub Domain\].

**NOTE:** Other Domain Access data is also available without a relationship.

Hope this helps.
> 0 votes

---
Tags: 7, views, domain-access
---