# Question
Title: Webform multistep form previous button asks to fill the required fields
I'm working on a D8 project and I have a multistep webform. Everything works fine but when I click the previous button I'm getting errors that the required fields shouldn't be null in order to go to the previous step. Is this a configuration I need to change or is there a way to avoid it?

Thanks in advance.

# Answer
I found the answer in the module.

Initially, the module doesn't validate when the user previews the form. In order to do that uses the `noValidate` function.

So what I did was, in hook\_form\_alter, to check if I have the previous button and replace the validation function:

```
  if(isset($form['actions']['wizard_prev'])){
    $form['actions']['wizard_prev']['#validate'] = ['::noValidate'];
  }

```
> 0 votes

# Answer
For exactly this purpose the form has the `#limit_validation_errors` attribute. It is an array of values that will be validated instead of the whole form.

So to go back this woul mean an empty array since you do not want to valdiate anything.

But a small issue is that with empty array you will not be able to detect the button that submitted the form so you have to always include it in the list. If you have custom button `#name` use that, if not then use `op` which is the default.

Also these are the `#parents` values, not `#array_parents` so if you have a tree form you have to take that into account. Also using this will not only limit the validation, it will actually strip the submitted values, so if you want to go back but save some information(textfield) from the form, you have to include it as well.

For example:

```
$form['actions']['back'] = [
  '#type' => 'submit',
  '#value' => $this->t('Back'),
  '#submit' => ['::goBackSubmit'],
  '#limit_validation_errors' => [['op']]
];

```

or:

```
$form['actions']['back'] = [
  '#type' => 'submit',
  '#name' => 'go_back_submit',
  '#value' => $this->t('Back'),
  '#submit' => ['::goBackSubmit'],
  '#limit_validation_errors' => [['go_back_submit']]
];

```

or:

```
$form['#tree'] = TRUE;
$form['actions']['back'] = [
  '#type' => 'submit',
  '#name' => 'go_back_submit',
  '#value' => $this->t('Back'),
  '#submit' => ['::goBackSubmit'],
  '#limit_validation_errors' => [['actions', 'go_back_submit']]
];

```
> 1 votes

---
Tags: 8, webforms
---


# Question
Title: How to prevent users (except for admin / editors) from viewing canonical page for content type?
For a certain content type, if you want most users to be able to view the content type (node bundle) when it's loaded on landing pages or on other node pages, but you don't want them to be able to access the route entity.node.canonical for the content type, unless they have an explicit permissions (which would be given to admin role and editor role), what is the best way to do this in Drupal 8?

As an example, let's say a site has a "video" content type, when it's loaded in a block, such as a related videos block, you want everyone to be able to view it, but if a user tries to go to that video's canonical page, they get a 404, unless they have the role with the permission to view it.

This would be for certain bundles of content or media entities that I want to only allow access to in a block, but the canonical page should 404 if the user doesn't have the correct permission.

What is the best strategy to set this up in Drupal 8?

# Answer
In Drupal 7, I believe you could do this with Rules. The Rules module is technically available for Drupal 8, but I couldn't figure out how to use it, so I'll show you how to wire up a custom module that redirects manually based on whatever your criteria is.

---

The basic idea is, in order to do custom redirects, you have to register an EventSubscriber service, subscribe to REQUEST KernelEvent, and then you have access to the entire request object.

In my company's case, I wrote a custom module called "redirect", so that's what this example will use.

First, create a redirect.services.yml file.

```
services:
  redirect.subscriber:
    class: Drupal\redirect\EventSubscriber\RedirectSubscriber
    tags:
      - { name: event_subscriber}

```

Then, create the class referenced above (`Drupal\redirect\EventSubscriber\RedirectSubscriber`) in `src/EventSubscriber/RedirectSubscriber.php`.

```
<?php

namespace Drupal\redirect\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Drupal\node\Entity\Node;

class RedirectSubscriber implements EventSubscriberInterface {

  public function redirect(GetResponseEvent $event) {
    $request = $event->getRequest();
    $baseUrl = $request->getBaseUrl();
    $attr = $request->attributes;
    $roles = \Drupal::currentUser()->getRoles();

    if ($attr !== null) {
      $node = $attr->get('node');
      if ($node !== null && $node instanceof Node) {
        $type = $node->get('type')->getString();
        if ($type == 'seel_lesson_plan' && !in_array('administrator', $roles)) {
          $event->setResponse(
            new RedirectResponse("$baseUrl/url-to-404-page")
          );
        }
      }
    }
  }

  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['redirect'];
    return $events;
  }

}

```

To get a better idea of how this works, read an explanation of registering event subscribers, the official Events API page, and this other Drupal SE question about redirecting content pages.
> 4 votes

# Answer
I marked Lincoln's answer as correct as it got me 90% there. But here's my version, that throws a 404, instead of redirecting.

Add this to your mymodule.services.yml file:

```
services:
  mymodule.canonical_404_subscriber:
    class: Drupal\mymodule\EventSubscriber\KernalEventSubscriber
    tags:
      - { name: event_subscriber}

```

and then in /modules/custom/mymodule/src/EventSubscriber/KernalEventSubscriber.php

Here is the class.

```
/**
 * Class KernalEventSubscriber
 *
 * Restrict access to the canonical pages for certain entities
 * and node bundles.
 */
class KernalEventSubscriber implements EventSubscriberInterface {

  public function checkAccess(GetResponseEvent $event) {

    // Routes to block, regardless of bundle, if
    // user lacks the appropriate role.
    $blocked_routes = [
      'entity.custom_entity1.canonical',
      'entity.media.canonical',
      'entity.custom_entity2.canonical'
    ];

    $allowed_roles = [
      'administrator'
    ];

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

    $current_user_roles = \Drupal::currentUser()->getRoles();

    if (in_array($current_route, $blocked_routes)) {
      if (empty(array_intersect($allowed_roles, $current_user_roles))) {
        throw new NotFoundHttpException();
      }
    }

    // Node bundles to block, if
    // user lacks the appropriate role.
    $node_bundles = [
      'photo_gallery',
      'video'
    ];

    if ($current_route == 'entity.node.canonical') {
      $node = \Drupal::routeMatch()->getParameter('node');
      if (in_array($node->bundle(), $node_bundles) && empty(array_intersect($allowed_roles, $current_user_roles))) {
        throw new NotFoundHttpException();
      }
    }

  }

  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['checkAccess'];
    return $events;
  }

}

```
> 1 votes

---
Tags: 8, routes, users
---


title: Adding Module Config Form Leads to WSOD

text:
# Question
Title: Adding Module Config Form Leads to WSOD
I am trying to create a configuration form for my test Drupal 8 module. I have followed the instructions from the following tutorials:

https://www.drupal.org/docs/8/api/configuration-api/working-with-configuration-forms https://www.drupal.org/docs/8/api/form-api/configformbase-with-simple-configuration-api

Before I followed the instructions in these guides my module worked fine. However, after adding the form, I now get a WSOD when installing the module, with no error in the logs. I know that error reporting is on because I can make intentional mistakes in my module files and an error will be reported in the logs.

My question is: where have I gone wrong? It's hard to figure out a problem when you don't even have a stack trace to follow.

My company\_info.routing.yml file:

```
company_info.content:
  path: '/company_info'
  defaults:
    _controller: '\Drupal\company_info\Controller\AdminController::content'
    _title: 'Hello World'
  requirements:
    _permission: 'access content'

company_info.admin_settings:
  path: '/admin/config/company_info'
  defaults:
    _form: '\Drupal\company_info\Form\AdminSettingsForm'
    _title: 'example'
  requirements:
    _permission: 'administer site configuration'

```

AdminSettingsForm.php:

```
<?php

namespace Drupal\company_info\Controller;

use Drupal\Core\Form\ConfigFormBase;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Form\FormStateInterface;

class AdminSettingsForm extends ConfigFormBase {

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

  /**
   * {@inheritdoc}
   */
  public function getEditableConfigNames() {
    return [
      'company_info.settings',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state,
Request $request = NULL) {
    $config = $this->config('company_info.settings');

    $form['your_message'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Your Message!'),
      '#default_value' => $config->get('your_message'),
    );

    return parent::buildForm($form, $form_state);
  }

  /**
   *
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->config('company_info.settings')
      ->set('your_message', $form_state->getValues('your_message'))
      ->save();

  }
}

```

company\_info.settings.yml

```
your_message: 'Default message here'

```

# Answer
> 1 votes
The namespace on your AdminSettingsForm class is incorrect.
It should be Drupal\company\_info\Form;

---
Tags: 8
---


title: AJAX listener on text_format field

text:
# Question
Title: AJAX listener on text_format field
I am trying to activate an AJAX callback on every change by the user of a text\_format field (which is part of a standard bundle edit form). The name of the field in the snippets below is `field_reponse`

The code works perfectly with other fields (dropdown, textfield), but not for the formatted text areas of type "text\_format".

I suppose it is connected with the post-processing of CKEditor. Am I right ? In any case, is there a workaround?

```
    function MY_MODULE_form_node_shut2_edit_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){

    // Autosave

    $form['field_reponse']['widget'][0]['#ajax'] = array(
            'callback' => 'Drupal\MY_MODULE\Form\FormAutosave::autosave',
            'event' => 'click',
            'wrapper' => 'autosave_ajax_placeholder',
            'progress' => array(
              'type' => 'throbber',
              'message' => NULL,
        ),
    );

  // Add placeholder for Ajax response markup
  $form['autosave_ajax_response'] = array(
            '#type' => 'html_tag',
            '#tag' => 'div',
            '#value' => t('Placeholder for ajax response'),
            '#attributes' => array(
              'class' => array('hidden'),
              'id' => array('autosave_ajax_placeholder'),
        ),
    );
    }

    return $form;
}

```

The callback:

```
<?php

namespace Drupal\MY_MODULE\Form;

use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\Node;

class FormAutosave {

  public static function autosave(array &$form, FormStateInterface $form_state) {

    // Load the shut2 and get changed form element
    $node = $form_state->getFormObject()->getEntity();
    //$curr_values = $form_state->getValues();
    //$triggering_element = $form_state->getTriggeringElement();
    //drupal_set_message($triggering_element));
    // Set and save node with new value for field
    //$node->set($triggering_element, $triggering_element['#value']);
    $node->set('field_reponse', $form_state->getValue('field_reponse'));
    $node->save();

    // Add an Ajax response to avoid error
    $response = [
      '#markup' => t('Sauvegardé automatiquement !'),
    ];
    return $response;

  }

}

```

# Answer
> 0 votes
I think the event should be keyup not click.

---
Tags: 8, ajax, wysiwyg
---


# Question
Title: Hide a particular radio box item in a set
I want to hide a particular item from an entity field that is using a radio box as widget. Can I achieve this using `hook_form_alter()`?

# Answer
To remove the entire field on the form, you can definitely do something like this

```
function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == "form_id_for_form_you_want_to_modify") {
    if (isset($form["field_you_want_to_remove"])) {
      unset($form["field_you_want_to_remove"]);
    }

  }

  return $form;
}

```

To change or remove a specific option on the field you can access and alter it with $form\['field\_your\_field'\]\['und'\]\['#options'\]

