# Question
Title: How to set a default controller if no other routes match
I my project I would like to have a default route or controller that handles any request that does not match any available route. For example on requesting /abcd it now returns 404 as there is route defined for the path /abcd. I want any such request to be handle by a default controller that consider 'abcd' or any other string for that matter as a parameter. How can I implement that. If I define a route for path /{param} wouldn't that override other active routes

# Answer
> 1 votes
Go to */admin/config/system/site-information* and set **Default 404 (not found) page** to the path of your custom controller.

In the controller place a typecasted `$request` in the argument list. Then get the path from the request and either build a custom 404 response or redirect to another page:

```
use Symfony\Component\HttpFoundation\Request;

  public function myController(Request $request) {
    $path = $request->getPathInfo();
    if ($path === '/abc') {
      return ['#markup' => 'Path "abc" does not exist!'];
    }
    else {
      return $this->redirect('<front>');
    }
  }

```

---

To answer the deleted comment. The controller can't set a status code 200, because it responds to a sub request and the master request is set to 404 no matter which 2xx status you set in the controller. For this you need an event subscriber: Does not redirect in EventSubscriber.

---
Tags: 8, routes
---


# Question
Title: Is there any way to do semi-anonymous commenting using Facebook login?
I'm wondering if it is possible to allow a user to login for commenting via Facebook, but without having to setup a full Drupal account.

Is there anyway that allows this sort of semi-anonymous commenting?

The module I've seen don't really seem to allow this and there's no way I can tell to hook into Drupal anywhere that allows you to allow anonymous comments but with a Facebook login.

# Answer
> 0 votes
You can use drupal module Facebook comments or Facebook comments block for the same.

---
Tags: comments, social-network
---


# Question
Title: Interactions between a form and a modal form
I need to help the user to fill a set of fields in a content type form, this way :

The users start to fill one of the concerned fields: They click on a button that will open a modal form. The modal form will propose some choices depending on the filled fields; when users choose a proposition, the modal form closes and the fields of the original form get updated with the chosen proposition.

I have tested 2 methods to open the modal form and I have issues with both.

With the first method, I can open and close the modal form, but I can't transmit field values from the form 1 to the modal form; with the second method, I can pass the field values to the modal form, but I fail closing this modal form.

How can I update the fields from the first form when I close the modal form?

This is my .module file. Read the comments for details.

```
use Drupal\Core\Url;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\OpenModalDialogCommand;
use Drupal\Core\Ajax\CloseModalDialogCommand;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function my_test_module_form_node_article_form_alter(&$form, &$form_state, $form_id)  {

    $form['#attached']['library'][] = 'core/drupal.dialog.ajax';

    $form['my_fieldset'] = array (
            '#type' => 'fieldset',
            '#title' => t ( 'My fieldset' ),
            '#collapsible' => TRUE,
            '#collapsed' => FALSE,
            '#tree' => TRUE
    );
    $form['my_fieldset']['my_field_1'] = array(
        '#type' => 'textfield',
        '#title' => t('Field 1'),
    );
    $form['my_fieldset']['my_field_2'] = array(
            '#type' => 'textfield',
            '#title' => t('Field 2'),
    );
    // METHOD 1
    // Problem : it doesn't allow to transmit my field values (from the $form_state) to the modal Form
    $form['my_fieldset']['open_modal1'] = array(
            '#type' => 'link',
            '#title' => t('Open modal 1'),
            '#url' => Url::fromRoute('my_test_module.modal_form'),
            '#attributes' => array(
                    'class' => array('button', 'use-ajax'),
                    'data-dialog-type' => 'modal',
            ),
    );
    // METHOD 2
    // Problem : The modal form can't be closed
    $form['my_fieldset']['open_modal2'] = array(
            '#type' => 'submit',
            '#value' => t('Open modal 2'),
            '#ajax' => array(
                    'callback' =>  'my_test_module_open_modal_form',
                    'event' => 'click',
            ),
    );
}

/**
 * Ajax Callback for the form - it opens the modal form
 *
 */
function my_test_module_open_modal_form($form, $form_state) {

    $values = $form_state->getValues();

    // Get the modal form
    $modal_form = \Drupal::formBuilder()->getForm('Drupal\my_test_module\Form\MyModalForm',$values['my_fieldset']['my_field_1'],$values['my_fieldset']['my_field_2']);
    // Add an AJAX command to open a modal dialog with the form as the content.
    $response = new AjaxResponse();
    $response->addCommand(new OpenModalDialogCommand(t('My Modal'), $modal_form, ['width' => '555']));
    return $response;
}

```

The modal form class I use is the following one.

```
/**
* @file
* Contains \Drupal\my_test_module\Form\MyModalForm.
*/

namespace Drupal\my_test_module\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\CloseModalDialogCommand;

/**
 * This class restitutes the modal form
 *
 */
class MyModalForm extends FormBase {

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

    public function buildForm(array $form, FormStateInterface $form_state, $field_1 = NULL, $field_2 = NULL) {

        $form['m1'] = array(
                '#markup' => 'Field 1 : ' . $field_1,
        );
        $form['m2'] = array(
                '#markup' => 'Field 2 : ' . $field_2,
        );

        $form['results'] = array (
                '#type' => 'table',
                '#header' => array('Field 1', 'Field 2',''),
        );

        $form['results'][0]['field_1'] = array(
                '#markup' => 'AAAA',
        );
        $form['results'][0]['field_2'] = array(
                '#markup' => 'BBBB',
        );
        $form['results'][0]['submit0'] = array(
                '#type' => 'submit',
                '#value' => 'Choose',
                'name' => '0',
                '#attributes' => [
                        'class' => [
                                'use-ajax',
                        ],
                ],
                '#ajax' => array(
                        'callback' => '::ajaxCloseModal',
                        'event' => 'click',
                ),
        );

        $form['results'][1]['field_1'] = array(
                '#markup' => 'AAAA',
        );
        $form['results'][1]['field_2'] = array(
                '#markup' => 'BBBB',
        );
        $form['results'][1]['submit1'] = array(
                '#type' => 'submit',
                '#value' => 'Choose',
                'name' => '1',
                '#attributes' => [
                        'class' => [
                                'use-ajax',
                        ],
                ],
                '#ajax' => array(
                        'callback' => '::ajaxCloseModal',
                        'event' => 'click',
                ),
        );
        return $form;

    }

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

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

    public function ajaxCloseModal(array &$form, FormStateInterface $form_state) {
        $response = new AjaxResponse();
        $response->addCommand(new CloseModalDialogCommand());
        //Get the triggering element, then replace the field_1 and field_2 values in the original form
        return $response;

    }

}

```

# Answer
> -1 votes
For closing model form you can use jquery. When field value will update javascript change event will occur so you can trigger modal form close button or link

```
$( "#textField" ).change(function() {
  $( "#close" ).trigger( "click" ); // if modal form have close button or some url
  $( "#modal" ).modal( "toggle" ); // in case of using bootstrap modal form
});

```

References: .change(), .trigger()

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


title: Print custom module in a block

text:
# Question
Title: Print custom module in a block
I want to print a custom module in a type of content already created through the interface. Is there any way to print it?

I have seen that one of the ways in drupal 7 to print the module is by using the 'module\_invoke' function, is there any equivalent in drupal 8 to print in a twig template?

Thanks!

# Answer
> 0 votes
Copy Print's print.tpl.php file into module folder, and name it print--node--foo.tpl.php.

`function foo_theme_registry_alter(&$theme_registry) {
 $theme_registry['print__node__foo']['template'] = 'print--node--foo';
 $theme_registry['print__node__foo']['path'] = drupal_get_path('module', 'foo');
}`

Note: My module and content type share the same name of foo.

---
Tags: 8, blocks
---


title: No block available with a module

text:
# Question
Title: No block available with a module
I am using Facebook post module which display its "Fb Account connection" generated informations/options in an user/%uid/edit/fb-post page.

I want to display these outputs in a custom panels page, but the module doesn't provide blocks, views, forms, or nothing I see that I could handle inside panels.

Any way to achieve this?

# Answer
> 1 votes
It should be pretty easy to create a block in your own custom module that displays this info. Take a close look at the `fb_post_page` function in `fb_post.admin.inc` and you can see what the module uses to output that data on the user/%uid/edit/fb-post page.

I'm not super familiar but it looks like the info you want to display can be gotten by calling `theme('fb_post_connect', array('connection_path' => fb_post_get_oauth_url($account, $app_id)));` and displaying the result in a block (or even directly in a panel pane)

---
Tags: 7, panels
---


title: embedding Facebook Video with oembed

text:
# Question
Title: embedding Facebook Video with oembed
What is the proper way to embed a (public) facebook video with the oembed field module?