(note: If your site is multilingual, you'll need to alter more than just \['und'\]. In this case \['und'\] means undefined language code).

You can also alter the field type with:

```
$form['field_your_field']['#type'] = 'checkboxes';

```

It all depends on what you're trying to accomplish.
> 0 votes

---
Tags: 7
---


# Question
Title: Real world experience in scaling and tuning performance
The website I'm working is allegedly going to have a massive hit rate *soon after launch*. The client is talking about the possibility of around 2500 hits per second over a day or so.

Ignoring the fact that this hit rate is probably wild client optimism and apart from getting the largest servers possible, what is the best way that Drupal should be configured to support a large hit rate.

I've read Scaling the drupal.org Infrastructure, Drupal performance blog, Best Practices for Scaling Drupal and many other pages, but what I'm looking for is real experience of doing this, what works, what doesn't, and what to expect.

# Answer
Markdorison's answer is basically the accepted method of attacking this problem. I'll take that a little further.

When you have Pressflow for D6 or Drupal for D7, Memcached and Varnish all working nicely together you'll need to custom code your VCL file. There are free ones available that make starting points but you always need to play with them.

To get Varnish to work optimally make sure you start it with -s malloc xG rather than the default of -s file /path/to/file. Also with Varnish have Varnish cache static items for as long as you can.

If you have more than one web server remove the ETag from the header sent to Varnish in VCL. I also remove Expires and simply rely on Age and max-age in the headers so get browsers back to the site.

Version 1.5 (as of 3rd March 2011) is still the fastest version of Memcached module from Drupal.org. I typically deploy it using a single bin per server to lower tcp traffic for connections to multiple bins at large scale)

Configure the caching in "Performance" to external and set a max age which will send the correct headers to a caching proxy such as Varnish.

If you can't get certain pages to cache properly in Varnish check out blog posts on the web that detail how to inspect the requests. Here is an example post I wrote a while back: What is stopping Varnish and Drupal Pressflow from caching anonymous users page views

You should pick InnoDB (or one of it's other names from other providers like XtraDB) for MySQL and move all tables into it. Then check out this blog post for basic tuning advice http://www.mysqlperformanceblog.com/2007/11/01/innodb-performance-optimization-basics/

Having a large buffer pool is fundamentally important. When load testing the site turn on the slow query log. You probably want to at first capture queries taking longer than 50msec then tune the queries and repetitively reduce the slow log capture time down until you have most queries running using indexes, and executing fairly quickly.

Other basics involve having APC in for PHP. If you go for fast CGI rather than mod\_php do spend some time trying to make the APC cache shared across the php instances by configuring a good wrapper script. Also make sure that the APC cache is in a memory mapped file to squeeze every last bit out of PHP.
> 45 votes

# Answer
I would recommend starting with Pressflow (if using Drupal 6), Memcache, Varnish, and some form of Content Distribution Network (CDN) such as Akamai. The end result should be as few of those users as possible actually hitting your origin server.

If you have parts of the page that you are not able to cache for non-anonymous users (things that are specific to that user, "Welcome userX" etc.), you can explore options to populate these pieces of the page such as asynchronous callbacks or edge side includes.

If you have a smaller group of internal users (such as a group of editors) that need to be able to view an uncached version of the site, I would recommend exposing an uncached version of your site at a different URL (protected behind a VPN or equivalent if possible).
> 22 votes

# Answer
* **Server side**

+ Install Varnish for caching pages for anonymous users.
    + Install a persistent cache system (Memcached, APC, Memcache).
    + Use a CDN such as Akamai to serve static files (JavaScript, CSS, images).
* **Code Side**

+ Use Pressflow, it allows Varnish to serve cached page for anonymous users.
    + Clean Drupal's watchdog table. Every time a watchdog error gets logged, it consumes CPU resources on the web server and database server. It also increases load time significantly.
    + Implement static and persistent cache strategies until the slow query log comes up clean.
    + Avoid PHP errors that occur within nested foreach loops at all costs.
    + Uninstall unused modules.
    + Turn on caching for Drupal core blocks and Views.
* **Database**

+ Make sure the tables are properly indexed for faster searching.
    + Do not store unnecessary records, a 100 node database will be always accessed faster than a 3 million node database.
> 6 votes

# Answer
I would also listen to this Lullabot podcast about the way they set up the Grammys.com website for a traffic explosion over the course of a week. It was a pretty educational explanation.

http://www.lullabot.com/podcasts/podcast-92-grammycom
> 5 votes

# Answer
While it is very difficult to predict patterns, if you have a fair idea of the traffic levels. Load test your solution. There are a host of different options and a lot will not be possible to predict until you have live traffic, but if you load test as much as possible at least you will have a fair degree of confidence that your setup can handle traffic.

All the tuning in the world won't help if you don't test it first.

This is was a presentation at DC SF about how the economist did it. http://sf2010.drupal.org/conference/sessions/performance-testing-economist-online-using-grinder
> 3 votes

# Answer
For high-traffic websites you should use multiple servers and load balancer or use simply CDN. Also it's very important to cache as much as possible to minimise load on the web servers.

Using Content Delivery Network (CDN) helps to spread out the resources over several domains (domain sharding) which reduces load on the web server.

Using CDN helps with distributed caching and remote acceleration, also helps to mitigate DDoS attacks, because of multiple end-points. It helps with security, because cached content is more more difficult to exploit.

Example providers: Fastly, Rackspace, Akamai, Azure, CloudFlare, Amazon, MaxCDN, Verizon.

Here are some more suggestions:

So your web architecture from the user point of view can look like:

1. User (local browser caching).
2. NGINX or Pound + Varnish (load balancer, reverse proxy as HTTP accelerator).
3. Apache (web server).
4. PHP-FPM (PHP FastCGI Process Manager).
5. MariaDB (database).

---

For Drupal optimization suggestion, check: How do you improve Drupal performance?
> 3 votes

# Answer
Enable two extensions :

* Zend OPcache
* wincache

Your performance will work better.

If you are looking to twig the Zend OPcache and Wincache in Microsoft Azure, at first create a folder name ‘`ini`’ under‘`D:\home\site\`’. Also, create 2 files, ‘`.user.ini`’ and ‘`settings.ini`

Add following configuration in each file :

**.user.ini**

```
[PHP]
post_max_size = 32M
memory_limit = 512M
zend.enable_gc = On
upload_max_filesize = 32M
opcache.enable=1

```

**setting.ini**

```
wincache.ocenabled = 1
wincache.ocachesize = 255

```

Also, add an App Setting to your Web App with the **key** `PHP_INI_SCAN_DIR` and **value** `d:\home\site\ini`

After changing **PHP\_INI\_SYSTEM** restart your web app. If want to know more about twigging configuration, please check Microsoft documentation.

After above setting, my Drupal (Drupal 8.3) site load within 3 seconds.
> 1 votes

# Answer
You could also examine redistributing the load over multiple servers with the aide of a DNS based or software/hardware load balancing solution. This would also bake in fault tolerance.
> 0 votes

---
Tags: caching, performance
---


title: Ajax callback works only once

text:
# Question
Title: Ajax callback works only once
I am using Drupal 7. I want to rebuild a part of form when a button is clicked. My form looks like this:

```
$form['me'] = array(
    '#type' => 'fieldset',
    '#value' => t('name'),
    '#prefix' => '<div id="me-wrapper>',
    '#suffix' => '</div>'
);

```

It contains various text fields and a submit button. The submit button looks like

```
$form['me']['save'] = array(
    '#type' => 'submit',
    '#validate' => array('save_validate'),
    '#submit' => array('save_submit'),
    '#ajax' => array(
        'wrapper' => 'me-wrapper',
        'callback' => 'me_ajax_callback'
    ),
);

```

in the save\_submit function I set `$form_state['rebuild] = true;`

in ajax callback function

```
function me_ajax_callback($form, $form_state) {
    return $form['me'];
}

```

Now, what happens is first time when I click submit, the ajax returns data and replaces the wrapper. But, 2nd time when I do so, I get a POST Internal Server Error 500.

Looking around the Form API, I set `$form_state['no_cache']=true;` in submit handler and that prevents the POST error but still the AJAX response is empty.

It works fine if, I reload the page. So, in short, the first time I hit submit I get an AJAX response. On the second time, the response is blank.

# Answer
Ok, I have solved the issue and this might help someone in future. I was dealing with a form which was actually a collection of various small forms. Each small form had various text fields and submit handler. So, when reloading a small form using AJAX I was setting `$form_state['rebuild'] = true`, this in process rebuilt the whole form in the back. But AJAX callback only rendered a small part of form into the wrapper. So, when I pressed the button again there was post error as Drupal was expecting values in new rendered form whereas it got a mixture of Old and new form. It happens because Drupal while rendering a form into HTML adds id to it, e.g., `id = edit-save` but when we rebuild it without reloading the page, it changes to something like `id = edit-save--2` and which keeps on to increment every time it's rebuilt. So, if your form needs rebuilding, reload the whole form else set `$form_state['rebuild'] = false` and that should allow subsequent AJAX calls without any post error.
> 2 votes

---
Tags: 7, forms, ajax
---


title: How to reference a specific field?

text:
# Question
Title: How to reference a specific field?
I need to link/sync a paragraph with another field on the parent node of this paragraph.

### Background:

All my nodes have some node-type-specific fields for strict-structured data (e.g. a product node has product image & price; a location node has a geolocation field). All nodes share one huge, repeating paragraph "generic content" field with a lot of paragraph types for unstructered data (marketing texts, emotional images, bullet points,...). Basically that paragraph is used as a sort of site building tool.

### Requirement:

I now need to display the node's structured data fields within the "generic content" paragraph field, so that editors can mix and move the structered content with the generic content paragraphs.

### Didn't work:

My initial idea was to create a paragraph with an entity reference to field types where editors could select the basefield. However, that didn't really work because I can't limit the autocomplete to fields of the current node, leading to a unusable list with a lot of invalid entries.

### Question:

Is there any way to create references to fields within a node? It has to be a mouse- and editor-friendly solution, my editors are trained in the Drupal Admin, but they have no access to code.

# Answer
Technically, you could add a reference field to field config entities. But you can't limit the options there and I'm sure you don't want to allow all the fields, and you need custom theming logic for this anyway. That would just allow you to select the field name.

You can't link to a field *value*, the combination of entity and field doesn't have its own identifier.

If I understand you correctly, then the simplest option is to make a custom list field with allowed values like this:

field\_name\_a|Field A field\_name\_b|Field B

With as many fields as you need. You could also register a allowed options callback and try to dynamically limit the options based the current page/node type, but that's a bit tricky.

Then you need custom logic in preprocess/twig templates for that paragraph type that gets the value for the selected field from the parent of the paragraph and renders it
> 2 votes

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


# Question
Title: Benefit of processing multiple entities at once?
I am about to port renderkit to Drupal 8.

The D7 version contains an interface EntityDisplayInterface, which builds render arrays from entities.

In the D7 version, this contains one method `buildEntities($entity_type, $entities);` which allows to process multiple entities at once. The idea here was that this could speed up performance.

For D8, I wonder if this is still relevant. E.g. it seems that D8 views really renders each entity separately. And even though there is EntityViewBuilder::viewMultiple(), this really does most of its processing within the foreach(), so separate per entity.

So.. should I drop the `buildEntities()` method in D8, and only leave `buildEntity()`?

# Answer
buildMultiple() exists, but it was done before we introduced render caching to entities and with that, lazy entity rendering/building. Now we don't really need multiple processing.

See https://www.drupal.org/node/2843565 for a discussion about that and the conclusion that we don't really need buildMultiple() anymore.

The idea is that if we render a page with 20 articles, then rendering them all separately is slightly slower on the first request. However, if you save one of those articles, or create a new one, then when accessing that page again, only one needs to be rendered (again), the others can be returned from the cache.

Whether or not a multiple API makes sense for you depends on how it will be called, if you expect it to be called on multiple entities, then can make sense, if not, then probably not.
> 3 votes

---
Tags: 8, entities
---


# Question
Title: What is the cause of this PHP exception?
When I disable the *Database logging* or the *Views UI* module from a Drupal 8 site, I get the following error.

> Drupal\Component\Serialization\Exception\InvalidDataTypeException: yaml\_parse(): end of stream reached without finding document 0 in Drupal\Component\Serialization\YamlPecl::errorHandler()

What might be causing it?

# Answer
it was faulty yaml file which caused the php exception. Follow script helped `"for filename in `find . -type f -name "*.yml"`
do
 php -r '
 $filename = "'$filename'";
 $string = file_get_contents($filename);
 $parsed = yaml_parse($string);
 if ($parsed === FALSE)
 {
 echo " $filename is borked \n";
 }'
done"` source https://docs.acquia.com/article/pecl-yaml-serialization-errors
> 0 votes

# Answer
looks like you have an invalid yaml file. you have a syntax error in it so the yaml library cannot "see" or parse the internal yaml document properly.
> 0 votes

---
Tags: 8
---


title: Refresh View in block using js

text:
# Question
Title: Refresh View in block using js
I have two different blocks. One has a form and the other one is a view with some files uploaded from the form above.

On submit of the form I need to update the view results. I thought I could do it using js but I can't make it work.

Please check my code. Any advice would be helpful!

```
Drupal.behaviors.myViewsRefresh = {
    attach: function( context , settings) {
        var viewName = 'application_documents';

        // Your views should be Ajax enabled
        var instances = Drupal.views.instances;
        var myViews;

        // then simply need to iterate through the various
        // views instances name to find the view
        $.each( instances , function getInstance( index, element){
            if(element.settings.view_name == viewName ){
                myViews = '.view-dom-id-' + element.settings.view_dom_id;
            }
        });

        $(document).once('mysubmitbutton').ajaxComplete(function(event, xhr, settings){
            if(typeof myViews !== 'undefined'){
                $(myViews).trigger('RefreshView');
            }
        });

    }
}

```

I can get into the ajaxComplete but the view doesn't reload. The view id is correct.

Thank you in advance.

# Answer
The way you construct your `myViews` variable seems to be the reason this doesn't work for you.

What worked for me was changing this:

```
            myViews = '.view-dom-id-' + element.settings.view_dom_id;

```

to

```
            myViews = '.js-view-dom-id-' + element.settings.view_dom_id;

```

I just tried a simple version of that without any form submiting, simply calling this from my browser's console:

```
jQuery('.js-view-dom-id-c58e9660da223aaf7c1645b2746e0b2e16f6a2f3e1de74c8533e6ad6117613db').trigger('RefreshView')

```

and it worked as expected. As a final remark and as is commented in the code you provided, your views should be Ajax enabled, otherwise, this will not work.

Good luck!

P.S.: The most relevant piece of information from the codebase (this comment says it all):

```
// Add a trigger to update this view specifically. In order to trigger a
// refresh use the following code.
//
// @code
// $('.view-name').trigger('RefreshView');
// @endcode

```

(http://cgit.drupalcode.org/drupal/tree/core/modules/views/js/ajax\_view.es6.js#n94)
> 9 votes

---
Tags: views, 8, ajax
---


# Question
Title: What drush version I can use that doesn't require composer?
I try to use drush on the server that is behind corporate firewall, and downloads from many sites are blocked. In particular, when I run "composer diag", it hangs for the long time on the line "Checking http connectivity to packagist: http://packagist.org/" and then prints "The "http://packagist.org/packages.json" file could not be downloaded: failed to open stream". I saw similar blockage when trying to use wget with a number of URLs, including ftp-origin.drupal.org/files/projects/.

So how far back should I go to get the version of drush that doesn't use composer and will not try to update itself on the first run? I understand that some functionality will be missing, but at least basic functions like "drush cc", "drush en", "drush dis", etc. I will be able to use.

# Answer
I believe any version on this page that is released as a `phar` file: https://github.com/drush-ops/drush/releases

Super old versions of Drush (unsupported) were not released as single phar files. The current version of drush (version 9) seems to be geared to released/maintained via Composer only; and no longer Pecl or other distribution channels.
> 1 votes

---
Tags: drush
---


title: Capture IP and URL of referrer

text:
# Question
Title: Capture IP and URL of referrer
This code is adapted from /*core/modules/statistics/statistics.php*. It uses a JavaScript file that sends an uncached POST request to the server (to ensure the code within gets run for every page request).

I want my code within to capture the IP and URL of the referrer. I've tried many things to grab this information and write it to the log, but no luck.

Whatever I do, I get a variation on `Error: Call to a member function *something* on null in...`. Like, I'm not getting anything. For example, the below throws: `Error: Call to a member function getClientIp() on null in main() (line 26 of...`.

Any ideas?

```
<?php

/**
 * @file
 * Store access data.
 */

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
// use Symfony\Component\HttpFoundation\RequestStack;
// use Symfony\Component\HttpFoundation;

chdir('../..');

$autoloader = require_once 'autoload.php';

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

// $container = $kernel->getContainer;

// $request = $kernel->getContainer()->get('request_stack')->getCurrentRequest();
// $request = $kernel->requestStack->getCurrentRequest();

// $url = \Drupal::request()->server->get('HTTP_REFERER');

// $hostname = $request->getClientIP();
// $hostname = \Drupal::request()->getClientIp();

\Drupal::logger('sitelog')->notice(REQUEST_TIME);

```

---

Working code:

```
<?php

/**
 * @file
 * Store access data.
 */

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

chdir('../..');

$autoloader = require_once 'autoload.php';

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

$hostname = $request->getClientIP();
$url = $request->server->get('HTTP_REFERER');

\Drupal::logger('sitelog')->notice($hostname . ' - ' . $url);

```

# Answer
You are almost there, here is a rewritten version of your code that should work:

```
<?php

/**
 * @file
 * Store access data.
 */

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$autoloader = require_once 'autoload.php';

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

$client_ip = $request->getClientIP();
$headers = $request->server->getHeaders();
$referer_url = isset($headers['HTTP_REFERER']) ? $headers['HTTP_REFERER'] : '';

\Drupal::logger('sitelog')->notice($referer_url . '::' . $client_ip);

```

The main idea of the rewrite is to keep a reference to the HttpFoundation\Request from the very beginning and use if to get access to the parameters you want.

P.S.: Loading Symfony's components as well as booting Drupal's kernel may be an overkill for getting the client's IP and referer url, a simple php script could do that for you and write logs in a file.
> 4 votes

# Answer
You cannot get the API to automatically get the IP Address of the referrer. You will need to do a DNS Lookup after getting the authority of the referrer.

See a similar question here and answer. Notice that two below this answer the asker shows his implementation of how to get the IP address using DNS lookup.

https://www.experts-exchange.com/questions/26330010/How-do-I-get-the-referral-IP-address.html#a33211593

Have you successfully completed a request using this script yet?
> 0 votes

---
Tags: 8
---


title: Why don't I get a module dependencies?

text:
# Question
Title: Why don't I get a module dependencies?
I've got very little knowledge but I've managed to install Drupal Commerce 2 on a Debian 9 with the command

`composer create-project drupalcommerce/project-base mysite --stability dev`

I started off with a minimal debian installation so I really had to look around to resolve any dependencies just to get this composer command to work! It's not as straight-forward as the manual seems to suggest. Anyways, I've got a site installed now and besides a few suggestions from composer, I don't think I have received any errors. I can browse to the installed site with my web browser but I'm stuck on page 2 (Verify requirements) where it says

> **REQUIRED MODULES: Not found Commerce\_log, Commerce\_tax**

Where do I get the modules from and how? Isn't composer supposed to resolve all dependencies and have these modules installed automatically?

Besides the error that stops me from continuing the creation of the site, I get a warning on CLEAN URLS (disabled).

Here is the log of my composer installation:

```
composer create-project drupalcommerce/project-base mystore --stability dev --verbose
Installing drupalcommerce/project-base (8.x-dev 44c1fe21fbd9155a294c4b8fe0eaac0195a0f585)
  - Installing drupalcommerce/project-base (8.x-dev 44c1fe2): Cloning 44c1fe21fbd9155a294c4b8fe0eaac0195a0f585 from cache
Created project in mystore
> pre-update-cmd: DrupalProject\composer\ScriptHandler::checkComposerVersion
Loading composer repositories with packagUpdating dependencies (including require-dev)         Dependency resolution completed in 9.290 seconds
Analyzed 11720 packages to resolve dependencies
Analyzed 485242 rules to resolve dependencies
Dependency resolution completed in 0.000 seconds
Package operations: 122 installs, 0 updates, 0 removals
Installs: cweagans/composer-patches:1.6.1, drupal-composer/drupal-scaffold:2.3.0, composer/installers:v1.4.0, symfony/yaml:v2.8.26, symfony/finder:v3.3.6, drupal/console-extend-plugin:0.9.2, drupalcommerce/commerce_base:dev-8.x-1.x 241bcf3, zendframework/zend-stdlib:3.1.0, zendframework/zend-escaper:2.5.2, zendframework/zend-feed:2.8.0, psr/http-message:1.0.1, zendframework/zend-diactoros:1.4.0, twig/twig:v1.34.4, symfony/polyfill-mbstring:v1.4.0, symfony/translation:v2.8.26, ircmaxell/password-compat:v1.0.4, symfony/polyfill-php55:v1.4.0, symfony/polyfill-php54:v1.4.0, symfony/http-foundation:v2.8.26, symfony/psr-http-message-bridge:v1.0.0, symfony/polyfill-iconv:v1.4.0, symfony/event-dispatcher:v2.8.26, psr/log:1.0.2, symfony/debug:v2.8.26, symfony/http-kernel:v2.8.26, symfony/routing:v2.8.26, symfony-cmf/routing:1.4.1, stack/builder:v1.0.4, paragonie/random_compat:v2.0.10, masterminds/html5:2.2.2, guzzlehttp/psr7:1.4.2, guzzlehttp/promises:v1.3.1, guzzlehttp/guzzle:6.3.0, doctrine/lexer:v1.0.1, egulias/email-validator:1.2.14, easyrdf/easyrdf:0.9.1, doctrine/inflector:v1.2.0, doctrine/collections:v1.4.0, doctrine/cache:v1.6.2, doctrine/annotations:v1.2.7, doctrine/common:v2.7.3, composer/semver:1.4.2, asm89/stack-cors:1.1.0, symfony/validator:v2.8.26, symfony/serializer:v2.8.26, symfony/process:v2.8.26, symfony/dependency-injection:v2.8.26, symfony/console:v2.8.26, symfony/polyfill-apcu:v1.4.0, symfony/class-loader:v2.8.26, drupal/core:8.3.6, drupal/admin_toolbar:1.19.0, psr/simple-cache:1.0.0, psr/cache:1.0.1, symfony/cache:v3.3.6, symfony/expression-language:v3.3.6, symfony/dom-crawler:v3.3.6, symfony/css-selector:v2.8.26, jakub-onderka/php-console-color:0.1, jakub-onderka/php-console-highlighter:v0.3.2, dnoegel/php-xdg-base-dir:0.1, nikic/php-parser:v3.1.0, symfony/var-dumper:v3.3.6, psy/psysh:v0.8.11, gabordemooij/redbean:v4.3.4, vlucas/phpdotenv:v2.4.0, drupal/console-dotenv:0.3.0, webmozart/assert:1.2.0, webmozart/path-util:2.3.0, webflo/drupal-finder:0.3.0, symfony/filesystem:v3.3.6, symfony/config:v3.2.13, stecman/symfony-console-completion:0.7.0, drupal/console-en:1.0.0, dflydev/placeholder-resolver:v1.0.2, dflydev/dot-access-data:v1.1.0, dflydev/dot-access-configuration:v1.0.2, drupal/console-core:1.0.0, alchemy/zippy:0.4.3, drupal/console:1.0.0, commerceguys/intl:v0.7.4, drupal/state_machine:1.0.0-beta3, drupal/entity:dev-1.x 6bf9d50, drupal/profile:dev-1.x 75637f8, drupal/entity_reference_revisions:1.3.0, drupal/inline_entity_form:1.0.0-beta1, commerceguys/enum:v1.0, commerceguys/addressing:v1.0.0-beta3, drupal/address:1.1.0, drupal/commerce:2.0.0-beta3, drupal/search_api:1.3.0, html2text/html2text:4.0.1, swiftmailer/swiftmailer:v5.4.8, drupal/mailsystem:4.1.0, drupal/swiftmailer:1.0.0-beta1, symfony/browser-kit:v3.3.6, fabpot/goutte:v3.2.1, behat/mink:v1.7.1, behat/mink-browserkit-driver:v1.3.2, behat/mink-goutte-driver:v1.2.1, jcalderonzumba/gastonjs:v1.0.3, jcalderonzumba/mink-phantomjs-driver:v0.3.3, mikey179/vfsStream:v1.6.5, sebastian/version:1.0.6, sebastian/global-state:1.1.1, sebastian/recursion-context:1.0.5, sebastian/exporter:1.2.2, sebastian/environment:1.3.8, sebastian/diff:1.4.3, sebastian/comparator:1.2.4, doctrine/instantiator:1.0.5, phpunit/php-text-template:1.2.1, phpunit/phpunit-mock-objects:2.3.8, phpunit/php-timer:1.0.9, phpunit/php-file-iterator:1.4.2, phpunit/php-token-stream:1.4.11, phpunit/php-code-coverage:2.2.4, phpdocumentor/reflection-common:1.0, phpdocumentor/type-resolver:0.3.0, phpdocumentor/reflection-docblock:3.2.2, phpspec/prophecy:v1.7.0, phpunit/phpunit:4.8.36
  - Installing cweagans/composer-patches (1.6.1): Downloading (100%)
 Extracting archiveNo patches found for cweagans/composer-patches.
Patching is disabled. Skipping.
  - Installing drupal-composer/drupal-scaffold (2.3.0): Downloading (100%)
 Extracting archiveNo patches found for drupal-composer/drupal-scaffold.
Patching is disabled. Skipping.
  - Installing composer/installers (v1.4.0): Downloading (100%)
 Extracting archiveNo patches found for composer/installers.
Patching is disabled. Skipping.
  - Installing symfony/yaml (v2.8.26): Downloading (100%)
 Extracting archiveNo patches found for symfony/yaml.
Patching is disabled. Skipping.
  - Installing symfony/finder (v3.3.6): Downloading (100%)
 Extracting archiveNo patches found for symfony/finder.
Patching is disabled. Skipping.
  - Installing drupal/console-extend-plugin (0.9.2): Downloading (100%)
 Extracting archiveNo patches found for drupal/console-extend-plugin.
Patching is disabled. Skipping.
  - Installing drupalcommerce/commerce_base (dev-8.x-1.x 241bcf3): Cloning 241bcf336c92abaac8275807ce552bea846bbee0 from cache
No patches found for drupalcommerce/commerce_base.
Patching is disabled. Skipping.
  - Installing zendframework/zend-stdlib (3.1.0): Downloading (100%)
 Extracting archiveNo patches found for zendframework/zend-stdlib.
Patching is disabled. Skipping.
  - Installing zendframework/zend-escaper (2.5.2): Downloading (100%)
 Extracting archiveNo patches found for zendframework/zend-escaper.
Patching is disabled. Skipping.
  - Installing zendframework/zend-feed (2.8.0): Downloading (100%)
 Extracting archiveNo patches found for zendframework/zend-feed.
Patching is disabled. Skipping.
  - Installing psr/http-message (1.0.1): Downloading (100%)
 Extracting archiveNo patches found for psr/http-message.
Patching is disabled. Skipping.
  - Installing zendframework/zend-diactoros (1.4.0): Downloading (100%)
 Extracting archiveNo patches found for zendframework/zend-diactoros.
Patching is disabled. Skipping.
  - Installing twig/twig (v1.34.4): Downloading (100%)
 Extracting archiveNo patches found for twig/twig.
Patching is disabled. Skipping.
  - Installing symfony/polyfill-mbstring (v1.4.0): Downloading (100%)
 Extracting archiveNo patches found for symfony/polyfill-mbstring.
Patching is disabled. Skipping.
  - Installing symfony/translation (v2.8.26): Downloading (100%)
 Extracting archiveNo patches found for symfony/translation.
Patching is disabled. Skipping.
  - Installing ircmaxell/password-compat (v1.0.4): Downloading (100%)
 Extracting archiveNo patches found for ircmaxell/password-compat.
Patching is disabled. Skipping.
  - Installing symfony/polyfill-php55 (v1.4.0): Downloading (100%)
 Extracting archiveNo patches found for symfony/polyfill-php55.
Patching is disabled. Skipping.
  - Installing symfony/polyfill-php54 (v1.4.0): Downloading (100%)
 Extracting archiveNo patches found for symfony/polyfill-php54.
Patching is disabled. Skipping.
  - Installing symfony/http-foundation (v2.8.26): Downloading (100%)
 Extracting archiveNo patches found for symfony/http-foundation.
Patching is disabled. Skipping.
  - Installing symfony/psr-http-message-bridge (v1.0.0): Downloading (100%)
 Extracting archiveNo patches found for symfony/psr-http-message-bridge.
Patching is disabled. Skipping.
  - Installing symfony/polyfill-iconv (v1.4.0): Downloading (100%)
 Extracting archiveNo patches found for symfony/polyfill-iconv.
Patching is disabled. Skipping.
  - Installing symfony/event-dispatcher (v2.8.26): Downloading (100%)
 Extracting archiveNo patches found for symfony/event-dispatcher.
Patching is disabled. Skipping.
  - Installing psr/log (1.0.2): Downloading (100%)
 Extracting archiveNo patches found for psr/log.
Patching is disabled. Skipping.
  - Installing symfony/debug (v2.8.26): Downloading (100%)
 Extracting archiveNo patches found for symfony/debug.
Patching is disabled. Skipping.
  - Installing symfony/http-kernel (v2.8.26): Downloading (100%)
 Extracting archiveNo patches found for symfony/http-kernel.
Patching is disabled. Skipping.
  - Installing symfony/routing (v2.8.26): Downloading (100%)
 Extracting archiveNo patches found for symfony/routing.
Patching is disabled. Skipping.
  - Installing symfony-cmf/routing (1.4.1): Downloading (100%)
 Extracting archiveNo patches found for symfony-cmf/routing.
Patching is disabled. Skipping.
  - Installing stack/builder (v1.0.4): Downloading (100%)
 Extracting archiveNo patches found for stack/builder.
Patching is disabled. Skipping.
  - Installing paragonie/random_compat (v2.0.10): Downloading (100%)
 Extracting archiveNo patches found for paragonie/random_compat.
Patching is disabled. Skipping.
  - Installing masterminds/html5 (2.2.2): Downloading (100%)
 Extracting archiveNo patches found for masterminds/html5.
Patching is disabled. Skipping.
  - Installing guzzlehttp/psr7 (1.4.2): Downloading (100%)
 Extracting archiveNo patches found for guzzlehttp/psr7.
Patching is disabled. Skipping.
  - Installing guzzlehttp/promises (v1.3.1): Downloading (100%)
 Extracting archiveNo patches found for guzzlehttp/promises.
Patching is disabled. Skipping.
  - Installing guzzlehttp/guzzle (6.3.0): Downloading (100%)
 Extracting archiveNo patches found for guzzlehttp/guzzle.
Patching is disabled. Skipping.
  - Installing doctrine/lexer (v1.0.1): Downloading (100%)
 Extracting archiveNo patches found for doctrine/lexer.
Patching is disabled. Skipping.
  - Installing egulias/email-validator (1.2.14): Downloading (100%)
 Extracting archiveNo patches found for egulias/email-validator.
Patching is disabled. Skipping.
  - Installing easyrdf/easyrdf (0.9.1): Downloading (100%)
 Extracting archiveNo patches found for easyrdf/easyrdf.
Patching is disabled. Skipping.
  - Installing doctrine/inflector (v1.2.0): Downloading (100%)
 Extracting archiveNo patches found for doctrine/inflector.
Patching is disabled. Skipping.
  - Installing doctrine/collections (v1.4.0): Downloading (100%)
 Extracting archiveNo patches found for doctrine/collections.
Patching is disabled. Skipping.
  - Installing doctrine/cache (v1.6.2): Downloading (100%)
 Extracting archiveNo patches found for doctrine/cache.
Patching is disabled. Skipping.
  - Installing doctrine/annotations (v1.2.7): Downloading (100%)
 Extracting archiveNo patches found for doctrine/annotations.
Patching is disabled. Skipping.
  - Installing doctrine/common (v2.7.3): Downloading (100%)
 Extracting archiveNo patches found for doctrine/common.
Patching is disabled. Skipping.
  - Installing composer/semver (1.4.2): Downloading (100%)
 Extracting archiveNo patches found for composer/semver.
Patching is disabled. Skipping.
  - Installing asm89/stack-cors (1.1.0): Downloading (100%)
 Extracting archiveNo patches found for asm89/stack-cors.
Patching is disabled. Skipping.
  - Installing symfony/validator (v2.8.26): Downloading (100%)
 Extracting archiveNo patches found for symfony/validator.
Patching is disabled. Skipping.
  - Installing symfony/serializer (v2.8.26): Downloading (100%)
 Extracting archiveNo patches found for symfony/serializer.
Patching is disabled. Skipping.
  - Installing symfony/process (v2.8.26): Downloading (100%)
 Extracting archiveNo patches found for symfony/process.
Patching is disabled. Skipping.
  - Installing symfony/dependency-injection (v2.8.26): Downloading (100%)
 Extracting archiveNo patches found for symfony/dependency-injection.
Patching is disabled. Skipping.
  - Installing symfony/console (v2.8.26): Downloading (100%)
 Extracting archiveNo patches found for symfony/console.
Patching is disabled. Skipping.
  - Installing symfony/polyfill-apcu (v1.4.0): Downloading (100%)
 Extracting archiveNo patches found for symfony/polyfill-apcu.
Patching is disabled. Skipping.
  - Installing symfony/class-loader (v2.8.26): Downloading (100%)
 Extracting archiveNo patches found for symfony/class-loader.
Patching is disabled. Skipping.
  - Installing drupal/core (8.3.6): Downloading (100%)
 Extracting archiveNo patches found for drupal/core.
Patching is disabled. Skipping.
  - Installing drupal/admin_toolbar (1.19.0): Downloading (100%)
 Extracting archiveNo patches found for drupal/admin_toolbar.
Patching is disabled. Skipping.
  - Installing psr/simple-cache (1.0.0): Downloading (100%)
 Extracting archiveNo patches found for psr/simple-cache.
Patching is disabled. Skipping.
  - Installing psr/cache (1.0.1): Downloading (100%)
 Extracting archiveNo patches found for psr/cache.
Patching is disabled. Skipping.
  - Installing symfony/cache (v3.3.6): Downloading (100%)
 Extracting archiveNo patches found for symfony/cache.
Patching is disabled. Skipping.
  - Installing symfony/expression-language (v3.3.6): Downloading (100%)
 Extracting archiveNo patches found for symfony/expression-language.
Patching is disabled. Skipping.
  - Installing symfony/dom-crawler (v3.3.6): Downloading (100%)
 Extracting archiveNo patches found for symfony/dom-crawler.
Patching is disabled. Skipping.
  - Installing symfony/css-selector (v2.8.26): Downloading (100%)
 Extracting archiveNo patches found for symfony/css-selector.
Patching is disabled. Skipping.
  - Installing jakub-onderka/php-console-color (0.1): Downloading (100%)
 Extracting archiveNo patches found for jakub-onderka/php-console-color.
Patching is disabled. Skipping.
  - Installing jakub-onderka/php-console-highlighter (v0.3.2): Downloading (100%)
 Extracting archiveNo patches found for jakub-onderka/php-console-highlighter.
Patching is disabled. Skipping.
  - Installing dnoegel/php-xdg-base-dir (0.1): Downloading (100%)
 Extracting archiveNo patches found for dnoegel/php-xdg-base-dir.
Patching is disabled. Skipping.
  - Installing nikic/php-parser (v3.1.0): Downloading (100%)
 Extracting archiveNo patches found for nikic/php-parser.
Patching is disabled. Skipping.
  - Installing symfony/var-dumper (v3.3.6): Downloading (100%)
 Extracting archiveNo patches found for symfony/var-dumper.
Patching is disabled. Skipping.
  - Installing psy/psysh (v0.8.11): Downloading (100%)
 Extracting archiveNo patches found for psy/psysh.
Patching is disabled. Skipping.
  - Installing gabordemooij/redbean (v4.3.4): Downloading (100%)
 Extracting archiveNo patches found for gabordemooij/redbean.
Patching is disabled. Skipping.
  - Installing vlucas/phpdotenv (v2.4.0): Downloading (100%)
 Extracting archiveNo patches found for vlucas/phpdotenv.
Patching is disabled. Skipping.
  - Installing drupal/console-dotenv (0.3.0): Downloading (100%)
 Extracting archiveNo patches found for drupal/console-dotenv.
Patching is disabled. Skipping.
  - Installing webmozart/assert (1.2.0): Downloading (100%)
 Extracting archiveNo patches found for webmozart/assert.
Patching is disabled. Skipping.
  - Installing webmozart/path-util (2.3.0): Downloading (100%)
 Extracting archiveNo patches found for webmozart/path-util.
Patching is disabled. Skipping.
  - Installing webflo/drupal-finder (0.3.0): Downloading (100%)
 Extracting archiveNo patches found for webflo/drupal-finder.
Patching is disabled. Skipping.
  - Installing symfony/filesystem (v3.3.6): Downloading (100%)
 Extracting archiveNo patches found for symfony/filesystem.
Patching is disabled. Skipping.
  - Installing symfony/config (v3.2.13): Downloading (100%)
 Extracting archiveNo patches found for symfony/config.
Patching is disabled. Skipping.
  - Installing stecman/symfony-console-completion (0.7.0): Downloading (100%)
 Extracting archiveNo patches found for stecman/symfony-console-completion.
Patching is disabled. Skipping.
  - Installing drupal/console-en (1.0.0): Downloading (100%)
 Extracting archiveNo patches found for drupal/console-en.
Patching is disabled. Skipping.
  - Installing dflydev/placeholder-resolver (v1.0.2): Downloading (100%)
 Extracting archiveNo patches found for dflydev/placeholder-resolver.
Patching is disabled. Skipping.
  - Installing dflydev/dot-access-data (v1.1.0): Downloading (100%)
 Extracting archiveNo patches found for dflydev/dot-access-data.
Patching is disabled. Skipping.
  - Installing dflydev/dot-access-configuration (v1.0.2): Downloading (100%)
 Extracting archiveNo patches found for dflydev/dot-access-configuration.
Patching is disabled. Skipping.
  - Installing drupal/console-core (1.0.0): Downloading (100%)
 Extracting archiveNo patches found for drupal/console-core.
Patching is disabled. Skipping.
  - Installing alchemy/zippy (0.4.3): Downloading (100%)
 Extracting archiveNo patches found for alchemy/zippy.
Patching is disabled. Skipping.
  - Installing drupal/console (1.0.0): Downloading (100%)
 Extracting archiveNo patches found for drupal/console.
Patching is disabled. Skipping.
  - Installing commerceguys/intl (v0.7.4): Downloading (100%)
 Extracting archiveNo patches found for commerceguys/intl.
Patching is disabled. Skipping.
  - Installing drupal/state_machine (1.0.0-beta3): Downloading (100%)
 Extracting archiveNo patches found for drupal/state_machine.
Patching is disabled. Skipping.
  - Installing drupal/entity (dev-1.x 6bf9d50): Cloning 6bf9d5039a2fa4a9cd596d0a3d6b41b5d70f04cb from cache
No patches found for drupal/entity.
Patching is disabled. Skipping.
  - Installing drupal/profile (dev-1.x 75637f8): Cloning 75637f87825aed9bb0cad0d912ee3bbe88383610 from cache
No patches found for drupal/profile.
Patching is disabled. Skipping.
  - Installing drupal/entity_reference_revisions (1.3.0): Downloading (100%)
 Extracting archiveNo patches found for drupal/entity_reference_revisions.
Patching is disabled. Skipping.
  - Installing drupal/inline_entity_form (1.0.0-beta1): Downloading (100%)
 Extracting archiveNo patches found for drupal/inline_entity_form.
Patching is disabled. Skipping.
  - Installing commerceguys/enum (v1.0): Downloading (100%)
 Extracting archiveNo patches found for commerceguys/enum.
Patching is disabled. Skipping.
  - Installing commerceguys/addressing (v1.0.0-beta3): Downloading (100%)
 Extracting archiveNo patches found for commerceguys/addressing.
Patching is disabled. Skipping.
  - Installing drupal/address (1.1.0): Downloading (100%)
 Extracting archiveNo patches found for drupal/address.
Patching is disabled. Skipping.
  - Installing drupal/commerce (2.0.0-beta3): Downloading (100%)
 Extracting archiveNo patches found for drupal/commerce.
Patching is disabled. Skipping.
  - Installing drupal/search_api (1.3.0): Downloading (100%)
 Extracting archiveNo patches found for drupal/search_api.
Patching is disabled. Skipping.
  - Installing html2text/html2text (4.0.1): Downloading (100%)
 Extracting archiveNo patches found for html2text/html2text.
Patching is disabled. Skipping.
  - Installing swiftmailer/swiftmailer (v5.4.8): Downloading (100%)
 Extracting archiveNo patches found for swiftmailer/swiftmailer.
Patching is disabled. Skipping.
  - Installing drupal/mailsystem (4.1.0): Downloading (100%)
 Extracting archiveNo patches found for drupal/mailsystem.
Patching is disabled. Skipping.
  - Installing drupal/swiftmailer (1.0.0-beta1): Downloading (100%)
 Extracting archiveNo patches found for drupal/swiftmailer.
Patching is disabled. Skipping.
  - Installing symfony/browser-kit (v3.3.6): Downloading (100%)
 Extracting archiveNo patches found for symfony/browser-kit.
Patching is disabled. Skipping.
  - Installing fabpot/goutte (v3.2.1): Downloading (100%)
 Extracting archiveNo patches found for fabpot/goutte.
Patching is disabled. Skipping.
  - Installing behat/mink (v1.7.1): Downloading (100%)
 Extracting archiveNo patches found for behat/mink.
Patching is disabled. Skipping.
  - Installing behat/mink-browserkit-driver (v1.3.2): Downloading (100%)
 Extracting archiveNo patches found for behat/mink-browserkit-driver.
Patching is disabled. Skipping.
  - Installing behat/mink-goutte-driver (v1.2.1): Downloading (100%)
 Extracting archiveNo patches found for behat/mink-goutte-driver.
Patching is disabled. Skipping.
  - Installing jcalderonzumba/gastonjs (v1.0.3): Downloading (100%)
 Extracting archiveNo patches found for jcalderonzumba/gastonjs.
Patching is disabled. Skipping.
  - Installing jcalderonzumba/mink-phantomjs-driver (v0.3.3): Downloading (100%)
 Extracting archiveNo patches found for jcalderonzumba/mink-phantomjs-driver.
Patching is disabled. Skipping.
  - Installing mikey179/vfsstream (v1.6.5): Downloading (100%)
 Extracting archiveNo patches found for mikey179/vfsstream.
Patching is disabled. Skipping.
  - Installing sebastian/version (1.0.6): Downloading (100%)
 Extracting archiveNo patches found for sebastian/version.
Patching is disabled. Skipping.
  - Installing sebastian/global-state (1.1.1): Downloading (100%)
 Extracting archiveNo patches found for sebastian/global-state.
Patching is disabled. Skipping.
  - Installing sebastian/recursion-context (1.0.5): Downloading (100%)
 Extracting archiveNo patches found for sebastian/recursion-context.
Patching is disabled. Skipping.
  - Installing sebastian/exporter (1.2.2): Downloading (100%)
 Extracting archiveNo patches found for sebastian/exporter.
Patching is disabled. Skipping.
  - Installing sebastian/environment (1.3.8): Downloading (100%)
 Extracting archiveNo patches found for sebastian/environment.
Patching is disabled. Skipping.
  - Installing sebastian/diff (1.4.3): Downloading (100%)
 Extracting archiveNo patches found for sebastian/diff.
Patching is disabled. Skipping.
  - Installing sebastian/comparator (1.2.4): Downloading (100%)
 Extracting archiveNo patches found for sebastian/comparator.
Patching is disabled. Skipping.
  - Installing doctrine/instantiator (1.0.5): Downloading (100%)
 Extracting archiveNo patches found for doctrine/instantiator.
Patching is disabled. Skipping.
  - Installing phpunit/php-text-template (1.2.1): Downloading (100%)
 Extracting archiveNo patches found for phpunit/php-text-template.
Patching is disabled. Skipping.
  - Installing phpunit/phpunit-mock-objects (2.3.8): Downloading (100%)
 Extracting archiveNo patches found for phpunit/phpunit-mock-objects.
Patching is disabled. Skipping.
  - Installing phpunit/php-timer (1.0.9): Downloading (100%)
 Extracting archiveNo patches found for phpunit/php-timer.
Patching is disabled. Skipping.
  - Installing phpunit/php-file-iterator (1.4.2): Downloading (100%)
 Extracting archiveNo patches found for phpunit/php-file-iterator.
Patching is disabled. Skipping.
  - Installing phpunit/php-token-stream (1.4.11): Downloading (100%)
 Extracting archiveNo patches found for phpunit/php-token-stream.
Patching is disabled. Skipping.
  - Installing phpunit/php-code-coverage (2.2.4): Downloading (100%)
 Extracting archiveNo patches found for phpunit/php-code-coverage.
Patching is disabled. Skipping.
  - Installing phpdocumentor/reflection-common (1.0): Downloading (100%)
 Extracting archiveNo patches found for phpdocumentor/reflection-common.
Patching is disabled. Skipping.
  - Installing phpdocumentor/type-resolver (0.3.0): Downloading (100%)
 Extracting archiveNo patches found for phpdocumentor/type-resolver.
Patching is disabled. Skipping.
  - Installing phpdocumentor/reflection-docblock (3.2.2): Downloading (100%)
 Extracting archiveNo patches found for phpdocumentor/reflection-docblock.
Patching is disabled. Skipping.
  - Installing phpspec/prophecy (v1.7.0): Downloading (100%)
 Extracting archiveNo patches found for phpspec/prophecy.
Patching is disabled. Skipping.
  - Installing phpunit/phpunit (4.8.36): Downloading (100%)
 Extracting archiveNo patches found for phpunit/phpunit.
zendframework/zend-feed suggests installing zendframework/zend-cache (Zend\Cache component, for optionally caching feeds between requests)
zendframework/zend-feed suggests installing zendframework/zend-db (Zend\Db component, for use with PubSubHubbub)
zendframework/zend-feed suggests installing zendframework/zend-http (Zend\Http for PubSubHubbub, and optionally for use with Zend\Feed\Reader)
zendframework/zend-feed suggests installing zendframework/zend-servicemanager (Zend\ServiceManager component, for easily extending ExtensionManager implementations)
zendframework/zend-feed suggests installing zendframework/zend-validator (Zend\Validator component, for validating email addresses used in Atom feeds and entries ehen using the Writer subcomponent)
paragonie/random_compat suggests installing ext-libsodium (Provides a modern crypto API that can be used to generate random bytes.)
easyrdf/easyrdf suggests installing ml/json-ld (~1.0)
symfony/validator suggests installing symfony/intl ()
symfony/validator suggests installing symfony/property-access (For using the 2.4 Validator API)
symfony/serializer suggests installing symfony/property-access (For using the ObjectNormalizer.)
symfony/dependency-injection suggests installing symfony/proxy-manager-bridge (Generate service proxies to lazy load them)
symfony/var-dumper suggests installing ext-symfony_debug ()
psy/psysh suggests installing ext-pdo-sqlite (The doc command requires SQLite to work.)
psy/psysh suggests installing hoa/console (A pure PHP readline implementation. You'll want this if your PHP install doesn't already support readline or libedit.)
alchemy/zippy suggests installing guzzle/guzzle (To use the GuzzleTeleporter with Guzzle 3)
commerceguys/addressing suggests installing symfony/intl (to use it as the source of country data)
behat/mink suggests installing behat/mink-selenium2-driver (slow, but JS-enabled driver for any app (requires Selenium2))
behat/mink suggests installing behat/mink-zombie-driver (fast and JS-enabled headless driver for any app (requires node.js))
sebastian/global-state suggests installing ext-uopz (*)
phpunit/php-code-coverage suggests installing ext-xdebug (>=2.2.1)
phpunit/phpunit suggests installing phpunit/php-invoker (~1.1)
Writing lock file
Generating autoload files
Downloading (100%)Downloading (100%)Downloading (100%)Downloading (100%)Downloading (100%)Downloading (100%)Downloading (100%)Downloading (100%)Downloading (100%)Downloading (100%)Downloading (100%)Downloading (100%)Downloading (100%)Downloading (100%)Downloading (100%)Creating packages services cache file:
/var/www/drupal/mystore/vendor/drupal/console/extend.console.uninstall.services.yml
> post-update-cmd: DrupalProject\composer\ScriptHandler::createRequiredFiles
Create a sites/default/settings.php file with chmod 0666
Create a sites/default/services.yml file with chmod 0666
Create a sites/default/files directory with chmod 0777
Do you want to remove the existing VCS (.git, .svn..) history? [Y,n]? y

```

# Answer
I just ran into this issue, using the same installation method.

I tried manually requiring the newer version with:

```
composer require "drupal/commerce 2.x-dev"

```

Which gave me an error:

```
Your requirements could not be resolved to an installable set of packages.
Problem 1
- Installation request for drupal/commerce 2.x-dev -> satisfiable by drupal/commerce[2.x-dev].
- drupal/commerce 2.x-dev requires ext-bcmath * -> the requested PHP extension bcmath is missing from your system.

To enable extensions, verify that they are enabled in your .ini files:
- /etc/php/cli-php7.0/php.ini
- /etc/php/cli-php7.0/ext-active/opcache.ini
You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.

Installation failed, reverting ./composer.json to its original content.

```

**Solution**: Updating PHP to use **bcmath** and restarting the web server solved the problem for me. Installation is now progressing normally.
> 1 votes

# Answer
This is something I haven't seen before.

Look at the output you shared: "Installing drupal/commerce (2.0.0-beta3)" The current version is RC1, beta3 is from last November. That's why you're getting the message about missing modules.

What makes this problem even weirder is that you got the most recent version of project-base, as well as Address. You only received an ancient version of Commerce.

Try deleting the folder and rerunning the command. If that still gives you the same result, try "composer clear-cache" first, then the command.
> 1 votes

---
Tags: commerce
---


# Question
Title: Changing the title of the Answers add answer form
I want to change "Your answer" in the add answer form of the Answers module so that it says "Give \[user who asked question\] your answer".

Here is a snippet of code from `answers.module` that defines the value

```
// Add the form to the question page.
        $node->content['new_answer_form'] = $answer_form;
        $node->content['new_answer_form']['#weight'] = 150;
        $node->content['new_answer_form']['new_answer_form_title'] = array(
          '#theme' => 'html_tag',
          '#tag' => 'h2',
          '#attributes' => array('class' => 'new-answer-form-title'),
          '#value' => t('Your answer'),
          '#weight' => -100,
        );

```

I tried changing it to:

```
// Add the form to the question page.
        $node->content['new_answer_form'] = $answer_form;
        $node->content['new_answer_form']['#weight'] = 150;
        $node->content['new_answer_form']['new_answer_form_title'] = array(
          '#theme' => 'html_tag',
          '#tag' => 'h2',
          '#attributes' => array('class' => 'new-answer-form-title'),
          '#value' => t('Give ', $author, 'your answer'),
          '#weight' => -100,
        );

```

Not surprisingly, this didn't work. I'm not sure which variable to use for $author, and other changes, so that the username of the person who asked the question appears there.

Disclaimer: I apologize if the question is off, I work for a non-profit organization that isn't a tech company and am just trying to build us a new website but have a gluten for punishment and an interest in getting back in to the tech field. Thanks for your patience.

Edit: I created a helper module for customizations to other modules.

# Answer
> 2 votes
Since you have the node object, you can find its author via `$node->uid`. Then load the account and wrap it in `format_username()`:

```
$uid = $node->uid;
$account = user_load($uid);
$account_name = format_username($account);

```

The hook you need depends on the function in which your snippet was found. In your case it is in `hook_node_view`, so you need `hook_node_view_alter()`

From there it is as simple as redefining the value. Something like this:

```
MODULENAME_node_view_alter(&$build) {
  $node = &$build['#node'];

  $new_title = t("Give @author your answer", array('@author' => $account_name));

  $node->content['new_answer_form']['new_answer_form_title']['#value'] = $new_title.
}

```

---
Tags: 7
---


# Question
Title: Menu does not translate on second language
I have a multi language Drupal 8 site. But when I change the language of the Drupal site to the second language everything changes to the selected language except the main menu.

When I change the language when I'm logged in, the main menu will be translated to the selected language.

Can someone help me to make the menu change language when a normal user select his preferenced language?

# Answer
> 0 votes
Your menu link translations are likely not published. Check the translation details element on the translate form and make sure the published checkbox is checked.

The default behavior around that is a bit weird, especially if you create the menu links before enabling translations, there is an issue that should improve that, might already be better in 8.4

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


# Question
Title: Notification and Messaging module for sending mails
I have installed send methods as html mail and i have set notification module with subscriptions to content type.

I am not receiving an email when notification actions get created.

have anyone pass through such scenario? Please let me know.

# Answer
> 0 votes
Html mail is not reliable, buggy and some features are not supported. I've got rid of it. Mime mail is much better. Mail system and SMTP module must also be installed.

In the settings SMTP Authentication Support SMTP server, SMTP port, User name, E-mail from address, E-mail from name must be filled, Allow to send e-mails formatted as Html could be ticked and password of your SMTP server must also be entered.

In the module Mail system in the submenu New class MimeMail\_SmtpMailSystem must be constructed and filled in Site-wide default MailSystemInterface class and Mime Mail module class. In the settings Mime mail E-mail format Full HTML can be selected and Sender e-mail address need to be filled.

This configuration must work.

---
Tags: 7, rules, notifications
---


# Question
Title: When more than one Shipping Rules applies, select the highest
I am using Drupal 7 with Drupal Commerce to manage an eshop.
I have 8 product types and I manage the shipping per product type with price variations.
Product type 1 when price is lower than 50 euros has 5 euros shipping, product type 2 has 3 euros shipping when the price is lower than 30 euros etc
I manage doing that by adding rules after a product is placed at the cart , using "Price comparison" and "Order contains products of particular product types" conditions, and action "Apply shipping rate to an order".

It seems to work fine but when I add multiple products from various categories, the shipping rule that prevails is the rule applied to the first product added to the cart.
What I want is to compare all Shipping rules and keep the one with the highest cost.

Is this possible?

# Answer
> 0 votes
Maybe Total amount of selected products comparison in Commerce Order can be used for that condition. A temporary solution is to apply the rule which only allows one product per cart.

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


# Question
Title: How to get the super user in a functional test?
How can I get the information for the super user (uid 1) in a functional test?

I want to test the external auth logic I have written, and one of the steps is authenticating the Drupal superuser locally instead of in the remote system. I am not seeing a way to get the username/password of that user in order to simulate a login.

Test:

```
  /**
   * The superuser should not authenticate to Netforum.
   */
  public function testSuperUserUsesDrupalAuthentication() {
    $this->drupalGet('user/login');
    $edit = ['name' => $this->rootUser->getEmail(), 'pass' => $this->rootUser->pass_raw];
    $this->drupalPostForm(NULL, $edit, t('Log in'));

    $user = \Drupal::currentUser();
    $this->assertEquals(1, $user->id());
  }

```

# Answer
> 0 votes
The problem occurs because the password is not set to start with. You can give this a try:

```
// Load real user object from UserSession object.
$admin_account = User::load($this->rootUser->id());
// The password is empty.
$this->assertFalse($admin_account->pass_raw);
// Set the password and save the User.
$new_password = $this->randomString();
$admin_account->setPassword($new_password);
$admin_account->save();
// Set the pass_raw directly on the User.
$admin_account->pass_raw = $new_password;
$this->drupalLogin($admin_account);

```

This is for the `WebTestBase`, if you use the `BrowserTestBase`, you should use the following (pass\_raw ≠ passRaw)

```
// Load real user object from UserSession object.
$admin_account = User::load($this->rootUser->id());
// The password is empty.
$this->assertFalse($admin_account->passRaw);
// Set the password and save the User.
$new_password = $this->randomString();
$admin_account->setPassword($new_password);
$admin_account->save();
// Set the passRaw directly on the User.
$admin_account->passRaw = $new_password;
$this->drupalLogin($admin_account);

```

Good luck!

**References**

The details regarding the passRaw/pass\_raw setting on the User object are available here:

# Answer
> 1 votes
Looking into `BrowserTestBase` I accidentally found `$this->rootUser->name` and `$this->rootUser->pass_raw` last week. These are being used in `installParameters()`. I have not tested it, but I suppose you should be able to use those in other functions as well.

rootUser appears to be a full AccountInterface object, so getName() and other methods should work as well..

---
Tags: 8, testing
---


# Question
Title: How to add item to cart programmatically, with attributes in Ubercart
So I know how to go about adding an item to the cart with PHP like this;

```
$product_nid = 2;
$some_data = NULL;

  uc_cart_empty(uc_cart_get_id());

  $data = serialize($some_data);

  uc_cart_add_item($product_nid, $qty = 1, $data, $cid = NULL, $msg = TRUE, $check_redirect = TRUE, $rebuild = TRUE);

```

but I'm uncertain how to add a product with a certain attribute/option such as if I have product "A" with options "1" and "2" I was hoping I could get a little help. This is for Drupal 7, Ubercart 3.

# Answer
> 2 votes
Taking Chris's answer an putting it in Answer format for readability.

Figured it out, perhaps this will be of help for someone :)

```
$product_nid = 2;
$some_data = array('attributes' => array(
                   '1' => '1',
                  ),
             );
uc_cart_empty(uc_cart_get_id());
$data = serialize($some_data);
uc_cart_add_item($product_nid,
                 $qty = 1,
                 $data,
                 $cid = NULL,
                 $msg = TRUE,
                 $check_redirect = TRUE,
                 $rebuild = TRUE);

```

# Answer
> 0 votes
i am using ubercart in drupal 8

$session = \Drupal::service('session');

$cart\_manager = \Drupal::service('uc\_cart.manager');

$anonymous\_cart = $cart\_manager-\>setID($session-\>get('uc\_cart\_id'));

$sql="delete from uc\_cart\_products where cart\_id='".$anonymous\_cart."'";

db\_query($sql);

$result= db\_insert('uc\_cart\_products')

```
        ->fields(array(
        'cart_id' => $anonymous_cart,
        'nid' => $nid,
        'qty' => $quantity,
        'changed' => strtotime(date('Y-m-d')),
        'data' => ($data),
        ))
        ->execute();

```

---
Tags: ubercart
---


# Question
Title: How do I use this module which depends from a module that is not available for the core version I am using?
I'm trying to install the *Juicebox HTML5 Responsive Image Galleries* module to the Drupal 8 site but the system doesn't allow me to do so because the *Libraries API* module is missing. The modules page shows the following.

Is it possible to use the *Juicebox HTML5 Responsive Image Galleries* module even if there is no Drupal 8 version for the *Libraries API* module? Could it work with the 7.x-2.3 version?

The project page for the *Libraries API* module shows the following message:

> This module is currently being ported to Drupal 8, but is not usable yet. Help us by following this issue.

Does it mean I can't use this API module for the Drupal 8?

# Answer
Welcome to Drupal Answers.

You don't need additional module for Libraries on Drupal 8, just create `libraries` folder in root of a Drupal project and put all libraries you need there.

In this case download juicebox library unarchive it, put the unarchived folder in libraries folder you created and rename it to `juicebox`, so your library should be in `/libraries/juicebox`.

And that's it, you can enable your module.
> 1 votes

# Answer
The *Juicebox HTML5 Responsive Image Galleries* module lists the *Libraries API* module as dependency in juicebox.info.yml. This means that Drupal will not let you install the *Juicebox HTML5 Responsive Image Galleries* module if it doesn't find the *Libraries API* module in one of the directories where Drupal looks for modules, or if the *Libraries API* module is not first installed. (In the first case, Drupal will install both the modules when you install the *Juicebox HTML5 Responsive Image Galleries* module.)

There is a Drupal 8 development snapshot for the *Libraries API* module. You can find it clicking on *View all releases* in the project page for the *Libraries API* module. The fact is not directly shown in the project page probably means the module is not ready to be used in Drupal 8.
There is also an issue opened for Drupal core (Libraries API in core) which makes me think they aren't releasing any stable release for Drupal 8, waiting for the module to be accepted to be included as core module.

What you can do right now is installing the 8.x-3.x version of the *Libraries API*, knowing that the last update has been done on March 15, 2017, and that you could have some problems using it. I would rather test it in a test site where you install all the modules you are using in the production server, and see which problems that causes.

The alternative is using a module with the same feature the *Juicebox HTML5 Responsive Image Galleries* module has, or a module that has the same features you are using from the *Juicebox HTML5 Responsive Image Galleries* module.

Using a Drupal 7 version of a module with Drupal 8 doesn't work as, to start, Drupal 8 requires modules have a .info.yml file, while Drupal 7 requires a .info file containing information in a totally different format.
> 0 votes

---
Tags: 8
---


# Question
Title: How to get the Bootstrap 3 Datepicker to redirect to an URL when a date is picked?
I use the Drupal bridge module **Bootstrap Date & Time picker** with its associated JavaScript libraries. I am trying to create a Drupal form where the user clicks on a particular month, and then the user is redirected to a page showing all the events happening that month.

This is how I build the form:

```
function rbg_date_picker($form, &$form_state) {
  $form['date'] = array(
    '#type' => 'date_text',
    '#bdtpicker' => TRUE,
    '#date_format' => 'Y-m',
    '#datepicker_chain' => array(
      'my_interval_end[date]' => 'next',
     ),
     '#datepicker_options' => array(
       'viewMode' => 'months',
     ),
  );
  return $form;
}

```

The form show up and when the user clicks on a month in the widget's grid, the date field gets filled in with the year and month. So far, so good.

However, at this point, I want the JavaScript to redirect to an URL so that I can create an ordinary page with the relevant information. For example, if the user picked August 2017, the Javacript should redirect to "http://example.org/2017-08".

Maybe there is already support for this functionality in the Drupal bridge module (and I haven't spotted it), or maybe I need to add a small JavaScript snipped to make this work (confession: I suck at JavaScript). Any help will be appreciated.

(PS: I know that if I add a submit button to the form, I can pick up the year and month in the submit handler. However, I think the UX would be better if the user can just click on the month, without having to explictly hit "Submit" afterwards.)

# Answer
You can redirect using ajax forms and ctools, first of all you will need to add #ajax property to your form field so the code will be :

```
function rbg_date_picker($form, &$form_state) {
  $form['date'] = array(
    '#type' => 'date_text',
    '#bdtpicker' => TRUE,
    '#date_format' => 'Y-m',
    '#datepicker_chain' => array(
      'my_interval_end[date]' => 'next',
    ),
    '#datepicker_options' => array(
      'viewMode' => 'months',
    ),
    '#ajax' => array(
      'callback' => 'SOME_FUNCTION_NAME',
    ),
  );
  return $form;
}

```

The rest is easy, in callback function you will need to have some code like below :

```
function SOME_FUNCTION_NAME($form,$form_state) {
  $time = $form_state['values']['date']; // maybe need ['und'][0]['value']
  //Some code to fetch desired values from date like month or year
  ctools_include('ajax');
  ctools_add_js('ajax-responder');
  //Some code to fetch desired values from form and compute 'some-valid-url'.
  $commands[] = ctools_ajax_command_redirect('some-valid-url');
  print ajax_render($commands);
  exit;
}

```
> 2 votes

# Answer
@Alireza Tabatabaeian, thank you for your answer, it has been accepted and upvoted.

However, your AJAX callback function does not work as it is written. Below is how I had to tweak it to make it work:

```
/**
 * AJAX callback
 */
function SOME_FUNCTION NAME($form, $form_state) {
  ctools_include('ajax');
  ctools_add_js('ajax-responder');
  //Some code to fetch desired values from form and compute 'some-valid-url'.
  $commands[] = ctools_ajax_command_redirect('some-valid-url');
  print ajax_render($commands);
  exit;
}

```
> 2 votes

---
Tags: ajax, bootstrap-theme
---


title: WSOD when redirecting based on cookie

text:
# Question
Title: WSOD when redirecting based on cookie
I have a site where I set a cookie when the user is visiting a specific content-type:

```
function THEME_preprocess_node(&$variables) {
  if (isset($variables['node']) && $variables['node']->getType() == 'MYTYPE') {
    // Store cookie with id of active node.
    user_cookie_save(['THEME_location' => $variables['node']->get('nid')->getString()]);
  }
}

```

Then if the user again is going to the frontpage, I would like to redirect him to the node referenced from the above cookie:

```
function THEME_preprocess(&$variables, $hook) {
  $variables['is_front'] = \Drupal::service('path.matcher')->isFrontPage();

  // Redirect the user to the selected node.
  $cookies = \Drupal::request()->cookies->all();
  if ($variables['is_front'] && isset($cookies['Drupal_visitor_THEME_location'])) {
    $nid = $cookies['Drupal_visitor_THEME_location'];
    $response = new RedirectResponse(\Drupal::url('entity.node.canonical', ['node' => $nid]));
    $response->send();
  }
}

```

The above works fine **most** of the time, but sometimes when loggin out from the backend and visiting the frontpage I only get a white screen and the page is completly dead. I know this is very vague but I cannot seem to reproduce this error by performing some specific steps. It just happens once in a while. If I then clear the cache everything seems to work as expected again? Can someone see what I am doing wrong here?

# Answer
> 3 votes
You should not be using theme\_preprocess to perform any processing the results of which cannot be cached, only manipulation of variables to be passed to the final theme processing function or template.

Doing a redirection in a theme\_preprocess will cause the result to be empty and this is what leads to the WSOD, I believe.

Instead the preferred method is to use an event subscriber, as described on this page: https://www.drupal.org/node/2013014

> Register your Event Subscriber in your mymodule.services.yml and tag it as such:

```
services:
  mymodule_event_subscriber:
    class: Drupal\mymodule\EventSubscriber\MymoduleSubscriber
    tags:
      - {name: event_subscriber}

```

> Your MymoduleSubscriber should be placed in folder structure of modules/src/EventSubscriber/MymoduleSubscriber.php and should implement the EventSubscriberInterface interface and in its getSubscribedEvents() point to the method that should be executed:

```
namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class MymoduleSubscriber implements EventSubscriberInterface {

  public function checkForRedirection(GetResponseEvent $event) {
    if ($event->getRequest()->query->get('redirect-me')) {
      $event->setResponse(new RedirectResponse('http://example.com/'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('checkForRedirection');
    return $events;
  }

}

```

---
Tags: 8, cookies, wsod
---


title: How to add scroll bar to views titles

text:
# Question
Title: How to add scroll bar to views titles
I created a views block to display the titles of nodes. I placed the block in the left side region. In order to see all the titles, I need to scroll down the page. Instead, I would like to add scroll bar to the views titles so I can simply scroll the bar to see the titles. How can I do it?

# Answer
> 3 votes
You will need some css to do this task. Pick a class from view content html and fix its height and set overflow-y property to scroll. Example snippet below -

```
.view-content{
    height: 50px;
    overflow-y: auto;
}

```

---
Tags: views
---


# Question
Title: Getting empty error message when install Drupal using Windows server 2012
I'm attempting to set up a Drupal 8.3.6 site on Windows Server 2012. I have been following this guide: http://www.drupalonwindows.com/en/blog/installing-drupal-8-windows

I'm at the point of running the Drupal installation, but am running into a road block at the Database configuration step. When attempting to save my database settings, it takes a very long time to attempt to save, and then I get an error message that simply says "Failed to connect to your database server. The server reports the following message: ." Just a blank error message.

Some info about my configuration:

* I'm using SQL Server Express and maintaining it with SSMS 2017
* My SQL Server setup uses Windows authentication and I am logged in as the Administrator account when working with it (I am not sure if this is different from the credentials Drupal tries to use)
* Windows Firewall on my server is configured to allow connections to port 1433 as well as to sqlserver.exe
* According to SQL Server Configuration Manager, SQL Server is running (SQL Server Agent and SQL Server Browser cannot be started however)
* I created a database called "drupal" in MSSQL owned by the Administrator account, however I get the same error whether or not I specify this database name in the "Database name" field or if I define a new one. I am leaving the username/password blank as instructed by the installation page.
* In the comments section of the install guide, one of the maintainers of the sqlsrv drivers says to use the 8.x-1.x branch if not purchasing Phpmssql, so these are the drivers I am using.
* My server has 2 IP addresses, and the IP address of my Drupal site is different from the primary IP address of my server (my primary IP is used for a different site). My bindings in IIS are correct and I'm accessing the site via its designated IP. I feel like this is causing the problem with a connection issue, however if I change the host under "Advanced Options" from "localhost" to my server IP, the problem still persists.
* Before using 8.x-1.x drivers, I was trying 8.x-2.x and getting the error message "The PhpMssql library is not available.", so maybe it's not an IP connection issue?

I feel like I've missed something in my configuration, but can't tell what that is from the install guide. Can anyone please shed some insight?

# Answer
I figured it out, I think that trying to connect to "localhost" was failing because I should have been specifying {servername}\SQLEXPRESS instead.
> 0 votes

---
Tags: 8, database, installation
---


# Question
Title: Unable to change the background image in theme
I am trying to change the background image provided in the theme. Below is the CSS snippet from *style.css* file:

```
.toplayer{
  background: url(../images/theme.png) right no-repeat;
  position: fixed;
  top: 0;
  right: 0;
  height: 100%;
  width: 100%;
  z-index: -1;
}

```

I put the new background image in the same directory and tried to change the background by overwriting the above CSS in following way:

```
background: url(../images/background.png)

```

After clearing the Drupal cache, I reload the page, but I don't see the new image. At the same, I tried to access the image from my browser, and got the following error:

```
Forbidden

You don't have permission to access /new/themes/drupal_theme/images/background.png on this server.
Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.

```

Later on, I moved *theme.png* and rename the *background.png* as *theme.png* but I still see the old background image.

# Answer
I think Your have 2 configuration problem.

* File Permission (in Filesystem)
* ErrorDocument Attribute (in Apache Webserver)

First, You can solve permission error using 'chmod' command to the sites folder of drupal.

Try this:

> chmod -R 777 directory (777 means allow permission for all)

Second, ErrorDocument handle error can occured from invaild ErrorDocument attribute setting in .htacess or httpd.conf(or apache2.conf) file.

Try this:

1. check your .htacess file in 'install/' directory. If you can not check this file, you can try 'ls -al' command in terminal. you have to find 'ErrorDocument' attribute, and remove or correct it.
2. check your apache webserver configuration file (httpd.conf or apache2.conf). If you can check 'ErrorDocument' attribute, you can try remove this attribute in file. It is temporary, so you must backup it before try suggested cases.
3. If you can not solve by case 1 and 2, you can try disable 'AllowOverride' attribute. Try find 'AllowOverride x' attribute and replace to 'AllowOverride None'. Because, this problem can have possiblity from .htacess file in parent directories. AllowOverride attribute can control allow or deny additional configuration in .htacess file.
4. You must restart apache service after try this cases. you can try 'service httpd restart' or 'service apache2 restart' command.

Hope this helps you...
> 1 votes

---
Tags: 7, theming
---


# Question
Title: Get field definitions across bundles, including base fields
In Drupal 8 there are two types of fields: "base fields" like node.uid, and user-defined fields like 'node.body'.

All of the field names for one entity type can be found with `EntityFieldManagerInterface->getFieldMap()`. However this only contains the field type (as string) and a list of bundles.

For the base fields like 'uid', there is `EntityFieldManagerInterface->getbaseFieldDefinitions($entity_type_id)`. But this omits the user-defined fields.

For user-defined fields, there is `EntityTypeManagerInterface->getStorage('field_storage_config')->load($entity_type_id . $field_name);`. But this does not include base fields like 'node.uid'.

There is also `EntityFieldManagerInterface->getFieldDefinitions($entity_type_id, $bundle_name)`. But this has to be called per bundle.

There is more in FieldTypePluginmanager, EntityAdapter, and EntityDataDefinition. The more I look, the more confusing and complex this entire architecture looks to me..

## Background

I would like to show a select element where a user can choose a field. Entity type is given, but bundle is not. Options are filtered by various criteria. E.g. maybe I want to show all fields where the item type extends EntityReferenceItem, and the reference target type is 'node'. For this I need to inspect the definition of each field.

All of this is for D8 version of https://drupal.org/project/renderkit.

# Answer
> 4 votes
> The more I look, the more confusing and complex this entire architecture looks to me.

The architecture is actually very similar to 7.x, just renamed. 7.x had fields and field instances, 8.x has field storages (= 7.x fields) and fields. Base fields are exposed as both by default, while configurable fields have a separate entity type for each.

Field storages exist per entity type and fields per entity\_type/bundle. (in 7.x, fields were global, otherwise it is the same).

To get all field storages of an entity type, you can use \Drupal\Core\Entity\EntityFieldManager::getFieldStorageDefinitions(). Note that a field storage has no label, only the field (and the label can be different per bundle), so you will need to consider all bundles anyway if you don't want to just show a machine name. token and views have helper functions for that, e.g. \_token\_field\_label().

Another useful reference is how the entity selection plugin build the list of fields to sort by: \Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection::buildConfigurationForm()

---
Tags: 8, entities
---


title: Adding a new token to a product

text:
# Question
Title: Adding a new token to a product
I'm trying to add a token to Product using the below code. The problem is that, although this adds the token I'm after, it also removes a number of standard tokens that are needed (e.g., the title).

```
/**
 * Implements hook_token_info().
 */
function fw_product_token_info() {

  $type = [
    'name' => 'Product',
    'description' => t('Useful additional tokens for products'),
    'needs-data' => 'commerce_product',
  ];

  $tokens['fw_product_parent_url'] = [
      'name' => t('Parent URL'),
      'description' => t('The full path to this product\'s parent'),
  ];

  return [
    'types' => ['commerce_product' => $type],
    'tokens' => ['commerce_product' => $tokens],
  ];

}

/**
 * Implements hook_tokens().
 */
function fw_product_tokens($type, $tokens, array $data = [], array $options = [], BubbleableMetadata $bubbleable_metadata) {

  $replacements = [];

  if ($type == 'commerce_product' && !empty($data['commerce_product'])) {
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'fw_product_parent_url':
          $entity = $data['commerce_product'];
          if ($parent_entity = \Drupal::service('fw_product.parent')->getEntity($entity)) {
            $replacements[$original] = $parent_entity->url('canonical');
          }
          else {
            $replacements[$original] = '';
          }
          break;
      }
    }
  }
  return $replacements;
}

```

# Answer
Return 'tokens' if you want to add new/custom to the existing list.

```
return [
  'tokens' => ['commerce_product' => $tokens],
];

```
> 2 votes

# Answer
That's because you are not just defining the token but also the token type. Don't define that if it's not yours to define.

To prevent conflicts, token module only defines tokens for base fields if there are no default token types for a given entity type.
> 1 votes

---
Tags: 8, commerce
---


title: Override custom module template

text:
# Question
Title: Override custom module template
I created a custom module with its own template file to display the content with the following code.

```
function mymodule_theme($existing, $type, $theme, $path) {
  return [
    'theme_mymodule_list' => [
      'template' => 'templates/list_mymodule',
      // name of the template file, minus the '.tpl.php'

      // these are the template variables that will available to your template
      'variables' => [
        'myvar1' => NULL,
      ],
    ],

  ];
}

```

With the code above I'm able to get the template from the module directory (sites/all/modules/mymodule/templates/list\_mymodule.tpl.php), but now I decided to make a theme for the site, and I want to override the custom module template file with the usual approach of copying-pasting the file into the theme and clear the cache.

How do I override the template used from a custom module from a theme?

# Answer
> 1 votes
What you describe is something that Drupal core already does. Take as example the Node module; it defines its own template file (node.tpl.php) that is then overridden from themes, such as the Bartik theme, with their own template file (in the case of the Bartik theme, with templates/node.tpl.php).

What is wrong in your implementation of `hook_theme()` is the name you give to the template file. Despite what it could seem, the *template* key doesn't allow to give the template name an arbitrary name; the name must match the theme name you are using, in your case mymodule\_list. You can replace the underscores in the theme name with hyphens, but that is the only change you could do.

See Override template files based on template filename as well as hook name, where the user suggesting the change says:

> Turns out the template file name needs to exactly match the array key used in `hook_theme()` (with the exception of dashes and underscores). In the case of my example, the template value would need to be **my\_abc\_index** and the file name **my-abc-index.tpl.php**. Failure to do so will result in an un-overridable template.

(I slightly changed formatting, and the spelling of a word.)

Also, as you see in the code used from Drupal core, the *theme\_* prefix in the the theme name is not necessary.

```
function node_theme() {
  return array(
    'node' => array(
      'render element' => 'elements',
      'template' => 'node',
    ),
    'node_search_admin' => array(
      'render element' => 'form',
    ),
    'node_add_list' => array(
      'variables' => array('content' => NULL),
      'file' => 'node.pages.inc',
    ),
    'node_preview' => array(
      'variables' => array('node' => NULL),
      'file' => 'node.pages.inc',
    ),
    'node_admin_overview' => array(
      'variables' => array('name' => NULL, 'type' => NULL),
      'file' => 'content_types.inc',
    ),
    'node_recent_block' => array(
      'variables' => array('nodes' => NULL),
    ),
    'node_recent_content' => array(
      'variables' => array('node' => NULL),
    ),
  );
}

```

# Answer
> 0 votes
You can override tpl files defined in modules inside your active theme (under the templates directory). But Drupal will look for a file name using the defined theme key name and not the defined template file.

In your case, you should create a `theme_mymodule_list.tpl.php` file within your theme. Maybe a good practice to name your template file the same as your theme definition.

---
Tags: 7, theming
---


# Question
Title: hook_options_list not getting fired in a custom module
I need to limit taxonomy term reference field options based on another field.This is needed as there are around 1000 terms available for this 'Select' field but I want to limit these options to a minimum using hook\_options\_list.

But this hook is not getting called from the custom module, not much detail provided on the drupal help too.

Does this hook require any prerequisite so it can be called.

# Answer
You can use hook\_field\_info\_alter() to attach custom allowed\_values\_function to your field and implement your own logic there:

```
function my_module_field_info_alter(&$info) {
  $info['my_field']['settings']['allowed_values_function'] = 'my_module_my_field_allowed_values_callback';
}

function my_module_my_field_allowed_values_callback($field, $instance, $entity_type, $entity) {
  // Custom logic
  return $values;
}

```
> 0 votes

---
Tags: entities, taxonomy-terms, hooks
---