I tried including a video with a link like `https://www.facebook.com/video.php?v=55555555555` but when I tested the link I got an error message (log didn't reveal details).

> `https://www.facebook.com/video.php?v=55555555555` is not valid oEmbed URL. Please check the error log for messages.

It also doesn't show up in the content type field.

The default schemes didn't do the trick:

```
http://www.facebook.com/video/video.php*
https://www.facebook.com/photo.php*
https://www.facebook.com/video/video.php*

```

So I've added this `https://www.facebook.com/video.php?v=*` in the media - oembed settings for facebook.

still, it didnt work.

Any ideas on what URL I have to provide for this to work?

**EDIT:**

I've posted an answer that worked for me.

Ideally, it should work without an embed.ly API key.

# Answer
> 1 votes
turned out i needed an API key for embedly service from http://embed.ly/. here is a good guide on oembed http://mustardseedmedia.com/podcast/episode54

strange. some images showed up even without an API key.

# Answer
> 0 votes
This has changed since this question was asked and answered. FB now fully supports integration with `oEmbed` and there is an easier way to include both videos and posts in a website.

You can check the documentation for doing so in their official page here.

---
Tags: 7, files, social-network, nodes
---


# Question
Title: Responsive image style with srcset and without sizes
Using this tutorial for example I found out how to use responsive image styles in Drupal 8 without `<picture>` (which is pretty straight forward anyway).

However this approach forces you to use `sizes`. The article says

> The default here `100vw` is hard-coded for a good reason, it's a pretty sane default and works well in most situations.

which I completely disagree with. I find that in most cases you simply want to provide higher resolution images of simple `<img>`s for devices with a `dppx` that is greater than `1`.

So how do I achieve something as simple like

```
<img src="foo_320.png" srcset="foo_640.png 2x">

```

with responsive image styles in Drupal?

# Answer
> 2 votes
1. Define your own breakpoints group with "multipliers" settings in YOURTHEME.breakspoints.yml (see D8 Docs)
2. Go to Admin \> Configuration \> Media \> Responsive Image Styles and add a new image style.
3. When creating the responsive image style, select your breakpoint group created in (1.). When your YAML is correct, you should see a separate detail set for every multiplier (=dppx).
4. Select type " Select a single image style." and select your corresponding image size. Repeat for every DPI group defined in your breakpoints.yml
5. In your node's display settings, for your image field, select the responsive image formatter and choose your responsive image style created in (2.)

---
Tags: 8, media, theming
---


# Question
Title: Loading content alone for each page from drupal to other site?
How to load only content in a page (exclude header & footer) from once specific drupal site to another non-drupal site page.

Like, if I click on link on non-drupal site it should open up drupal content of respective link page without header and footer in a new popup.

I know Iframe and webservice are options to do.

Is there any other way to load content for specific page in drupal to non-drupal site ? Thanks in advance.

# Answer
You could create a custom HTML template that would remove the HTML tags but that would render on a certain URL. However, that would make that URL every time it rendered. Web services are your best bet rendering the information an XML format. Below is the services module for Drupal 7

https://www.drupal.org/project/services
> 0 votes

# Answer
In your theme's page.tpl.php, you could do this.

```
<?php if (isset($_GET['embed'])) {
    print render($page['content']);
} ?>

<?php (!isset($_GET['embed'])): ?>

    the contents of your page.tpl.php file

<?php endif; ?>

```

That means you can add `?embed=true` (or just `?embed`) to a url and only the content blocks / node etc. will show.

I do similar to this for some node edit forms that I load in an iFrame inside a modal, like below.

```
page--node--article--edit.tpl.php
// just an example file path.

<?php

if (isset($_GET['modal'])) {
    print render($page['content']);
} else {
    include(drupal_get_path('theme', 'mytheme').'/page.tpl.php');
}
?>

```
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Create a Gmap with Views that connects locations of different nodes
I am looking for a way to make some sort of roadtrip website.

The idea is to use two node types: a parent nodetype "Roadtrip" and a child nodetype "Day". The user can create a Roadtrip and add a different Days to the Roadtrip. Every "Day" have a location field that needs to be filled in.

Then, I want to use Views with a Gmap display that I show on the parent Roadtrip node page using contextual filters. On that map, I want to show all the locations of the different Days and connect them to eachother in ascending order by publish date. So visually, you can see which trip someone made in how many days.

I am quite familiair with Views but can't wrap my head around Gmap and it's API so, anyone an idea how to achieve this?

# Answer
The function is not available in the gmap modules, and there was some work done in the Trackfield module that was similar but is deprecated.

You would want to use Google Maps Polylines to create the connection between the points.

https://developers.google.com/maps/documentation/javascript/examples/polyline-simple

Using this, you should be able to write a jQuery function that takes the nodes, sorts them by publish date, then loop over each and grab the lat/long to mark each point in which the lines should connect.
> 0 votes

# Answer
This answer is for D7, you'll need the folowing modules: entityreference to relate both contentypes, geolocation\_views only D7, it displays several nodes in a single map, geolocation, and simple\_gmap, this one is for for users to enter city name in a text field, handy tutorials: https://www.youtube.com/watch?v=hdzembWMgPc and https://www.youtube.com/watch?v=Pc0xPiRBb54 and https://www.youtube.com/watch?v=FVvKJlq4Wo8, you will end with something like this, each mark in map links to your day-node, enjoy.
> 0 votes

---
Tags: 7, views, location, google-maps
---


title: Migrate field_collections

text:
# Question
Title: Migrate field_collections
I'm using Drush and the migrate tools to migrate a Drupal 7 site to Drupal 8. The site uses field\_collections which do not migrate. The field\_collections page indicates it is probably being deprecated and recommends moving to paragraphs.

I have searched, but all of the custom migrations I have found so far have been flat fielded. I need to figure out a way to convert field\_collections to paragraphs, or field\_collections to custom entities.

I am generally comfortable with PHP and OOP, but building the entities and/or migrations in a new module have me confused.

How would I proceed to build a migration for a content type that included one or more field\_collections, so that the field\_collection data would be available in Drupal 8?

# Answer
There's a patch in development for the Paragraphs module to support migration in Drupal 8. This work is currently undergoing development with recent activity. This might be a good way to get a start on your own work and contribute back to the community.
> 1 votes

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


title: Slow Drupal 7 Load Time

text:
# Question
Title: Slow Drupal 7 Load Time
I have a 10 second page load time on Drupal 7.52. It has the approximately the same problem on localhost and my server.

On my localhost (WAMP) Apache uses an insignificant amount of CPU (3% or less). There is no sign of the localhost being limited by CPU, RAM, or Disk.

The MySQL queries are fast (50-250 ms total time). My page generation time is fast (100-350 ms).

Due to my server setup I cannot use APC.

I've tried searching for answers but most of the people are complaining about high cpu. I've got low cpu usage which is very weird.

I've tried disabling a lot of the modules and it didn't help.

How can I debug what is causing this slowness?

The website is www.energyjustice.net

# Answer
> 1 votes
Looks like my site was hacked. Bootstrap.inc was compromised and I have yet to find the source of the problem. But it might be related to an old security vulnerability.

https://www.drupal.org/forum/support/post-installation/2016-01-27/includesbootstrapinc-hackedchanged-constantly

The hack causes the website to try to load two URLs. The CURL timeout is 5 seconds. Thus the 10 second delay.

This is called the Pharma hack. It happened in February 2015, and the problem was that I only partially cleaned it. This allowed it to reinfect.

# Answer
> 0 votes
Most likely the issue is with the frontend CSS or JS due to the page generation time of 0.35s but page load times of 10 seconds. The network tab of your web browser (firefox, chrome) should help; you can also use http://www.webpagetest.org/ to get the same info.

# Answer
> 0 votes
the server itself loads a text file very fast (ie /robots.txt ) its seems like you are minifying and combining css/js files

have you enabled cache in `admin/config/development/performance` ? have you enabled cache on all the sidebar block views ?

create a page (a hidden one) with no blocks on the sidebars see if it loads faster if its faster progressively add all the blocks and see which one seems to slow it down

perhaps one of the blocks involves a view with a SLOW query

---
Tags: 7, performance
---


# Question
Title: How to put Inline Entity Form in another form (without widget)?
My end goal is to put the Inline Entity Form inside of a custom widget, and have it submittable without submitting the parent form inside of which it has been placed.

I'm not sure how to do this programmatically. I looked for an example in the tests/ subdirectory of IEF, and found a form like this:

```
$form['inline_entity_form'] = [
  '#type' => 'inline_entity_form',
  '#entity_type' => 'node',
  '#bundle' => 'ief_test_custom',
  '#form_mode' => $form_mode,
];
$form['submit'] = [
  '#type' => 'submit',
  '#value' => t('Save'),
];

```

But if I take this code and put it inside an existing form via hook\_form\_alter or a custom widget, it will submit the entire form, when in reality I just want it to save the values for the reference. I also tried to experiment by putting a rendered form into an iframe, but it wouldn't load the form code inside it.

```
$form = \Drupal::formBuilder()->getForm(\Drupal\user\Form\UserLoginForm::class);

$ief = [
  '#type' => 'inline_entity_form',
  '#entity_type' => 'node',
  '#bundle' => 'article',
  '#default_value' => \Drupal\node\Entity\Node::load(1),
  '#form_mode' => 'default',
];

$element['inline_entity_form'] = [
  '#type' => 'inline_template',
  '#template' => '<iframe srcdoc="<div id="iframe-ief">{{ ief|escape }}</div>"></iframe>',
  '#context' => [   // Tried the above with & without |escape
    'ief' => $form, //<--tried both $form and $ief here.
  ],
];

```

Is there any example of doing this that I can look for, or any suggestions or which direction to look?

# Answer
i would do it via ajax submit handler. yes you will recieve the full node but you can just take the necessary values and save it directly yourself.

see this post for how to do ajax in forms: ajax\_example\_add\_more - Drupal 8
> 1 votes

# Answer
I ended up making a Form like this:

```
public function buildForm(array $form, FormStateInterface $form_state, $form_mode = 'default') {
  $node_id= \Drupal::request()->get('node_id');

  $form['ief'] = [
    '#type' => 'inline_entity_form',
    '#entity_type' => 'node',
    '#bundle' => 'article_reference',
    '#form_mode' => $form_mode,
    '#default_value' => \Drupal\node\Entity\Node::load($node_id),
    '#save_entity' => true,
  ];
  $form['ief_submit'] = [
    '#type' => 'submit',
    '#value' => t('Save'),
    '#ajax' => array(
      'event'=>'click',
      'callback' => '::ajaxSubmit',
      'name' => 'submit1',
     ),
  ];
  return $form;
}

public function ajaxSubmit(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $response = new AjaxResponse();

  if ($form_state->getErrors()) {
  }
  else {
    $response->addCommand(new \Drupal\Core\Ajax\CloseModalDialogCommand());
  }

  return $response;
}

/**
 * {@inheritdoc}
 */
public function submitForm(array &$form, FormStateInterface $form_state) {
  \Drupal\inline_entity_form\Element\InlineEntityForm::submitEntityForm($form['ief'], $form_state);
  drupal_set_message(t('Updated @entity_type @label.', ['@entity_type' => $form['ief']['#entity']->getEntityType()->getLabel(), '@label' => $form['ief']['#entity']->label()]));
}

```

And then called that form (by it's route in the routing.yml) using the modal method I found here: http://www.innoraft.com/blog/popups-drupal-8-no-problem

If anyone has a more Drupal-y way to do this, feel free to let me know. But, I like the modal, it feels very clean.
> 1 votes

---
Tags: 8, forms
---


# Question
Title: How do I redirect a node to a path followed by a wildcard?
I have a basic page node that contains two views in block form. The views both contain contextual filters captured from the URL. How to I publish my node to allow the user to visit /report/2002, or /report/2004, or /report/2010. The blocks are configured to display on /report/\*. How do I do the same for a node?

Do I need to make my own controller with custom routing?

# Answer
A view with a page display instead of the block display would generate the route automatically.
> 1 votes

---
Tags: 8, nodes, redirection
---


# Question
Title: Full archive configuration export doesn't work
When I go to `/admin/config/development/configuration/full/export` and want to export the full archive, the site loads for a while and then just goes completely blank and the URL bar shows `/admin/config/development/configuration/full/export-download`.

There is no error in the server log files and no entry in the Drupal reports.

In the sync directory `sites\default\files\config_[...]\sync` there is no file except for the .htaccess.

And when I try `drush cex` or `drush cex sync` this error occurs:

```
PHP Fatal error:  Declaration of Drush\Command\DrushInputAdapter::hasParameterOption($values) must be compatible with Symfony\Component\Console\Input\InputInterface::hasParameterOption($values, $onlyParams = false) in C:\Program Files (x86)\DevDesktop\tools\vendor\drush\drush\lib\Drush\Command\DrushInputAdapter.php on line 27

```

I've tried everything with the `settings.local.php` enabled and disabled. But the export just doesn't work. What can I do?

# Answer
Firstly, What is the version of drush?

I advise that you use the **console bundle**(add it via composer: "drupal/console": "~1.0")

and then execute this command

```
drupal config:export  --directory="modules/custom/import_export_config/config/install/"

```
> 1 votes

---
Tags: 8, importing-exporting, configuration
---


# Question
Title: Can not see test modules in module install page
In Drupal 7, tests module can be added with `hidden = TRUE` property in `.info` file to not to display on modules list page, but tests can find and enable them using `protected $modules` property.

But Drupal 8 doesn't have this property and the test modules don't appear in modules list page. How does it work?

# Answer
> 0 votes
Test modules are under `module_name/tests/` or `module_name/tests/directory` and can be enabled by `TestDiscovery` service. As `ExtensionDiscovery::scan()` calls `TestDiscovery::getExtensions()` method with `$include_test` flag `TRUE`.

The flag can be overridden by settings: if (!isset($include\_tests)) { $include\_tests = Settings::get('extension\_discovery\_scan\_tests') || drupal\_valid\_test\_ua(); }

See also ExtensionDiscovery::scanDirectory and RecursiveExtensionFilterIterator::acceptTests()

For manually enabling and testing a test module, it could be moved under modules directory (from /tests) and move back once development done to enable it via test.

---
Tags: 8
---


# Question
Title: When do hook_views_data() and hook_views_data_alter() get called?
I'm working on a site I inherited that has a functioning `hook_views_data_alter()` implementation. I can see things in the Views editor that it has added. However, I cannot figure out how on earth to get that function to be called again so I can change the data. I am running xdebug with a breakpoint in the function body, and nothing I do, from editing a view, to adding a relationship, to clearing the cache or rebuilding the registry, trips that breakpoint. Not even putting `module_invoke_all('views_data_alter');` in index.php. What do I need to do to get Drupal to run that hook again?

# Answer
In case anyone else is making the same mistake I was, here's the answer.

1. First of all, `hook_views_data()` will not ever, ever be called if you put it in yourmodule.module. It has to be in yourmodule.views.inc.
2. You should probably implement `hook_views_api()` to tell Drupal where your yourmodule.views.inc file resides; for example with code similar to the following one.

```
function yourmodule_views_api($module = NULL, $api = NULL) {
  return array(
    'api' => '3.0',
    'path' => drupal_get_path('module', 'yourmodule') . '/includes/views',
  );
}

```

This tells Drupal that yourmodule.views.inc can be found at yourmodule/includes/views/yourmodule.views.inc. If you don't implement `hook_views_api()`, put the .inc file in the same folder as your .module file.

Once you have this set up, `yourmodule_views_data()` will be called when you clear the caches.
> 0 votes

---
Tags: views
---


title: Override buildForm() in another module

text:
# Question
Title: Override buildForm() in another module
I would like to override the `buildForm()` method of the Comment module in my custom module.

The method is defined in core/modules/comment/src/Form/CommentAdminOverview.php.

To achieve this, I've created myModuleName/src/Form/MyModuleNameCommentAdminOverview.php, whose first lines are the following.

```
namespace Drupal\myModuleName\Form;

use Drupal\comment\CommentInterface;
use Drupal\comment\Form\CommentAdminOverview;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\user\PrivateTempStoreFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;

class myModuleNameCommentAdminOverview  extends CommentAdminOverview {
  public function buildForm(array $form, FormStateInterface $form_state, $type = 'new') {
    // ...
  }
}

```

In myModuleName.info.yml I have these lines.

```
 dependencies:
  - comment:comment

```

My code is not working. What am I doing wrong?

I have read the following, but I don't understand what I'm doing wrong.

# Answer
> 3 votes
These are the two routes for the original form class:

*comment.routing.yml:*

```
comment.admin:
  path: '/admin/content/comment'
  defaults:
    _title: 'Comments'
    _form: '\Drupal\comment\Form\CommentAdminOverview'
    type: 'new'
  requirements:
    _permission: 'administer comments'

comment.admin_approval:
  path: '/admin/content/comment/approval'
  defaults:
    _title: 'Unapproved comments'
    _form: '\Drupal\comment\Form\CommentAdminOverview'
    type: 'approval'
  requirements:
    _permission: 'administer comments'

```

You have to alter both routes like this

```
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('comment.admin')) {
      $route->setDefault('_form', '\Drupal\mymodule\Form\MyForm');
    }
  }

```

in a RouteSubscriber.

---
Tags: 8, forms, comments
---


# Question
Title: Paragraph how to get content level wise?
Using module https://www.drupal.org/project/paragraphs.

On Admin side I have made content as a 3 level categories. Main Category, Sub Category, Sub Category.

Each category have their content as well.

On twig file when i print

```
{{ content }}

```

It display all data. Which is correct.

I need to fetch individual category & their content & do the styling for each.

How can i retrieve that each field in loop?

# Answer
> 0 votes
You can use this template file:

*/themes/mytheme/templates/field--paragraph--field-category--faq.html.twig:*

```
    <div{{ attributes }}>
        {% for item in items %}
            <div{{ item.attributes }}>{{ item.content }}</div>
        {% endfor %}
    </div>

```

---
Tags: theming, 8, paragraphs
---


# Question
Title: Find webform submission ID in a custom submission handler
I have created a webform custom submission handler.

```
public function submitForm(array &$form, FormStateInterface $form_state,  WebformSubmissionInterface $webform_submission) {
  $webform_submission->getDate();
}

```

I am getting all the submitted values except the submission id. How do I get that value?

# Answer
> 2 votes
I have been able to get the submission ID in a custom submission handler using the following code.

```
$webform_submission->setSticky(!$webform_submission->isSticky())->save();
$sid = $webform_submission->id();

```

---
Tags: webforms
---


title: Getting only TID by Entity Query

text:
# Question
Title: Getting only TID by Entity Query
I am using Drupal 8. By retrieving an entity by Entity Query I am getting an array. How can I fetch directly the TID?

Right now I am doing the following:

```
  public function getCommuneTidByPostalCode(int $postalCode) {
    $commune = \Drupal::entityQuery('taxonomy_term')
      ->condition('field_zipcode', $postalCode)
      ->condition('vid', 'commune')
      ->execute();

    if (!empty($commune)) {
      return intval(key($commune));
    }
  }

```

Can I drop somehow this part?:

```
if (!empty($commune)) {
  return intval(key($commune));
}

```

# Answer
No. An entity query always returns a list, if you want just one record, you have to get that from the array.

The intval() isn't really necessary though, Drupal/PHP doesn't care if you use the tid as string or integer. Also, it always returns an array, and key() also works on an empty array, so you can really simplify that to just `return key($communie);`. And I'd actually recommend to use `current()` or `reset()` because the key is the revision ID and the value the ID and while terms currently do not yet use revisions, they will likely soon support that.

So...

```
$commune = \Drupal::entityQuery('taxonomy_term')
  ->condition('field_zipcode', $postalCode)
  ->condition('vid', 'commune')
  ->execute();

return current($commune);

```

Is all you need.
> 4 votes

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


title: D7 CKEditor missing buttons

text:
# Question
Title: D7 CKEditor missing buttons
I'm using:

* Drupal 7
* CKEditor 7.x-1.18
* Jquery Update 7.x-3.0 (running jquery version 1.10)

**I don't understand how to make the 'Font' & 'Size' dropdowns appear on the CkEditor interface**.

* The first image shows the settings for the "Full HTML" profile.
* The second image shows the CkEditor in action. You can see that there are lots of buttons missing, but at the moment, I'm only interested in making the 'Font' & 'Size' dropdowns appear. You'll also notice that even though "Styles" hasn't been selected on the "Full" profile - it still appears here !?!?

I have been to the CKEditor site and downloaded the full package from here: http://ckeditor.com/download

The existing CKEditor install says to download, "Then uncompress the contents of the "ckeditor" directory of the downloaded file to this folder (modules/ckeditor/ckeditor)."

I appreciate similar questions have been asked before, but none of the solutions offered have worked for me.

*pic 1 (above) Editing the Full HTML profile for CkEditor*

*pic 2 (above) Buttons are missing, and Styles has appeared !?*

# Answer
> 0 votes
Hugronaphor's comment helped me find a solution that worked for me... I'm just going to explain it clearly.

* Browse to /admin/config/content/ckeditor
* Edit the **CKEditor GLOBAL Profile**
* Under the "Advanced Settings", change the "Path to CKEditor"

What you enter here will depend on whether you have downloaded and installed the full package (as described in my initial question) and where you have installed it, or whether you want to use the CDN. The instructions given below the text box are quite clear, but much like anything, it's just knowing where to look !

Because I'd already installed the full package and installed it to "modules/ckeditor/ckeditor" it means instead of using the CDN, I entered "**%m/ckeditor**" which made it work perfectly.

If I'd installed the full package to "/sites/all/libraries/ckeditor" I would have entered "**%l/ckeditor**"

...and if I wanted to use the CDN version, I would have entered "**//cdn.ckeditor.com/4.4.3/full-all**" Although, I assume this version number will possibly change in the future

---
Tags: 7, wysiwyg
---


# Question
Title: Is there any way to connect to a second (MySQL) database in a Kernel Base test?
Right now I have configured this environment variable in my phpunit.xml to connect to a Drupal database in a SQLite file:

```
<env name="SIMPLETEST_DB" value="sqlite://localhost//Users/jepster/Dev/my-project/project/docroot/sites/default/files/db.sqlite"/>

```

This works fine. But can I also connect to a second database like I am doing in the settings.php?

```
$databases['second-database']['default'] = array(
  'database' => 'second-database',
  'username' => 'second-database',
  'password' => 'second-database',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

```

Currently my Kernel Base Test fails with the following error:

> The specified database connection is not defined: second-database

That's because I want to connect to my database from a service constructor:

```
  public function __construct() {
    $this->database = Database::getConnection('default','second-database');
  }

```

I have been digging in the Drupal core Kernel Base Tests ("core" folder), but I could not find a way there.

# Answer
I have figured it out. The setUp() method in my Kernel Base Test must look like that:

```
/**
 * {@inheritdoc}
 */
protected function setUp() {
    parent::setUp();

    $databases['second-database']['default'] = array(
        'database' => 'second-database',
        'username' => 'second-database',
        'password' => 'second-database',
        'prefix' => '',
        'host' => 'localhost',
        'port' => '3306',
        'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
        'driver' => 'mysql',
    );
    Database::setMultipleConnectionInfo(
        $databases
    );
}

```
> 5 votes

---
Tags: 8, database, testing
---


# Question
Title: User registration without email address OR registration with pseudo-email address
I am programmatically creating users for the roles Parent (Adult) & Child (minor). During registration, minors (Children) typically will not have email addresses but Drupal user registration requires email address.

During registration of minor, unfortunately, the adults email address cannot be reused based on Drupal’s one email rule.

My queries are as follows:

1. Is it possible that we can create users without email address?
2. If not 1. can we use some pseudo-email address that we can created for each minor. However, emails for any minor should be sent to the adults address instead.

# Answer
> 0 votes
I think you need an email address, but I could be wrong about this.

You can definitely provide a fake email address though.

For example, you can use `hook_form_alter()` to modify the registration form:

```
function MYMODULE_form_user_register_form_alter(&$form, FormStateInterface &$form_state, $form_id) {
  // Hide the mail form
  $form['account']['mail']['#access'] = FALSE;
  // Set the email address to minor+UID@mydomain.com
  // You need to write this code yourself...

```

Make sure you set the email address to include the UID or something similar that will ensure the email is unique; Drupal has to have a unique email for each account.

Then, use hook\_mail\_alter to check the user's role and, if the user is a minor, query the parent's email address and send the parent an email instead.

---
Tags: 8, users
---


title: How to add content-type in views markup

text:
# Question
Title: How to add content-type in views markup
This doesn't strike me as a very complex problem so I'm hopefully just missing something obvious.

I've got a views\_bootstrap grid that shows fields of multiple content types. However the View doesn't output what content type each element is.

How can I get the content type in the markup as a css class which I then can style?

Use case: I'd like to be able to style grid elements different on basis of what content type it is. For example:

* Grid elements of content type 1 should be 400px high
* Grid elements of content type 2 should be 650px high

# Answer
You could add in your view a hidden field with the content type and either rewrite the results of each field and add wrapper to each field using the available value (content type) or theme the specific view and add a class to the row wrapper based on content type (which still is passed to your view as a field).

Update:

In case you need to add a class to the row:

For D7 in Advanced settings you can check the theme: information and create template file for your rows based on the suggestions of the informations.

If you work on D8 you can create a template file check (https://api.drupal.org/api/drupal/core%21modules%21views%21templates%21views-view-grid.html.twig/8.0.x) where you have all the views data so as you can add all a wrapper to each row.

Whatever version you use have a look at theme hook suggestions D7 - https://www.drupal.org/docs/7/theming/template-theme-hook-suggestions and D8 - https://api.drupal.org/api/drupal/core%21modules%21views%21views.theme.inc/group/views\_templates/8.2.x in order to make sure how to name your template and which template you really need.

If you just need to add a class to a field:

In your views put your content type field at the top of the fields and add a new field or edit an existing one. Go to REWRITE RESULTS and select Rewrite the output of this field. Below of this you will find a list of all the replacement patterns which you can use to create your own markup with all the details you need.

Good luck!
> 1 votes

---
Tags: views, theming
---


# Question
Title: adding or remove multiple classes with attributes.addClass
In my page template I can add a single class and remove a single class like this `<aside{{attributes.addClass(sidebar_first_classes).removeClass('content_classes') }}>` But now I want to add a single class and remove two classes, and this does not work `<asideright{{attributes.addClass(sidebar_second_classes).removeClass('content_classes','sidebar_first_classes') }}>`

# Answer
> 4 votes
From the documentation for addClass and removeClass:

> attributes.removeClass()
>
> Removes a class from an Attribute object. Used similarly to addClass. Let's say you get the classes variable from somewhere else like a preprocess function.
>
> {% set classes = \[ 'red', 'green', 'blue' \] %}
>
> \<div{{ attributes.addClass(classes).removeClass('green') }}\>\</div\> outputs \<div class="red blue"\>\</div\>.

So either you need to use an array to remove multiple classes or make multiple calls the removeClass and a single class.

---
Tags: theming, 8
---


# Question
Title: What is the best caching solution for website with a lot of content?
We are building a website with over a million nodes. Those nodes also have paragraphs which increases the number of entities. Therefore, the cache tables are getting bigger and bigger, especially the cache\_entity and cache\_render tables.

What is the best way to avoid the database to get too big (we're talking hundred of gigabytes) ? Is memcache a solution here or is it just deporting the problem of disk space ?

The basic cron task doesn't clear the tables. We were also thinking about setting a cron task to execute "drush cr".

According to that post and that issue, Drupal 8.4 will have a better cache table management.

# Answer
Part of the solution could be to compress those cache tables where the typical values to cache are quite big and allow for a high compress ratio. I think render caches fit that description very well.

See e.g. issue \[#1281408\] and a comment on another issue mentioned in comment #23.
> 0 votes

---
Tags: 8, caching
---


# Question
Title: Query and load entity by Entity Type Manager
Currently I am firstly "searching" for an taxonomy term entity with the Entity Query in Drupal 8:

```
$termIds = \Drupal::entityQuery('taxonomy_term')
  ->condition('field_code', $code)
  ->condition('vid', 'computer')
  ->execute();

```

And then I am loading the taxonomy term entity:

```
      $termId = current($termIds);
      $term = \Drupal::entityTypeManager()
        ->getStorage('taxonomy_term')
        ->load($termId);

```

Is there a way to do it in 1 step, instead of these two?

# Answer
You can do this in one step by using loadByProperties():

```
$term = current(\Drupal::entityTypeManager()->getStorage('taxonomy_term')
  ->loadByProperties(['field_code' => $code, 'vid' => 'computer'])
);

```

This method is a shortcut for basic entity queries like you have here and also includes the step for loading the entities.
> 17 votes

---
Tags: 8, entities
---


# Question
Title: How to show a menu link that is hidden because the role has no permission to see the linked page?
I need show a menu link that links to `/node/add/article` for anonymous users but they don't have access to that page.

I have seen solutions like:

* Using an absolute URL (that way Drupal does not check user access).
* Alter the menu access callback but I do not really want to give them access just to print the link.

Are there any other solutions?

# Answer
In your case you can use two menu entries in the same menu:

* One pointing to `/node/add/article`.
* Another one pointing to `/user/login`.

First link is only visible to registered users, because anonymous users don't have permissions to add articles.

Second link is only visible to anonymous users because registered users don't have permissions to see the user login page (because they are already logged in).

The result is a menu with only one menu entry. Registered users see first link, anonymous see only second one.
> 2 votes

---
Tags: 8, navigation
---


# Question
Title: content type is not saved when altering the node add form
Here, I have alter the `add content type` form as follows

```
function hc_listings_form_alter(&$form, &$form_state, $form_id)
{
//    print_r($form_id);
    if($form_id =='home_care_popular_search_region_node_form'){
        dpm($form,'form');
        $selected_states=hc_listings_load_agecare_regions();
//        dpm($selected_states,'selected');
        reset($selected_states);
        $first_state = key($selected_states);
//        dpm($first_state,'$first_state');

      $form['field_popular_state']=array(
            '#type' => 'select',
            '#default_value' => array_shift($selected_states),
            '#title' => t('Popular State'),
            '#description' => t('Home Care Popular State'),
            '#options'=>hc_listings_load_agecare_regions(),
            '#ajax'=>array(
                'callback'=> 'hc_popular_region_form_ajax',
                'wrapper'=> 'regions_list',
                'event'=>'change',
                'method'=>'replace',
//                'effect'=>'fade'
            ),
            '#required' => TRUE,
      );
     $form['field_popular_region']=array(
         '#type' => 'container',
         '#tree'=>TRUE,
         '#prefix'=>'<div id="regions_list">',
         '#suffix'=>'</div>'

     );
     $form['field_popular_region']['list']=array(
        '#type' => 'checkboxes',
        '#title' => t('Popular Search Regions'),
        '#description' => t('Home Care Popular Search Regions'),
        '#options'=>get_popular_regions($first_state),
        '#required' => TRUE,

     );
   }
}

```

And the ajax Callback function is as follows:

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

  if(isset($form_state['values']['field_popular_state'])){

    $state=$form_state['values']['field_popular_state'];
    hc_my_log($state);

    $form['field_popular_region']['list']=array(
        '#type'=>'checkboxes',
        '#title'=>'Popular Search Regions',
        '#description'=>'Home Care Popular Search Regions',
        '#options'=>get_popular_regions($state)
    );

    hc_my_log($form['field_popular_region']['list']);

    $form['field_popular_region']['list']=form_process_checkboxes($form['field_popular_region']['list']);

   }
//    $form_state['rebuild'] = true;
    return $form['field_popular_region'];

}

```

This works but when the ajax callback is called it will execute the `dpm($form,'form')` (line:5) too.What is the reason for this...

And after that when I am submitting the form by clicking the default `Save` button in the node add form both `popular regions` and `popular states` values are not saved.What will be the cause of that? Should I have to alter the submission of the node too ?

Please help me with this ..Thanks in advance

# Answer
Here, I have altered the form fields in a wrong way so in the form submission it alerts me with errors saying that the form structure has been changed in my altering.

The error is that it is not directly targetting the specific form field..so it should be corrected as follows:

```
if($form_id =='home_care_popular_search_regions_node_form'){

    $selected_states=hc_get_states();
    reset($selected_states);
    $first_state = key($selected_states);
    dpm($first_state,'$first_state');
    $state= (isset($form_state['values']['field_popular_state']['und'][0]['tid']))?$form_state['values']['field_popular_state']['und'][0]['tid']:$first_state;

    //popular states field altering
    $form['field_popular_state']['und']['#default_value']=$selected_states[$first_state];
    $form['field_popular_state']['und']['#options']=$selected_states;
    $form['field_popular_state']['und']['#ajax']['callback']='hc_popular_region_form_ajax';
    $form['field_popular_state']['und']['#ajax']['wrapper']='regions_list';
    $form['field_popular_state']['und']['#ajax']['method']='replace';
    $form['field_popular_state']['und']['#ajax']['event']='change';

    //popular regions field altering
    $form['field_popular_region']['und']['#prefix']='<div id="regions_list">';
    $form['field_popular_region']['und']['#suffix']='</div>';
    $form['field_popular_region']['und']['#options']=hc_get_popular_regions($state);

```

}

Ajax callback is as follows:

```
function hc_popular_region_form_ajax($form, &$form_state){
   return $form['field_popular_region'];
}

```

**Note**: the method `hc_listings_load_agecare_regions()` has been changed to `hc_get_states()`
> 0 votes

---
Tags: forms, ajax, hooks
---


# Question
Title: With enabling modsecurity_crs_41_sql_injection_attacks all submit form return forbidden 403
I installed and activated the module mod\_security. then I enabled the modsecurity\_crs\_41\_sql\_injection\_attacks.conf.

For each form, when I submit, I have an error 403 forbidden

**Error log:**

```
[Wed Nov 15 16:53:03.324516 2017] [:error] [pid 27760] [client] ModSecurity: Access denied with code 403 (phase 2). Pattern match "([\\\\~\\\\!\\\\@\\\\#\\\\$\\\\%\\\\^\\\\&\\\\*\\\\(\\\\)\\\\-\\\\+\\\\=\\\\{\\\\}\\\\[\\\\]\\\\|\\\\:\\\\;\\"\\\\'\\\\\\xc2\\xb4\\\\\\xe2\\x80\\x99\\\\\\xe2\\x80\\x98\\\\`\\\\<\\\\>].*?){4,}" at ARGS_NAMES:field_cl_address[0][format]. [file "/usr/share/modsecurity-crs/activated_rules/modsecurity_crs_41_sql_injection_attacks.conf"] [line "159"] [id "981173"] [rev "2"] [msg "Restricted SQL Character Anomaly Detection Alert - Total # of special characters exceeded"] [data "Matched Data: ] found within ARGS_NAMES:field_cl_address[0][format]: field_cl_address[0][format]"] [ver "OWASP_CRS/2.2.9"] [maturity "9"] [accuracy "8"] [tag "OWASP_CRS/WEB_ATTACK/SQL_INJECTION"] [hostname "www.d8.dev.xxxx"] [uri "/node/add/occlient/19784"] [unique_id "Wgxw738AAQEAAGxw91sAAAAO"]

```

Can anyone explain the cause?

# Answer
I found the solution by consulting the log:

```
[Wed Nov 15 16:53:03.313249 2017] [:error] [pid 27752] [client 54.208.242.36] ModSecurity: Access denied with code 403 (phase 2). Pattern match "(^[\\"'`\\xc2\\xb4\\xe2\\x80\\x99\\xe2\\x80\\x98;]+|[\\"'`\\xc2\\xb4\\xe2\\x80\\x99\\xe2\\x80\\x98;]+$)" at ARGS:field_cl_ref_no[508752]. [file "/usr/share/modsecurity-crs/activated_rules/modsecurity_crs_41_sql_injection_attacks.conf"] [line "64"] [id "981318"] [rev "2"] [msg "SQL Injection Attack: Common Injection Testing Detected"] [data "Matched Data: '\\x22 found within ARGS:field_cl_ref_no[508752]: '\\x22()"] [severity "CRITICAL"] [ver "OWASP_CRS/2.2.9"] [maturity "9"] [accuracy "8"] [tag "OWASP_CRS/WEB_ATTACK/SQL_INJECTION"] [tag "WASCTC/WASC-19"] [tag "OWASP_TOP_10/A1"] [tag "OWASP_AppSensor/CIE1"] [tag "PCI/6.5.2"] [hostname "www.d8.dev.xxxx"] [uri "/node/add/occlient/19784"] [unique_id "Wgxw738AAQEAAGxoJOMAAAAH"]

[Wed Nov 15 17:19:51.286111 2017] [:error] [pid 28380] [client] ModSecurity: Access denied with code 403 (phase 2). Pattern match "(?i:(?:\\\\A|[^\\\\d])0x[a-f\\\\d]{3,}[a-f\\\\d]*)+" at ARGS:form_token. [file "/usr/share/modsecurity-crs/activated_rules/modsecurity_crs_41_sql_injection_attacks.conf"] [line "55"] [id "981260"] [rev "2"] [msg "SQL Hex Encoding Identified"] [data "Matched Data: E0X10B found within ARGS:form_token: xCyRB87OqEoGB47ngDdQJ0gVaIa5fy4JtgE0X10BVW0"] [severity "CRITICAL"] [ver "OWASP_CRS/2.2.9"] [maturity "8"] [accuracy "8"] [tag "OWASP_CRS/WEB_ATTACK/SQL_INJECTION"] [tag "WASCTC/WASC-19"] [tag "OWASP_TOP_10/A1"] [tag "OWASP_AppSensor/CIE1"] [tag "PCI/6.5.2"] [hostname "d8.dev.xxxx"] [uri "/node/1369392/edit"] [unique_id "Wgx3N38AAQEAAG7cNtYAAAAK"]

```

I disabled the rules id 981173 and 981260 in vhost and then it turns

```
<Directory /var/www/html>
                Order allow,deny
                Allow from all
                Options +FollowSymLinks +ExecCGI
                RewriteEngine On
                AllowOverride All

            <IfModule security2_module>
                    SecRuleRemoveById 981245
                    SecRuleRemoveById 981248
                    SecRuleRemoveById 981173
                    SecRuleRemoveById 981231
                    SecRuleRemoveById 950901
                    SecRuleRemoveById 981260
            </IfModule>

    </Directory>

```
> 0 votes

---
Tags: 8, security
---


# Question
Title: Setting up Multisite on windows server with IIS7
First off I'm not a server person. New windows box spun up, IIS7 was used to install one instance of Drupal 7. Great :)

However I need to have multiple sites running. I've read several tutorials on getting this to work, tried several solutions, and continue to gets errors (from page not found to "this drupal site is already set up"). Does anyone know if there are step by step instructions somewhere on exactly how to set up multisite on a windows box with IIS7?

The "base" drupal install is /inetpub/wwwroot/Drupal/DrupalTest/

Having very little knowledge of Windows servers is probably part of the issue. I really need basic step by step instructions and I have yet to locate any that assume you know essentially zero about windows. I've been taking notes so I can write some out if I eventually figure it out :)

One example I've followed: http://drupal.org/node/554336 : Yielded the "site already setup" when I tried to access the install.php from the second site.

---

I'm at the point where multisite would be nice, but if I need to use multiple instances of Drupal that's fine, I just need to be able to move forward with the content and be finished messing with the dang server, but I have no idea how to accomplish that as well.

# Answer
> 2 votes
After much digging, found out the combo of msSQL and PHP 5.3 caused the site to break. Reinstalled with PHP 5.4 and mySQL and it's running swimmingly!

# Answer
> 0 votes
If any one still using IIS server to configure the multisite on drupal its pretty simple. First thing is make sure of two important files that need to be modified. **sites.php settings.php**

you don't need the local files (settings.local.php and sites.local.php) for multi site setup.

Configuring the above two files would be enough to setup the multi site on IIS. https://www.drupal.org/docs/7/multisite-drupal/multi-site-on-windows-using-iis

# Answer
> -1 votes
Hi you can read more on how to install multisite in drupal 7 with below links.

http://mydons.com/drupal-7-multisite-install-steps-in-windows/

---
Tags: installation
---


# Question
Title: Kernel Base Test: Create node content types and taxonomy vocabularies via configuration?
Does anybody know, how the mentioned entity types can be setup via configuration Yaml files? Right now I am setting up my entity types for a Kernel Base Test like the following:

```
Vocabulary::create([
  'name' => 'Kreise',
  'vid' => 'districts',
])->save();

$stringFields = [
  'field_district_number',
];
$this->saveFields($stringFields, 'string', 'districts', 'taxonomy_term');

$booleanFields = [
  'field_searchable'
];
$this->saveFields($booleanFields, 'boolean', 'districts', 'taxonomy_term');

```

Is it possible to quickly load the entity type configuration by an existing site configuration to save time? Because I already have configured entity types in my site configuration. It seems like an not necessary additional step, to code the entity configuration for my test.

# Answer
Here is documentation for using the configuration. So for example, if you want to load Tags Vocabulary you will do:

```
$config = \Drupal::service('config.factory')->getEditable('taxonomy.vocabulary.tags');
$description = $config->get('description');

```

$description contains the description of the vocabulary. In this way, you can load what you want from the yml file.
> 0 votes

---
Tags: 8, testing
---


# Question
Title: How to open accordion when setting error?
I have custom validation on an element using \['#element\_validate'\].

But the element is within an accordion item within an accordion and the error doesn't signal to the parent elements to open up when the form is reloaded with the errors.

Is there a way to signal to an elements groups to open up when doing `$form_state->setError($element)` on an element?

# Answer
I have added this an issue on the field\_group module and have posted a patch: https://www.drupal.org/project/field\_group/issues/2923831
> 1 votes

---
Tags: 8, forms
---


# Question
Title: Is it safe to truncate a field revision table?
I noticed D7 creates a field\_revision table for every field, and duplicates the content from its field table counterpart even if one has revisions turned off.

I have a big text table and it is taking up a lot of space (several GBs).

Would it be safe to truncate the revision table?

PS: Meanwhile, I have also reported this as a bug.

# Answer
I think there the Field SQL norevisions module will help you out:

> Field SQL norevisions provides a field storage backend that prevents entity revisions from being saved to the MySQL storage backend.
>
> The purpose of the module is to reduce the amount duplicated data that is saved on large Drupal sites that do not use revisions. It has the additional performance benefit of halving the number of queries during creating entities with fields.

This module will not allow revision fields to be created so it will increase your performance as number of queries will get reduced, besides that you will have no revisions on nodes further.

Also you can use some custom module codes provided on following URL:

http://www.ambidev.com/make-your-drupal-7-faster-by-removing-all-revisions/

and this module to delete revision entries:

https://www.drupal.org/project/node\_revision\_delete
> 3 votes

# Answer
You should have a look at this How I can delete all node/field revisions?, and perhaps subscribe to http://drupal.org/node/1063266#comment-5268252
> 1 votes

# Answer
No, it is not safe. I am using Drupal 7. I use quiz module on my website, and I noticed there at least were two error when I emptied all the field\_revision\_\* one with variable error which I do not really remember, and the other one was the questions were disappeared.

Oddly enough, answer options were there, but all the questions were gone. I did not look into more details, I put the field\_revision\_\* tables back and it started working properly.

All I can say is if you use quiz module and go to myPHPAdmin and truncate these tables, you will get errors. If you don't use quiz module, I don't know. but it is not bulletproof. I would recommend using some proven modules to clear your revisions.
> 0 votes

---
Tags: 7, entities, database, nodes
---


# Question
Title: How to specify the correct private file path in a block
I have a Drupal site at http://example.org/xyz

Per the instructions here, I have set up a private file directory outside the web root.

So let's say the web root is at /home/public\_html/example/xyz The private directory is at /home/public\_html/private

I have that private directory set in the settings.php file and cleared the caches. It shows up correctly here: http://example.org/xyz/admin/config/media/file-system

After clearing the cache, I can indeed confirm there is a valid .htaccess file in /atrium/admin/config/media/file-system

The directory permissions for the private directory are 755.

So now I specify the file location of a link in a block as "/xyz/system/myfile.pdf"

When I click the link, the home page simply reloads (instead of a download window), but the URL now reads: http://example.org/atrium/system/myfile.pdf

I've tried many other variations, and they all fail.

What am I doing wrong?

# Answer
> 0 votes
drupal will not let you specify a direct link to a private file

If you upload the file using file field (core) then you can use views to display the file in a block using `block display` and use https://www.drupal.org/project/private\_files\_download\_permission for fine grained permissions on who can download the file

if you want to program this behaviour then you have to look at using `file_create_url` in a custom module

```
$fid = 1; //set fid to your file's fid.
$downloadlink = file_create_url(file_load($fid)->uri);

```

and this link will hide the actual path where you private file is

for more details you can look at

How can I get the URL to the public files directory?

https://api.drupal.org/api/drupal/core%21includes%21file.inc/function/file\_create\_url/8.2.x

---
Tags: 8, files
---


# Question
Title: When should I "send mail by queue" with the SMTP module?
On the SMTP module configuration page at `/admin/config/system/smtp`, it offers the option to **Send mail by queue** (*Mails will be sent by drupal queue api.*).

When would I want to check this box? What are the advantages and disadvantages?

# Answer
TL;DR: send the email by queue if you are sending larger number of emails at once, or if your SMTP server takes longer time to process a request (for whatever reason).

Below is a brief overview of the main pros/cons.

### Pros

* Better handling of large volume of emails. Email sending task will be split into batches, and Drupal will process them in smaller chunks during cron runs. This is better because your server might time out or become unresponsive for visitors if you are trying to send 500 emails at once.
If the same task is split into multiple batches, it will be easier to process them, and regular visitors will not experience as big decrease in performance.

### Cons

* Requires more frequent cron (or a custom script that will process the batches), which translates into more used resources at all times. You might see certain decrease in performance if the site is processing email batches and there are a lot of users online simultaneously. This of course depends on many factors (number of emails you are sending, frequency of your cron, speed at which remote SMTP server processes the requests, number of visitors on your site, complexity, and so on).
See Elysia Cron module for fine tuning the cron implementations of all modules on your site. It will help you use less resources during each cron run, because you will be able to choose how often will cron of certain modules be run.
* In some cases this can result in slower email delivery. If you have a large number of emails to deliver (e.g. 100k newsletter subscription list), last user in the queue will receive the message significantly later than the first one. Also, all emails requested to be sent during that time, will be delayed as well.
> 7 votes

# Answer
The previous two answers discuss the pros/cons of queuing email when sending large batches. There are different pros/cons when non-batch emails are sent (e.g. triggered by a user registration event).

The questioner doesnt say which version of the SMTP module they're using, but the current 8.x-1.0-beta3 doesnt have the option to queue (sadly). Nevertheless, the pros and cons of queuing that seem evident to me are:

Pros: If the SMTP server cannot be reached, for any reason, and there's no queue, then the email simply doesnt get sent (and an error is returned). If there is a queue, then sending will be re-tried later, and, hopefully, the email will eventually get sent.

Cons: If there's a queue, the part of the application that wanted to send the email doesnt know when (or even if) the email actually got sent. When you have a queue, you also have to have something that monitors the queue and raises an alert if there's a problem.
> 3 votes

# Answer
We also did this to control the rate of email flow.

As well our SMTP server is a little slow, and errors sometimes for an unknown reason during the authentication phase, upon which we would need to retry until the email sent. By using the queue the user doesn't have to wait, instead we return a confirmation screen to them immediately, and then let the smtp queue and retry errors on queue take care of sending the email later.

Note you don't need to run the whole cron, you can just run the command **drush queue-run smtp\_send\_queue**, and it should send your emails.
> 1 votes

---
Tags: queue, emails
---


title: how to remove a node with a garbled url

text:
# Question
Title: how to remove a node with a garbled url
I have this stray node showing up in places (mainly menus) on my site - I don't know how it got created, but I would like to delete it and I can't find a way to delete it from the administration interface.

The url looks like this:

www.organization.com **/node/dc436a14-ff7d-4ff8-85f2-ee2b4f9e81ad**

and when you click it, it goes to the 404 page.

Anyone know a way to delete this node without having to go into the database?

Thanks!

# Answer
Ok, I found a way to do this.

Went into the specific menu as admin, and looked through the urls each of the menu items were pointing to (painful process when you have 60 some items). Found the menu item and deleted it from the menus interface and that worked.
> 2 votes

---
Tags: 8, nodes, uri
---


# Question
Title: Views exposed filter returns all results when using Autosubmit
This is slightly different than other people asking questions about an exposed filter returning results before they found the 'Input Required' option. Here is the scenario:

I have a series of 'county' nodes that are very simple - the title is the Zip Code, and there is an additional 'county' field that is the county. So for example the title is '78872' and the county field is 'Zavala'. I have then set up a View that allows a user to enter in a zip code in an exposed filter field and the corresponding county will be displayed. Since there is only one county that corresponds to a zip code, only 1 result should be returned (counties have multiple zip codes, but zip codes only correspond to 1 county).

The client wanted the form to autosubmit when the user input a zip code, so I have the following settings for the exposed form:

When the user first comes to the page, before they enter anything in the exposed form field, I also have it set to 'Input required' so nothing is displayed until the user enters in a zip code:

You can see it here https://texaslawhelp.org/legal-help/legal-help-finder

If there are no matches when you enter a zip code, it simply says 'no results found'. I did this by configuring the view under Advanced-\>No results behavior.

Here is the issue, once someone starts entering zip codes, if they then delete everything from the exposed filter form, it still shows a result. To duplicate this, enter in a zip code (78872) - Zavala is returned.

Then without refreshing the page, delete 78872 from the exposed filter and it returns 'El Paso'.

I believe this is because if nothing is entered in the exposed filter, it will match everything, and is just returning all results in a random order. Since the user has already input something, the 'Input Required' option no longer is in the mix. Only 1 result is displayed since I have the view set up to only display 1 result - there should only ever be 1 county returned when a zip code is entered. If I change the view to display 200 results (even though only 1 should ever match) I can see that if I enter something in the field, and then delete it, 200 results are found. So it seems pretty clear that it is a problem where every possible node is a match if nothing is entered in the field.

So, is there a workaround? Views and the exposed filter are actually working correctly as far as I can tell, so what is the trick for hiding any results if that exposed filter field is empty after the user has input something and then deleted it?

# Answer
> 0 votes
**1.** Maybe "El Paso" has a relation with a "Null Zip code"

**2.** You can go to "Configure Field -\> No results behavior and select "Hide if empty"

Maybe that can fix your problem

---
Tags: views
---


# Question
Title: How do I programmatically change the admin theme?
How do I define a different administration theme for a user and administration role in Drupal 8?

I have looked at the context module for Drupal 8. There is a problem with the context condition and the reaction theme related items are all based on the front-end themes. I need the same but for the back-end themes.

My code is the same as the context reaction code for Theme.php. I just changed the `submitConfiguration()`.

```
 /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $configuration['admin'] = $form_state->getValue('theme');
    $configuration += $this->getConfiguration();
      \Drupal::configFactory()
          ->getEditable('system.theme')
          ->set('admin', $form_state->getValue('theme'))
          ->save();
    $this->setConfiguration($configuration);
  }

```

I defined the following in the context configuration.

1. Condition =\> Role:User

Reaction =\> Admin Theme: Customtheme
2. Condition =\> Role: Administrator

Reaction =\> Admin Theme: Seven

Is this possible? Are there other methods for achieving this goal?

# Answer
> 3 votes
As the context module is still in alpha I would try a solution in custom code by extending the class AdminNegotiator:

*src/Theme/CustomAdminNegotiator.php*

```
<?php

namespace Drupal\mymodule\Theme;

use Drupal\user\Theme\AdminNegotiator;
use Drupal\Core\Routing\RouteMatchInterface;

class CustomAdminNegotiator extends AdminNegotiator {

  public function determineActiveTheme(RouteMatchInterface $route_match) {
    if (in_array('custom_role', $this->user->getRoles())) {
      return 'custom_admin_theme';
    }
  }

}

```

and register this service class in *mymodule.services.yml* tagged as theme negotiator with a priority higher than the default admin negotiator (-40):

```
services:
  theme.negotiator.admin_theme.custom:
    class: Drupal\mymodule\Theme\CustomAdminNegotiator
    arguments: ['@current_user', '@config.factory', '@entity.manager', '@router.admin_context']
    tags:
      - { name: theme_negotiator, priority: -39 }

```

The applies() method is kept the same as in AdminNegotiator, so that only users with the correct permission have access to this theme and this only applies for admin routes.

# Answer
> 4 votes
I came here just looking for a solution on how to programmatically set the admin theme (say during hook\_install or hook\_update).

This code will achieve that:

```
// Make sure the theme is installed
$theme_handler = \Drupal::service('theme_handler');
$theme_handler->install(['my_custom_admin_theme']);

// Set it as the admin theme
$config = \Drupal::service('config.factory')->getEditable('system.theme');
$config->set('admin', 'my_custom_admin_theme')->save();

```

---
Tags: 8, theme-negotiation
---


# Question
Title: How to prohibit access to a view if the user is not the user in the account path?
I created a page view to display forms created by the user on his account.

I added a "Submitted by" context filter to this view to filter the user ID of the logged in user.

My problem :

When I disconnect and reload the page, the view is still displayed. How to prevent access to this page if the user does not match the user of the account path ?

# Answer
The submitted by is not an access will not do it

I will post all the steps below since I am not sure what you have done (your view is translated in french)

Basically you will have a view of `webform submissions` with `relationship to the user` and `filter the current user`

### creating the view

### adding the user relationship

### adding the current user filter

### the finished view with important parts highlighted

the current logged in user should see ONLY their submissions NOW
> 0 votes

---
Tags: views, 8
---


# Question
Title: change the date format to dd/mm/yyyy in views of the webform
I have created the fields for the view extracte from a webform. It is working perfectly. But when i try to extract the date field it just get the date it yyyy/mm/dd format. Now I searched alot but no where i could find easy steps to convert the date format of this field to dd/mm/yyyy. Please explain in easy steps how to convert my field to my required date format.

# Answer
Visit **admin/settings/date-time/formats** in you instance & add a custom date format. See PHP manual for the options which you can.

Use your created date format to show the field value wherever you want like views.
> 1 votes

# Answer
I am writing this for future devs who stumble upon this. For me in the Webform Submission Data field, choosing "Number" and "Plain Text" resulted in dd/mm/yyyy format
> 0 votes

---
Tags: views
---


# Question
Title: How to modify Drupal 8 Views "Rewrite..." field values later in code?
In a Drupal 8.3 View, I am displaying fields. One of these fields is configured to *"rewrite results"* so as to *"output this field as a custom link"* with a custom link path.

I would like to modify these links in code (based on some later logic). However, I cannot find a place to actually modify this value in code. If someone knows how to accomplish this, please let me know. (This was much easier in D7.)

Here's what I've tried thus far.

* `theme_preprocess_views_view()`: I found `...['#view'] -> field['name'] -> options['alter']['path']` in Drupal 8's endless arrays, but changing this value did not affect the output. I could not find my custom link anywhere else in this endless array.
* `hook_views_post_render()`: This supposedly allows one to alter the output string, but doesn't actually give the output as a string (broken documentation).
* I can see the output string in a twig template, but cannot easily substitute my link given that PHP doesn't run in twig. This would be a less desirable option in any case.

# Answer
After more time and effort poking around, I found one possible solution, but perhaps not the best or most efficient.

**What didn't work:**

My original approach of changing the field path links in `theme_preprocess_views_view()` didn't work because this function is too late in the page build. ("Preprocess" is apparently contextual to the target function. In this case it comes before the final View, not the View's fields.)

I also tried using `template_preprocess_views_view()`, which was called before other View preprocess functions. While I was able to change the View rewrite values (e.g., `$view -> field['name'] -> options['alter']['path'] = 'my new path'`), this changed the links for all the fields, not allowing each field to be individually customized.

I was able to change the Views rewrite path value inside `hook_preprocess_views_view_field(&$variables)`, but this affected the *following* field in the results array, not the *current* field.

**My Solution:**

I ended up using `hook_preprocess_views_view_field(&$variables)`, and rendering my own custom links and saving them to `$variables['output']`.

`$variables['view']` and `$variables['row']` were available for finding data for the logic, as well as additional objects depending on what the View is displaying.

I also used `template_preprocess_views_view()` to re-organize all the Views rows before they were rendered in the twig template, but as mentioned before, I couldn't change the content of the rows inside this function because they were already rendered before this function was called.

I hope this saves time for someone. Feel free to post more eloquent solutions.
> 2 votes

# Answer
I'm late to the game but had similar questions. The drawback of using hook\_preprocess\_views\_view\_field(&$variables) is it operates on a field for every row. In order to have some logic based on row values you have to loop through all rows, like
`foreach ($variables['row'] as $idx) { // your logic here }`

Since in my logic I had to check for a node NOT having paragraphs and entity-\>hasField('fieldname') was unobtainable in hook\_preprocess\_views\_view\_field I reverted to hook\_views\_post\_execute($view) and did all of the rewrite logic there.

Eric
> 1 votes

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


title: Entity updates fails after migration D8

text:
# Question
Title: Entity updates fails after migration D8
So we have taken over a site and I migrated yamlforms to webforms with yamlform\_to\_webform module using drush. Now when I do a `drush updb` I get an error that says:

```
The SQL storage cannot change the schema for an existing field (field_getintouch in block_content entity) with data.
The following updates are pending:

webform module :
  8007 -   Issue #2840521: Add support for global CSS and JS.
  ... Many updates
  8088 ...

Do you wish to run all pending updates? (y/n): y
The following module is missing from the file system: yamlform_to_webform bootstrap.inc:250                                                                                [warning]
Performing webform_update_8007                                                                                [ok]
# THIS IS WHERE IT ALWAYS BREAKS
The SQL storage cannot change the schema for an existing field (field_getintouch in block_content entity) with data.                                                                           [error]
Performing webform_update_8026                                                                                [ok]
Failed: The SQL storage cannot change the schema for an existing field (field_getintouch in block_content entity) with data.

```

So went ahead and tried `drush entity-updates` and got this instead.

```
vagrant@somesite:/srv/www/somesite/web$ drush entity-updates
The following updates are pending:

block_content entity type :
  The block_content.field_getintouch field needs to be updated.
field_collection_item entity type :
  The field_collection_item.field_block_background_color field needs to be updated.
node entity type :
  The node.field_form field needs to be updated.
  The node.field_register_form field needs to be updated.
  The node.webform field needs to be updated.
paragraph entity type :
  The Published field needs to be updated.
  The paragraph.field_block_background_color field needs to be updated.
webform_submission entity type :
  The Webform submission entity type needs to be updated.
Do you wish to run all pending updates? (y/n): y
Drupal\Core\Entity\EntityStorageException: Exception thrown while performing a schema update. SQLSTATE[42S22]: Column not found: 1054 Unknown column 'field_getintouch_open' in 'where clause':[error]
SELECT 1 AS expression
FROM
{block_content_revision__field_getintouch} t
WHERE (field_getintouch_target_id IS NOT NULL) OR (field_getintouch_default_data IS NOT NULL) OR (field_getintouch_status IS NOT NULL) OR (field_getintouch_open IS NOT NULL) OR
(field_getintouch_close IS NOT NULL)
LIMIT 1 OFFSET 0; Array
(
)
 in Drupal\Core\Entity\Sql\SqlContentEntityStorage->wrapSchemaException() (line 1513 of     /srv/www/somesite/web/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).
Failed: Drupal\Core\Entity\EntityStorageException: !message in Drupal\Core\Entity\Sql\SqlContentEntityStorage->wrapSchemaException() (line 1513 of                                          [error]
/srv/www/somesite/web/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).
Cache rebuild complete.                                                                                [ok]
Finished performing updates.

```

Ofcourse I have googled and looked for solutions but getting nowhere. Many have suggested `composer update drupal/webform --with-dependencies` I've tried that, did not help.

My next idea was to update the tables manually OR delete the data in those fields so it can be updated. But the error message isn't enough verbose for me to know where to search for the correct tables.
I'm on a local machine and I have backed up everything so I can play around and destroy everthing over and over again until I find a rock solid solution.

Any help would be highly appreciated. Let me know if you need additional info, I'll try to post that as soon as possible.

Im currently running `8.4`

# Answer
Have succesfully updated entities now by truncating the affected tables, run entity updates and manually imported all forms. I could list all the nodes with forms from the backed up db. Still having issues with reCaptcha though!
> 0 votes

# Answer
You might need to incrementally do the updates. For example, you would do the initial migration in Drupal 8.2 with last year's first release of the Webform module and then incrementally apply the Webform 8.x-5.x releases.
> 0 votes

---
Tags: entities, webforms, drush, updating
---


# Question
Title: Enabling AJAX in Views breaks Form API AJAX button (Drupal 8)
On a product node there is form with a button "add to cart" that is implemented with form API (ajax):

```
$form['add_to_cart'] = array(
  '#type' => 'button',
  '#value' => $this->t('Add to cart'),
  '#ajax' => array(
    'callback' => 'Drupal\custom_cart\Form\AddToCartForm::addProductToCart',
    'event' => 'click',
    'effect' => 'fade',
    'wrapper' => '#custom-cart',
    'progress' => array(
      'type' => 'throbber',
    ),
  )
);

...

public function addProductToCart(array &$form, FormStateInterface $form_state) {
if ($parent_node_id = $form_state->getStorage()['parent_node_id']) {
  if ($product_node = Node::load($parent_node_id)) {
    $pid = $product_node->get('field_product_bid')->value;
    $price = $product_node->get('field_product_price')->value;
    $renderer = \Drupal::service('renderer');
    $response = new AjaxResponse();
    Cart::addLineItem($pid, $form_state->getValue('amount'), $price);
    $cart = Cart::getThemedCart();
    $elem = ['#markup' =>  $cart];
    $response->addCommand(new ReplaceCommand('.cart-nav', $renderer->render($elem)));
    return $response;
  }
 }
}

```

This works as expected.

For a product overview page we render out product nodes with a view (node teasers) and the view includes some exposed filters. If the view is ajax enabled the ajax callback from the "add to cart" button (breaks) and returns a 404 error:

Request URL:http://foobar.lo/views/ajax?\_wrapper\_format=drupal\_ajax Request Method:POST Status Code:404 Not Found

Does somebody know how to fix this (core patches anywhere?) or a workaround you know?

Thanks for any advice

# Answer
> 4 votes
The issue is in this line of RenderElement::preRenderAjaxForm:

```
$settings['url'] = Url::fromRoute('<current>');

```

When the form with the button "add to cart" is rendered inside of an ajax request of a view, then the url is set to the wrong endpoint `/views/ajax`.

A workaround would be to add a static url in the ajax setting of the form element, so that it won't be set dynamically:

```
use Drupal\Core\Form\FormBuilderInterface;

  '#ajax' => [
    'callback' => '::add',
    'wrapper' => $wrapper,
    'url' => Url::fromRoute('<front>'),   // set this to the route of the view page
    'options' => ['query' => \Drupal::request()->query->all() + [FormBuilderInterface::AJAX_FORM_REQUEST => TRUE]],
  ]

```

If you use the form in multiple pages you would need to adjust the code to only set the url when the form is rendered in this view.

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


title: Rule + redirect

text:
# Question
Title: Rule + redirect
I want all my anonymous users to be redirected to a specific page. I created a rule for this : https://imgur.com/mUl8H9Q

It works, all anonymous are redirected to the page "espace press" and they can log in/create account.

But now, I want to allow my anonymous to view a specific content type (called CP) + the front page. Then they would be redirected if they try to view any page except the front page or a CP page.

What do I need to change in my rule to make it happen in drupal 7?

The code for my rule :

```
{ "rules_login" : {
"LABEL" : "login",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "login" ],
"REQUIRES" : [ "rules" ],
"ON" : { "init" : [] },
"IF" : [
  { "user_has_role" : {
      "account" : [ "site:current-user" ],
      "roles" : { "value" : { "1" : "1" } }
    }
  },
  { "NOT text_matches" : { "text" : [ "site:current-page:url" ], "match" : "espace-presse" } },
  { "NOT text_matches" : { "text" : [ "site:current-page:url" ], "match" : "user\/login" } },
  { "NOT text_matches" : { "text" : [ "site:current-page:url" ], "match" : "user\/register" } },
  { "NOT text_matches" : { "text" : [ "site:current-page:url" ], "match" : "user\/password" } },
  { "NOT text_matches" : { "text" : [ "site:current-page:url" ], "match" : "user" } }
],
"DO" : [ { "redirect" : { "url" : "espace-presse" } } ]

```

} }

# Answer
> 0 votes
Solution is very simple With pathauto, I created a specific pattern for my content type and I added a text comparison in rules which contains the begining of the pattern.

---
Tags: rules, redirection
---


title: Twig Math Operators

text:
# Question
Title: Twig Math Operators
So, I'm trying Twig for the first time with a Drupal 8 Theme. According to the Twig docs I can use the / operator. Why does

```
{% set contentMinutes = item.content/60 %}

```

result in a wsod with an error 'Unsupported operand types in \__TwigTemplate' ?

# Answer
> 1 votes
Because `item.content` is a render array. You might find the number you are looking for inside of the render array, for example in `item.content['#markup']`, but this depends on how you set up the field to be formatted in the content type. For example if you format it with a prefix the math won't work. So better use database values for math operations, like for example `node.field_number.value`.

---
Tags: theming
---


title: Dynamic fileds on a drupal node

text:
# Question
Title: Dynamic fileds on a drupal node
I have a **job** and **application** node types and I'd like to add a field on Job so the recruiter can set dynamic (different between jobs) questions that a user should answer when filling in an application. How can I display the custom questions on the application form and collect the answers?

# Answer
> 0 votes
Try to use paragraphs module it allows to create as much fields as you want

---
Tags: nodes, entities
---


# Question
Title: How do I properly install the MailChimp module?
In order to install MailChimp in Drupal 8 I followed the instructions for the MailChimp Drupal module.

> **Instructions for 8.x-1.x**
>
> The 8.x-1.x release uses version 3.0 of the MailChimp API and bundles the library with the module. This is a temporary solution until the process for installing libraries via composer is finalized in Drupal 8.

1. in `admin/modules/install` I added mailchimp 8.x-1.3
2. Checked that libraries is installed (`Machine name: libraries; Version: 8.x-3.x-dev`)
3. Enabled all four modules (mailchimp, mailchimp\_campaign, mailchimp\_lists, mailchimp\_signup)

However, when trying to **configure the module at `admin/config/services/mailchimp` the page could not be found**.

How can I resolve this issue and where should I start looking?

* PHP 7.1.6-nmm1
* Drupal 8.4.0-dev

# Answer
> 0 votes
You should use Composer to fetch this module, as it has an external dependency noted in its `composer.json` file:

http://cgit.drupalcode.org/mailchimp/tree/composer.json

It seems to include an older version with the module, I'm not sure why, but the current version of Mailchimp API by Thinkshout looks to be 1.0.8. I don't see any installation notes. The module comes with 1.0.6... ?

Other than that, clear your caches and try to access the page again.

---
Tags: 8, installation, plugins, emails
---


# Question
Title: What hook can alter fully rendered html?
I'm rendering some JSON using Views and Views Datasource and due to a bug in Views Datasource, I can't seem to get the output rendered properly. So, I'm looking for a workaround.

What hook can I implement in my theme or module that will give me the final string that is about to sent back to the browser that will give me one last chance to alter it?

EDIT: I was in a hurry and worded that poorly. When I say the page won't render properly, I mean that the bug in Views Datasource doesn't use the proper data formatters for the data fields. I'm getting JSON back just fine, but some of the values within the JSON are not properly processed by the relevant module formatters. In this example, the Video field can contain a Video URL and a Thumbnail Image URL. The view is configured to display a Thumbnail Image URL, but due to the bug in Views Datasource, it is displaying the Video URL instead.

I can't just change the render array, because Views Datasource is not generating its output using a render array.

# Answer
I **highly** recommend you not to alter the page output when you clearly know where the bug is. See Bala's answer. Or may be you want to let us know what is the exact problem ?

To answer your question, to alter the content that is going to be *rendered*, use hook\_page\_alter
> 1 votes

# Answer
Try hook\_page\_alter, it lets you alter the final page render array

You may also be interested in

drupal\_json\_encode
> 1 votes

# Answer
I am also having this issue when using View Datasource module but i solved it by changing the views-views-xml-style-raw.tpl.php file

located under "sites\all\modules\views\_datasource-6.x-1.0-beta2\views\_datasource\theme\\"

Replace drupal\_set\_header("Content-Type: $content\_type; charset=utf-8"); with

```
drupal_set_header('Content-Type: text/xml;');

```

I hope it will works for you too.
> 0 votes

# Answer
For Drupal 7:

`// Implement HOOK_page_alter.
function MY_MODULE_page_alter(&$page) {
 // Add our processing to the #post_render functions.
 $page['#post_render'][] = 'MY_MODULE_page_post_render';
}`

`function MY_MODULE_page_post_render($html) {
 // Do something to the HTML for the page.
 $html = str_replace('apples', 'oranges', $html);
 return $html;
}`
> 0 votes

---
Tags: 7, views, hooks
---


# Question
Title: Is it possible to programmaticaly change the HTML rendered by Drupal 7?
Imagine that we have a project completely finished, with lots of modules, themes, etc. Is it possible at all to have a module, which will be called at the last stage, and change the HTML output. For example, we want to make a ereg\_replace of a img tag, and we don't want to deep into the modules. Is there a simple hook which can accomplish this extremely simple task ?

# Answer
> 1 votes
If you want to alter the rendered content of a page, you start by adding a `post_render` function to the node:

```
/**
 * Implements hook_node_view_alter().
 */
function MODULE_node_view_alter(&$build) {
  $build['#post_render'][] = 'MODULE_wrap_images';
}

```

And then in that post render function, you can do what you need to do. In the example below, I am replacing `float:left` and `float:right` with a wrapper div:

```
function MODULE_wrap_images($content) {
  // Find all links within the content and extract the complete <img> tag.
  if (preg_match_all('#<img.*?/>#i', $content, $matches)) {

    // Loop matches and process.
    foreach ($matches[0] as $index => $match) {

      // Align images left.
      if (stripos($match, 'float: left;')) {
        $new = '<div class="content-img content-img-left">' . str_ireplace('float: left;', '', $match) . '</div>';
        $content = str_ireplace($match, $new, $content);
      }

      // Align images right.
      if (stripos($match, 'float: right;')) {
        $new = '<div class="content-img content-img-right">' . str_ireplace('float: right;', '', $match) . '</div>';
        $content = str_ireplace($match, $new, $content);
      }
    }
  }

  return $content;
}

```

# Answer
> 0 votes
Same approach for altering the HTML for the entire page:

For Drupal 7:

`// Implement HOOK_page_alter.
function MY_MODULE_page_alter(&$page) {
 // Add our processing to the #post_render functions.
 $page['#post_render'][] = 'MY_MODULE_page_post_render';
}`

`function MY_MODULE_page_post_render($html) {
 // Do something to the HTML for the page.
 $html = str_replace('apples', 'oranges', $html);
 return $html;
}`

---
Tags: 7, theming
---


# Question
Title: How to write PHPUnit test for any function that has external dependencies?
I have 1 function that returns value of any field of particular content type. For this I need to load my current user and a node from where I will retrieve value.

But loading user calls User class and when I run the test, it says undefined method - user\_load.

My function is:

```
public static function get_ctype_field_value($field) {

    $user = user_load(\Drupal::currentUser()->id());
    $ulm = get_type_id($user); // another function in some class, return value 445
    $local_market = \Drupal\node\Entity\Node::load($ulm);
    $llf = '';
    if ($local_market) {
      // Get the field value from the LM.
      if ($local_market->hasField($field)) {
        $localmarket_field = $local_market->$field->value;
      }
    }
    return $localmarket_field;
  }

```

AND my test function is:

```
class MyControllerTest extends UnitTestCase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = ['node'];

  /**
   * Users to use during this test.
   *
   * @var array
   */
  protected $users = [];

  /**
   * Nodes to use during this test.
   *
   * @var array
   */
  protected $nodes = [];

  protected function setUp() {
    parent::setUp();
    $container = new ContainerBuilder();
    $methods = get_class_methods('\Drupal\Core\Entity\EntityManager');

    $entityManager = $this->getMockBuilder('\Drupal\Core\Entity\EntityManager')
  ->disableOriginalConstructor()
  ->getMock();

  }

  public function test_get_ctype_field_value() {
    $originalString = 'field_vat';
    $expectedResult = '10.00';
    $econtroller = new myController(); //controller where function resides
    $this->account->expects($this->once())
      ->method('user_load');
    $this->users[] = $this->account->load(1);
    $result = $econtroller->get_ctype_field_value($originalString);
    $this->assertEquals($expectedResult, $result);
  }
}

```

Please suggest any way to write PHPUnit test for this function.

The error I'm getting is:

> Error: Call to a member function load() on null

# Answer
> 2 votes
The code is dependent on Drupal's service container existing, and thus a container needs to be instantiated and used. This is possible in PHPUnit tests using the `\Drupal::setContainer()` method, and creating a container object.

```
use Drupal\Core\DependencyInjection\ContainerBuilder;

protected function setUp() {
  parent::setUp();

  $this->account = $this
    ->getMockBuilder('Drupal\user\Entity\User')
    ->disableOriginalConstructor()
    ->getMock();

  // Create a new container object.
  $container = new ContainerBuilder();

  // Add a service into it.
  $container->set('current_user', $this->account);

  // Let Drupal use your mock container.
  \Drupal::setContainer($container);
}

```

---
Tags: 8, testing
---


# Question
Title: Attach a jQuery function to an AJAX response
I'm trying to attach a jQuery function to an AJAX response. The JavaScript file content is the following.

```
(function($) {
   $(document).ready(function(){
      $('.rembourcement').find( ".button" ).click(function() {
         var nb=$(this).data('ligne');
         //
         if($('.bloks_sous_lignehold'+nb).is(':visible')){
            $( this).removeClass('button_active');
            $(this).closest('.ligne').removeClass('bg-washed-green2 shadow-1');
         }else{
            $( this ).addClass('button_active');
            $(this).closest('.ligne').addClass('bg-washed-green2 shadow-1');
         }
         $( ".bloks_sous_lignehold"+nb ).slideToggle( "slow" );
     });
}(jQuery));

```

In the AJAX callback, I used the following code, without success.

```
$renderer = \Drupal::service('renderer');
$response = new AjaxResponse();
$elem = [
   '#type' => 'container',
   '#attributes' => ['id' => 'table-wrapper'],
   '#theme' => 'Mcfiltered',
   '#mc_build_data' => $mc_build_data
];
$response->addCommand(new ReplaceCommand('#table-wrapper', $renderer->render($elem)));
$response->addCommand(new InvokeCommand('.rembourcement .button', 'click'));
return $response;

```

This doesn't seem to work. Do you have any idea?

# Answer
> 0 votes
In Drupal 7, I have functions like the below in my JS file.

```
$(document).bind('myFunction', function() {
     //
});

```

In my module, I then have the below.

```
$commands[] = ajax_command_invoke('html', 'trigger', array('myFunction'));

```

Maybe Drupal 8 would be similar.

**Edit:** If you're here looking to run a jQuery function after Ajax, like the title asks, ignore the downvote. Drupal Behaviours may be what you're looking for, but if it's just Dom manipulation, it isn't.

# Answer
> 0 votes
Thank you @Niall, but i used drupal 8's behaviors which is a cool approach to solve this issue. i tweaked my Js to the following:

```
(function($, Drupal)
{
// I want some code to run on page load, so I use Drupal.behaviors
Drupal.behaviors.smenoModule = {
    attach:function(context, settings){

        // Ensure that this behavior is only attached once to the window.
        $($('.rembourcement').find( ".button" ), context).once().click(function () { //$(context).find('[data-mybehavior]')
            var nb=$(this).data('ligne');
            //
            if($('.bloks_sous_lignehold'+nb).is(':visible')){
                $( this).removeClass('button_active');
                $(this).closest('.ligne').removeClass('bg-washed-green2 shadow-1');
            }
            else{
                $( this ).addClass('button_active');
                $(this).closest('.ligne').addClass('bg-washed-green2 shadow-1');
            }
            $( ".bloks_sous_lignehold"+nb ).slideToggle( "slow" );
        });
    }
};
}(jQuery, Drupal));

```

what the above code does is the same as jQuery's ready function, the content is executed on the page load but also:

> After the AJAX Form API has submitted a form.
>
> When an AJAX request returns a command that modifies the HTML, such as ajax\_command\_replace().

and to ensure that the functions are called only once we use once().

check out this good article

PS: I no longer needed this lign, so i removed it:

> $response-\>addCommand(new InvokeCommand('.rembourcement .button', 'click'));

---
Tags: javascript, ajax
---