# Question
Title: How are routes refresh/rebuild after they are programmaticaly created?
I installed the External Entities module, which allows to create an entity and generate its route automatically. I checked what the module does and found the following.

* KernelDesctructionSubscriber.php line 48 --\> `public function onKernelTerminate(PostResponseEvent $event)`
* ContainerAwareEventDispacther.php line 111 --\> `$definition['callable']($event, $event_name, $this);`
* HttpKernel.php Line 84 --\> `$this->dispatcher->dispatch(KernelEvents::TERMINATE, new PostResponseEvent($this, $request, $response));`
* StackedHttpKernel.Php Line 32 --\> `$kernel->terminate($request, $response);`
* Drupal Kernel Line 634 --\> `$this->getHttpKernel()->terminate($request, $response);`
* index.php Line 22 --\> `$kernel->terminate($request, $response);`

`KernelDestructionSubscriber::onKernelTerminate` contains the following code.

```
foreach ($this->services as $id) {
  // Check if the service was initialized during this request, destruction
  // is not necessary if the service was not used.
  if ($this->container->initialized($id)) {
    $service = $this->container->get($id);
    $service->destruct();
  }
}

```

when the ID is equal to *drupal.proxy\_original\_service.router.builder*, it executes `Container::initialized()`.

```
if (isset($this->aliases[$id])) {
  $id = $this->aliases[$id];
}

return isset($this->services[$id]) || array_key_exists($id, $this->services);

```

it will return `TRUE` because `$this->services[$id]` is set, call `$service->destruct()` in `onKernelTerminate()`, and rebuild the route.

Where does the *External Entities* set `$this->services[$id]` and rebuild the routes?

# Answer
> 1 votes
I can't see anything in the module doing it, but this is done through the router.builder service.

Either rebuild immediately, with `\Drupal::service('router.builder')->rebuild();` or tell it to rebuild at the end of the request, which is `\Drupal::service('router.builder')->setRebuildNeeded()`

Based on what you posted, it looks to me that you went through all the boring, generic stuff and stopped right before if would have gotten interesting, in the `rebuildIfNeeded()` method of that service. It checks the `rebuildNeeded` flag and rebuilds the routes when necessary.

So, you don't have to do anything to have that method called, that happens automatically if the service got invoked, you just have to make sure that flag is set.

---
Tags: 8, entities, routes
---


# Question
Title: Simple test always failing for custom module
I am trying to implement simple test for my custom module. But the test case always failing for user login. In the test script what I am trying to test is whether admin page is loading properly without any errors.

I am following similar code from core modules and other contributed modules. But couldn't figureout what I am missig in mine. My test script is given below:

```
<?php

/**
 * @file
 * Test file for custom_module module.
 */

/**
 * Default test case for the custom_module module.
 *
 * @ingroup custom_module
 */
class MyCustomModule extends DrupalWebTestCase {

  /**
   * {@inheritdoc}
   */
  public static function getInfo() {
    return array(
      'name' => 'My Custom Module Test Case',
      'description' => 'Functional test for My Custom Module Module',
      'group' => 'My Custom Module',
    );
  }

  /**
   * {@inheritdoc}
   */
  function setUp() {
    parent::setUp('custom_module');

    $permissions = array(
      'access administration pages',
      'administer custom module',
    );
    $this->admin_user = $this->drupalCreateUser($permissions);
    $this->drupalLogin($this->admin_user);
  }

  /**
   * Test site working properly after installs the module.
   */
  function testCustomModulePageLoads() {
    $paths = array(
      '/admin/config/custom_module/manage',
    );
    foreach($paths as $path) {
      $this->drupalGet($path);
      $this->assertResponse(200, '200 response for the path ' . $path);
    }
  }

}

```

Result:

# Answer
Try calling $this-\>setUp(); from the testCustomPageLoads() function.
> 0 votes

# Answer
With the info given here, it's essentially impossible to say what's wrong.

The code you have provided and test results doesn't match. It says user creation happens on line 36 and user login happens on line 43/44 but this not what the code says.

Also it's worth noting that you are getting 500 response (internal server error) and invalid HTML meaning something fundamentally is failing in your tests. It's not possible to say what it causing this, could be any kind of coding error on your part.

If the module works in non test scenario, most likely you have unmet dependencies, like some module/theme not being enabled which is causing errors and trouble.

Looking at the debug messages and `DrupalWebTestCase::parse` would be a good place to start debugging.
> 0 votes

---
Tags: 7, testing
---


# Question
Title: Access callback infinite loop in specific case
I need to **limit node creation** to one item for a specific content\_type (photography contest), and to **redirect the user to its photography** if he already posted one. The snippet below is almost working as expected.

```
function mymodule_menu_alter(&$items) {
  $items['node/add/slide']['access callback'] = '_mymodule_limit_slide';
}

function _mymodule_limit_slide () {
  global $user;
  if(user_access("create slide content")) {
    $allowed_limit = variable_get('allowed_limit', 1);
    $slides = db_query("SELECT nid, count(*) ct FROM {node} WHERE type = :type AND uid = :uid", array(':type' => 'slide' ,':uid' => $user->uid))->fetchAssoc();
    if ($slides['ct'] < $allowed_limit || in_array('administrator', $user->roles)) {
      return TRUE;
    }
    else {
      drupal_set_message('You cannot post more than one photography. But you can edit the one you posted below if yo wish to.');
      drupal_goto(drupal_get_path_alias('node/'.$slides['nid']));
    }
  }
  return FALSE;
}

```

If I `dpm(slides)`, it returns the correct array and data.

But, as far as I could debug, if I try to connect a user who :

* already posted at least one node of other content type
* whether he posted or not a slide

Drupal tries to go to `node/'.$slides['nid']` and that creates an infinite loop.

**Summary :** I don't understand why my function `_mymodule_limit_slide ()` would be called out of `node/add/slide` url, or what else is wrong ?

# Answer
I think if you add the access login in the form\_alter, the user should be redirected properly. IOW something like this:

```
function yourmodule_form_alter(&$form, $form_state, $form_id) {  if($form_id == 'CONTENT-TYPE_node_form') {  global $user;
  if(user_access("create slide content")) {
    $allowed_limit = variable_get('allowed_limit', 1);
    $slides = db_query("SELECT nid, count(*) ct FROM {node} WHERE type = :type AND uid = :uid", array(':type' => 'slide' ,':uid' => $user->uid))->fetchAssoc();
    if ($slides['ct'] < $allowed_limit || in_array('administrator', $user->roles)) {
      return TRUE;
    }
    else {
      drupal_set_message('You cannot post more than one photography. But you can edit the one you posted below if yo wish to.');
      drupal_goto(drupal_get_path_alias('node/'.$slides['nid']));
    }
  }
}

```
> 0 votes

# Answer
I got it working that way :

```
function mymodule_node_prepare($node) {
  if ( empty($node->nid) && $node->type == 'slide' && !in_array('administrator', $user->roles)) {
    global $user;
    $slides = db_query("SELECT nid, count(*) ct FROM {node} WHERE type = :type AND uid = :uid", array(':type' => 'slide' ,':uid' => $user->uid))->fetchAssoc();
    $allowed_limit = variable_get('allowed_limit', 1);

    if ($slides['ct'] >= $allowed_limit  ) {
      drupal_set_message('You cannot post more than one photography. But you can edit the one you posted below if yo wish to.');
      drupal_goto('node/'.$slides['nid']);
    }
  }
}

```

Sounds more elegant than `menu_alter()`, but I couldn't figure out what was wrong in question logic.
> 0 votes

---
Tags: 7, nodes, redirection
---


# Question
Title: Drupal 8: Webform - how to programmatically prevent or call a form submission?
I build a form with the webform module and hooked it to be able to submit it via AJAX:

```
function mytheme_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
  if ( isset($form['#webform_id']) && $form['#webform_id'] == 'myform' )
  {
    // add an AJAX callback to the form submission
    $form['actions']['submit']['#ajax'] = array(
      'callback' => '\Drupal\mymodule\Controller\DefaultController::submitMyForm',
      'event' => 'click',
    );
  }
}

```

Now i'd like to prevent the form submission in the submitMyForm-function when a certain condition takes place. How can I achieve that?

And how can I submit it when the condition doesn't take place?

---

EDIT

This worked:

```
function submitMyForm(&$form, FormStateInterface $form_state, $form_id)
{
   if ( $condition ) {
      $form_state->setErrorByName('field_name', t('error message'));
   }
}

```

# Answer
Sitepoint has a nice example of Ajax form validation in Drupal 8:

https://www.sitepoint.com/using-ajax-forms-drupal-8/
> 2 votes

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


title: Are .module files still required?

text:
# Question
Title: Are .module files still required?
I noticed that, in the current page crumb module, there is no .module file.

Why is that no longer necessary? As a test I added a .module file, but it seems it is not being read. Where can I find documentation about using or not using a .module file in Drupal 8?

# Answer
`.module` files are not required if you are not adding any procedural code. If you need to use any hooks, like `hook_theme` or `hook_form_alter`, yes, you need to do that in the `.module` file, because it cannot be done anywhere else. A lot of modules that extend base classes or provide services don't have any need to also include a `.module` file unless they provide something via `hook_help`, for example.

Some developers provide empty `.module` files, like:

```
<?php

// empty

```

I simply omit them if they have no code.

> And as a test I added a .module file but it seems it is not being read.

You'd have to elaborate on this, because any module that is enabled that has a `.module` file is definitely read. You may have to clear cache to pick up on changes.
> 8 votes

---
Tags: 8
---


# Question
Title: views and contextual filters with entity reference field
how do you use contextual filters to a views block when you want to use a reference field from the content type displaying the view?

here's the simple scenario

1. artist content type has some basic fields
2. song content type has a reference field referencing which artist
3. event content type has a reference field referencing which artist is headlining
4. view has a block with fields

on each Artist content page, it's working and i have a block of songs for that artist in the sidebar. i used views provide default entity and basic validation (but does not work for below)

on each Event content page, i want a block of songs for that artist in the sidebar. Essentially i want the reference field in the event to match up with the artist's songs.

since we don't have access to the path, i've been playing around with contextual filters on the reference field (and reverse of it) to no avail.

---

Ok thanks to @Jimajamma I seem to have figured it out, it's actually quite simple.

In order to get the argument into the Song view, you add a 'contextual filter' and select the Song's artist reference field. Then under 'When the filter value is NOT available' choose 'provide default value' and PHP Code. In that PHP code you want to return the value of the Event's artist reference field like so

```
$node=menu_get_object();
return $node->field_event_artistref['und'][0]['target_id'];

```

then under 'When the filter value IS available or a default is provided', choose 'Specify validation criteria' and basic validation

In a nutshell, this is simply taking the argument of the artist the Song references and comparing it to the default value you provided which is the current node's artist reference field. also as @Jimajamma said, best practice would be to use a switch statement on the node-\>type to be able to use the songs by %artist block on several different types of content like artist nodes.

# Answer
> 6 votes
In the contextual filter, you can use php to supply the argument. There, you could put in something like:

```
$node=menu_get_object();
return $node->field_headliner[0]['nid'];

```

where `field_headliner` is the node reference field of your event content type. The exact syntax above is D6, but I am pretty sure it's the same or at least very similar in D7.

Then, just as long as this view block is being show in/on an event page, the above will return the nid of the headlining band, and if your view is set up to filter on that node nid, you should be set.

You could even get fancy up in there with something like:

```
$node=menu_get_object();

switch ($node->type) {
  case 'band':
    return $node->nid;
  case 'event':
    return $node->field_headliner[0]['nid'];
  default:
    return 0; // or however you want to return an error
}

```

and then the same view block display could be used on both types of page. Then just put this block on band and event pages and you should be all set.

# Answer
> 0 votes
You could use this snippet to get the target\_id of your field entity reference. It's permits multipes target\_id.

```
$ Node = menu_get_object () // we get the current node
switch ($ node->type) {     // We can manage multiple scenarios with the content type
  case 'type A':            // For the content type A
    $ Related_ids = array ();
    $ Related = field_get_items ('node', $node, 'field_event_artistref') // Get the entity reference field
    if ($related && is_array ($related) && sizeof ($related)> 0) {
      for ($i = 0; $i <count ($related); $i++) {
        $ Related_ids [] = $related [$i]['target_id'];
      }
    }
    return implode ('+', $related_ids) / / It returns the values of the field entity reference

  default:
    return 0 / / default it returns 0
}

```

http://drupal.org/node/1714188

# Answer
> 0 votes
I've created a new sandbox module to solve this exact problem:

https://drupal.org/sandbox/nickurbits/2070451

Allows you to change a contextual filter's default value using a field from the current entity.

# Answer
> 0 votes
You *can* do this without code. Here's how:

1. Create a block view which lists fields and do a content type filter on "Event"
2. Add an entity reference to the artist
3. Add a contextual filter of NID and use the entity reference of the artist as the relationship
4. Add another entity reference of content that *is referencing* the song content and use the the artist entity reference as the relationship.
5. Add a field for the song name (perhaps it's title?) and use the song relationship.

That should do it. Basically you're starting with the Event and building relationships to Artist and then to Song.

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


title: index.php file for custom module

text:
# Question
Title: index.php file for custom module
i have custom software and wanna write an api for drupal (custom software -\> drupal). The thing is the custom software will call api calls to index.php (you cant change that). So how can i write something like an index.php for my module, like (http://drupal.install/myhookmenulink/index.php) so the software can reach that link and send infos to my module. anyone know ?

greetings

# Answer
> 3 votes
Drupal allows calls to .php files out of the box. Take a look at the .htaccess file and you will see that .php files will be handled just like any php application.

So... just create your .php file and make sure you are including it at the appropriate path.

That all said, in D8 (or in D7 + elbow grease) you get some pretty powerful autoloader capabilities out of the box so ideally you could take advantage of that in your module.

---
Tags: navigation
---


# Question
Title: How to make Forena render my SVG Graph properly?
I am trying to create a bar graph using Forena's SVG Graph facilities. But it shows output like this:

As shown in the above image, **it is not rendering the SVG Graph properly**.

I am using this SQL statement (my "*data block*" related to the SVG Graph I try to create):

```
SELECT Type,count(*) as Number
FROM node
GROUP by type

```

Following is a screenprint of the related FRX file:

And here is a textual version of that FRX file:

```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE root [
<!ENTITY nbsp " ">
]>
<html xmlns:frx="urn:FrxReports">
<head>
<title>Graph Demo</title>
<frx:category>Sample Graph</frx:category>
<frx:options/>
<frx:parameters>
</frx:parameters>
<frx:docgen>
</frx:docgen>
<frx:fields>
</frx:fields>
<frx:menu/>
<frx:cache/>
<style/>
</head>
<body>
<div id="nodeGraph" class="FrxSVGGraph" frx:block="reports/nodeGraph">
  <svg frx:group="{Type}" frx:key="{Type}" frx:series_1="{Number}" frx:renderer="FrxSVGGraph" frx:type="BarGraph"/>
    <table>
      <thead>
        <tr>
          <th>Type</th>
          <th>Number</th></tr></thead>
      <tbody>
        <tr frx:foreach="*">
          <td>{Type}</td>
          <td>{Number}</td></tr></tbody></table></div></body>
</html>

```

**My question**: How to make Forena render my SVG Graph properly?

# Answer
The issue you described in your custom graph, is pretty sure similar to what is also happening when viewing the delivered graphs. So make sure that the delivered graphs work before moving on to custom graphs, such as the SVG Graph Demo, which is one of the delivered SQLite sample reports and graphs. Visit relative path `/reports/sample.svg_demo` in your own site. If you don't get the very same graphs in your own site, then use this checklist to get that issue resolved:

* After you installed/enabled Forena, complete the required setup to Enable SVGGraph library (`reports/help.setup#svggraph` in your own site is where you can find the same). Pay special attention to this part documented around there:

> If you don't see a nicely formatted graph, but only some square with a gray background (about the size of the SVG graph you should see if it would have worked), or you're getting some error messages, you may want to checkout the issue queue on Drupal.org (search for html filter) ...

Obviously, if you change "gray" to "white", your first screenprint is pretty similar to "*... some square with a gray background ...*" (more details on that "*html filter*" in the next bullet).
* Quite often the reason why Forena doesn't seem to render SVG Graphs correctly, is because the input format used by Forena is simply stripping out the SVG tags. To remedy this, this is what's needed:

> go to `admin/config/content/forena` in your site and ensure that the **Text Format** specified **does NOT strip out SVG tags**.

Additional info: have a look at "*Prepare a text format to be used by forena*" within the Installation and Configuration section of the Setup guide. At the very end of it there is this note:

> Especially if you're planning to use SVG graphs it is important to avoid that tags are being stripped out, as this could cause such graphs to not be shown at all or with errors.
> 1 votes

---
Tags: forena
---


# Question
Title: How to add month and year dropdown to calendar month view
I want to add a month and a year dropdown to the month view of calendar so a user can jump to any month from the dropdown and can jump to the year, if selected. (Users can pick month OR year and will get results). I can add an exposed filter that doesn't update the calendar display when I click apply.

Any suggestions of what terms to search for or how to start this. I cannot seem to find tutorials or posts on this other than people saying yeah, I want that but I have no idea how to do it without building a custom calendar or using jquery datepicker.

# Answer
The Date module has a subproject called **Date Views**. Once that module is enabled, you can add exposed filters to your date fields. Setting the filter option **Date selection form element** to *select* will provide the dropdown selection widget for your date.

Finally, under the Advanced \> Exposed form \> Exposed form style \> Settings link there's an **Autosubmit** option that will submit the filter form upon date change.
> 1 votes

---
Tags: 7, views, datetime
---


# Question
Title: Drupal 8 + Twig background-color -field select
How I do with twig this:

I got list -field where I got differents color:

black|Black

grey|Grey

---

black = background-color: #000;

grey = background-color: #eee;

---

When I select Black it will appear somewhere on the node or field.

```
<div class="black">Example</div>

```

# Answer
> 1 votes
One way to do this is provide a field template for that field that just prints the value and no markup:

**field--your-field-name.html.twig**:

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

```

Then in the main template, wherever you want to output that field value, you would have:

```
<div class="{{ content.your_field_name|trim }}">Example</div>

```

The result should be just the field value, with no whitespace, so "black" or "grey".

---
Tags: theming, 8
---


# Question
Title: customizing an info window with geolocation views
I have been beating myself up a lot with this problem. I can't for the life of me figure it out.

I am using Drupal 7, using the geolocation module, specifically the views part.

I am essentially trying to put a view for each node within this map view.

It works really well, however, it doesn't render in a particularly nice way for the user.

I am guessing that I can sort this out in css. However, I can't for the life of me figure out which div class to alter. The one that I think I want to alter is just a standard Div tag. I am sure I am missing something, but I just can't work it out. I tried altering the .balloon class, but got some weird results.

Thanks in advance,

Mark.

# Answer
> 1 votes
Having clarified this with the developer, you need to alter the ip\_geoloc\_gmap\_multi\_loc.js file at line 165. This relates to the infoWindow maxWidth setting. Essentially I have tried to increase this massively.

This sorts out the problem for me, and the developer advised me that this should not cause a problem.

I couldn't work out how to do this with css. Might be possible...but I couldn't work it out...

...hope this helps someone in the future, as it caused me quite a headache!

Thanks again for your posts,

Mark.

---
Tags: views, theming
---


title: Changing user edit form

text:
# Question
Title: Changing user edit form
I am trying to change my Drupal 8 theme user edit form but can't find a template to override. I want't to make something like this: http://keenthemes.com/preview/metronic/theme/admin\_1/page\_user\_profile\_1\_account.html

Is it possible? Thank you!

# Answer
> 2 votes
To preface, changing the Drupal user edit forms is not the most straightforward thing to do (when compared to changing the templates for regular site's theme), but it is *possible*, just as anything else. Firstly, are you currently using one of the stock admin themes (e.g. Seven)? If so, you will need to sub-theme that, which is done in the same way as you create a normal theme, then you just configure your site to use that admin theme. Then, you can override templates. In the case of the user edit form, it will depend the level of customization you want to do to the form. If you turn on debugging (see https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates), then you will be able to see the templates you need to override at the form and field level. Of course, if you can do what you need to do with CSS or Javascript (and it's not too kludgey), that is something to consider as well to avoid the pain of having to mess with the generation of the actual markup.

---
Tags: 8, forms
---


title: Error after updating?

text:
# Question
Title: Error after updating?
I am updating a development environment; after updating to Drupal 8.3.0, I can't access /user/login.

These are the errors from my log.

> \[Mon Apr 10 15:57:50.142266 2017\] \[:error\] \[pid 22325\] \[client 172.16.8.46:65128\] Recoverable fatal error: Object of class Drupal\Core\Link could not be converted to string in /var/www/html/core/lib/Drupal/Component/Utility/Xss.php on line 67 #0 /var/www/html/core/includes/bootstrap.inc(552): \_drupal\_error\_handler\_real(4096, 'Object of class...', '/var/www/html/c...', 67, Array)\n#1 \[internal function\]: \_drupal\_error\_handler(4096, 'Object of class...', '/var/www/html/c...', 67, Array)\n#2 /var/www/html/core/lib/Drupal/Component/Utility/Xss.php(67): str\_replace('\x00', '', Object(Drupal\Core\Link))\n#3 /var/www/html/core/lib/Drupal/Core/Render/Renderer.php(749): Drupal\Component\Utility\Xss::filter(Object(Drupal\Core\Link), Array)\n#4 /var/www/html/core/lib/Drupal/Core/Render/Renderer.php(382): Drupal\Core\Render\Renderer-\>ensureMarkupIsSafe(Array)\n#5 /var/www/html/core/lib/Drupal/Core/Render/Renderer.php(448): Drupal\Core\Render\Renderer-\>doRender(Array)\n#6 /var/www/html/core/lib/Drupal/Core/Render/Renderer.php(195): Drupal\Core\Render\Renderer-\>doRender(Array, false)\n#7 /var/www/html/core/lib/Drupal/Core/Render/MainContent/HtmlRenderer.php(226): Drupal\Core\Render\Renderer-\>render(Array, false)\n#8 /var/www/html/core/lib/Drupal/Core/Render/Renderer.php(574): Drupal\Core\Render\MainContent\HtmlRenderer-\>Drupal\Core\Render\MainContent\\{closure}()\n#9 /var/www/html/core/lib/Drupal/Core/Render/MainContent/HtmlRenderer.php(227): Drupal\Core\Render\Renderer-\>executeInRenderContext(Object(Drupal\Core\Render\RenderContext), Object(Closure))\n#10 /var/www/html/core/lib/Drupal/Core/Render/MainContent/HtmlRenderer.php(117): Drupal\Core\Render\MainContent\HtmlRenderer-\>prepare(Array, Object(Symfony\Component\HttpFoundation\Request), Object(Drupal\Core\Routing\CurrentRouteMatch))\n#11 /var/www/html/core/lib/Drupal/Core/EventSubscriber/MainContentViewSubscriber.php(90): Drupal\Core\Render\MainContent\HtmlRenderer-\>renderResponse(Array, Object(Symfony\Component\HttpFoundation\Request), Object(Drupal\Core\Routing\CurrentRouteMatch))\n#12 /var/www/html/core/lib/Drupal/Component/EventDispatcher/ContainerAwareEventDispatcher.php(111): Drupal\Core\EventSubscriber\MainContentViewSubscriber-\>onViewRenderArray(Object(Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent), 'kernel.view', Object(Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher))\n#13 /var/www/html/vendor/symfony/http-kernel/HttpKernel.php(149): Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher-\>dispatch('kernel.view', Object(Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent))\n#14 /var/www/html/vendor/symfony/http-kernel/HttpKernel.php(64): Symfony\Component\HttpKernel\HttpKernel-\>handleRaw(Object(Symfony\Component\HttpFoundation\Request), 1)\n#15 /var/www/html/core/lib/Drupal/Core/StackMiddleware/Session.php(57): Symfony\Component\HttpKernel\HttpKernel-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)\n#16 /var/www/html/core/lib/Drupal/Core/StackMiddleware/KernelPreHandle.php(47): Drupal\Core\StackMiddleware\Session-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)\n#17 /var/www/html/core/modules/page\_cache/src/StackMiddleware/PageCache.php(207): Drupal\Core\StackMiddleware\KernelPreHandle-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)\n#18 /var/www/html/core/modules/page\_cache/src/StackMiddleware/PageCache.php(121): Drupal\page\_cache\StackMiddleware\PageCache-\>fetch(Object(Symfony\Component\HttpFoundation\Request), 1, true)\n#19 /var/www/html/core/modules/page\_cache/src/StackMiddleware/PageCache.php(75): Drupal\page\_cache\StackMiddleware\PageCache-\>lookup(Object(Symfony\Component\HttpFoundation\Request), 1, true)\n#20 /var/www/html/core/lib/Drupal/Core/StackMiddleware/ReverseProxyMiddleware.php(47): Drupal\page\_cache\StackMiddleware\PageCache-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)\n#21 /var/www/html/core/lib/Drupal/Core/StackMiddleware/NegotiationMiddleware.php(50): Drupal\Core\StackMiddleware\ReverseProxyMiddleware-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)\n#22 /var/www/html/vendor/stack/builder/src/Stack/StackedHttpKernel.php(23): Drupal\Core\StackMiddleware\NegotiationMiddleware-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)\n#23 /var/www/html/core/lib/Drupal/Core/DrupalKernel.php(656): Stack\StackedHttpKernel-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)\n#24 /var/www/html/index.php(19): Drupal\Core\DrupalKernel-\>handle(Object(Symfony\Component\HttpFoundation\Request))\n#25 {main}

Any help is very much appreciated.

# Answer
Not possible to see much, as it is set indirectly through a render array. You seem to have some code that is setting a link object on a #markup. Either a custom or a contrib module.

```
/var/www/html/core/lib/Drupal/Core/Render/Renderer.php(749): Drupal\Component\Utility\Xss::filter(Object(Drupal\Core\Link), Array)

```

This is where you want to start debugging, check that line and the Xss::filter() call, check the argument for a link object and if it is, dump that render array to see if you can figure out what it is. Calling toUrl() on the link might help for example, so you see what kind of link it is.
> 1 votes

---
Tags: updating
---


# Question
Title: How to do dependency injection on complex classes like when extending WidgetBase
Since the Drupal sniffer whines at you if you call `\Drupal::service()` in your code, I have been trying to figure out how to use dependency injection on a widget I’ve been working on. Here’s what I’ve currently arrived at:

```
<?php

use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\xois\SicsService;
use Symfony\Component\DependencyInjection\ContainerInterface;

class XoisSicSelect extends WidgetBase {

  /**
  * SICs service.
  *
  * @var \Drupal\xois\SicsService
  */
  protected $sicsService;

  /**
  * {@inheritdoc}
  */
  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, SicsService $sicsService) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);
    $this->sicsService = $sicsService;
  }

  /**
  * {@inheritdoc}
  */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('xois.sics')
    );
  }

}

```

Pretty much the standard DI pattern, no? Only difference is that WidgetBase takes a whole load of construct parameters already.
Problem is, it doesn’t work. When run, it gives this delightful error:

```
The website encountered an unexpected error. Please try again later.
Recoverable fatal error: Argument 6 passed to Drupal\xois\Plugin\Field\FieldWidget\XoisSicSelect::__construct() must be an instance of Drupal\xois\SicsService, none given, called in /var/www/docroot/core/lib/Drupal/Core/Field/WidgetPluginManager.php on line 125 and defined in Drupal\xois\Plugin\Field\FieldWidget\XoisSicSelect->__construct() (line 35 of modules/xois/src/Plugin/Field/FieldWidget/XoisSicSelect.php).

```

Anyone got an idea on how to accomplish this?

# Answer
> 5 votes
You will need to implement `ContainerFactoryPluginInterface` in order to use dependency injection in your class.

Include `use Drupal\Core\Plugin\ContainerFactoryPluginInterface;` and implement the interface so it looks like:

```
class XoisSicSelect extends WidgetBase implements ContainerFactoryPluginInterface {

    ....

}

```

You will also need to make sure your `__construct()` and `create()` methods contain the correct parameters.

If you look at `ContainerFactoryPluginInterface.php`, you will see the parameters the `create()` method takes in:

```
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition);

```

Thus, your final code should look like:

```
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\xois\SicsService;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;

class XoisSicSelect extends WidgetBase implements ContainerFactoryPluginInterface {
  /**
   * SICs service.
   *
   * @var \Drupal\xois\SicsService
   */
  protected $sicsService;

  /**
   * {@inheritdoc}
   */
  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, SicsService $sicsService) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);
    $this->sicsService = $sicsService;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $plugin_id,
      $plugin_definition,
      $configuration['field_definition'],
      $configuration['settings'],
      $configuration['third_party_settings'],
      $container->get('xois.sics')
    );
  }
}

```

# Answer
> 2 votes
This was a difficult one for myself as well. How I figured out to resolve it was to go to the documentation page for the class (ex WidgetBase), and look for the \__construct() method (ex WidgetBase::\__construct()). Click on that, and you'll see a section for "X methods override CLASSNAME::\__construct()". For example, DateRangeDefaultWidget::\__construct overrides WidgetBase::\__construct(). Click on the override, and you'll an example of what the \__construct() override should look like:

```
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, EntityStorageInterface $date_storage) {
  parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);

  $this->dateStorage = $date_storage;
}

```

And if you look at the class page (ex DateRangeDefaultWidget), you can find what the create() method should look like: DateRangeDefaultWidget::create):

```
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
  return new static(
  $plugin_id,
  $plugin_definition,
  $configuration['field_definition'],
  $configuration['settings'],
  $configuration['third_party_settings'],
  $container->get('entity_type.manager')->getStorage('date_format')
  );
}

```

So it takes a bit of detective work, but once you figure out the method of detecting, it's actually fairly straightforward for any classes.

# Answer
> 1 votes
You need to copy the create() method and add your argument, not replace it.

There's no magic involved, it's just a plain static PHP method that contructs an object, including all its arguments.

---
Tags: 8, dependency-injection
---


# Question
Title: Why would some images be saved to field_image / some maintain href after on import from Blogger?
Using Blogger Importer, I pulled content from Blogger. The posts include images embedded in the text and a small image gallery at the base of the post that was built (rather painfully) using tables.

Reading this Cheeky Monkey post, I saw that they had modified the module to aid with image import since the standard module didn't handle that well. I got very mixed results.

For some posts, the images are correctly identified and added to "field\_image" as specified. For others, the images remain embedded in the text with a URL reference back to blogger.

Cheeky Monkey updated code:

```
      // Image downloaded successfully.
          if ($response->code == 200) {
            // Save it.
            $file = file_save_data($response->data, $filepath, FILE_EXISTS_REPLACE);

            // Save the image to the field_image now
            $node->field_image[LANGUAGE_NONE][] = array('fid' => $file->fid, 'display' => 1);
          }
        }

```

I would like to head in this direction, so that I can have better controls over the image gallery views / template. That said, I also see that the embedded images look much sharper than the images that have been saved in field\_image. (Might fix that if with color box, but am not sure.)

This particular post came in with a mix of how the images were handled. The images at the top of the post are saved in field\_image, while the image midway in the text and thumbnail at the bottom reference the blogger href. Here's the original post in blogger.

# Answer
The issue you described with some images not importing (keeping the blogger URL) is caused by the regex not identifying the image URLs as blogger hosted images. This regex can currently be found in the same file batch.nodes.inc on line 213 :

```
      if (preg_match_all('/(href|src)="(http:\/\/.*?\.blogspot\.com\/(.*?))"/', $node->body[LANGUAGE_NONE][0]['value'], $matches)
      || preg_match_all('/(href|src)="(http:\/\/.*?\.blogger\.com\/(.*?))"/', $node->body[LANGUAGE_NONE][0]['value'], $matches)) {

```

The code that worked for me is follows :

```
      if (preg_match_all('/(href|src)="(https?:\/\/[0-9a-z\.]+blogspot\.com\/(.*?))"/', $node->body[LANGUAGE_NONE][0]['value'], $matches)
      || preg_match_all('/(href|src)="(https?:\/\/[0-9a-z\.]+blogger\.com\/(.*?))"/', $node->body[LANGUAGE_NONE][0]['value'], $matches)) {

```

This could be improved but worked for me. It allows for http and https. And the .\* was grabbing too much text before an image if there was a link above the image.

For the image quality, note that blogger uses different quality of image for displaying within the post and when clicking on the image. Note the number contained within the URL s200 is low resolution, s1600 is high resolution. Other numbers could be used for different size image. You will have to decide which image to save or create a field to save two versions of each image.
> 0 votes

---
Tags: migrations, importing-exporting, media
---


title: Migrate statistics

text:
# Question
Title: Migrate statistics
Is there an automatic way to import, with migrate, statistics (from core module statistics) from d7 to d8?

The "dirty" way could be export statistics from d7, loop on these values and then run a insert query on node\_counter table..

# Answer
> -1 votes
Support for this is being added to Drupal 8 core: https://www.drupal.org/node/2500521. You can try applying the latest patch and seeing if it works for you (and if so - or, if not - please report back in the issue!).

Thanks.

---
Tags: migrations, nodes
---


# Question
Title: extracting data from specific content type
I have an old site developed with drupal 7 and now I have created a new site (with new template) with drupal 8. I want to extract a specific content type data and restore in the new site. suppose I have a content type called Academic and I want to restore it on the new site. Is it possible to do that automatically, because it has more than 1000 contents. Any help would be appreciated. Thanks in advance

# Answer
> 1 votes
You can create a custom migration for that node type - see https://www.drupaleasy.com/blogs/ultimike/2016/04/drupal-6-drupal-81x-custom-content-migration (more than you need for just the one migration, but it should help).

---
Tags: migrations, backups
---


# Question
Title: Is there an easy way to call a migration from a controller for debugging purposes
I am trying to debug a migration and having issues getting xdebug to work with drush as I described in this issue. Would there be an easy way for me to call a migration from a controller (I am able to text xdebug from browser)?

For example, I would like to debug this:

```
drush mi upgrade_d6_field_instance

```

I was thinking to create a custom module that adds a controller that I can call the migration from the browser. The only option I cant think of is to recreate a lot of the functions from migrate\_tools in the controller but I feel like there has to be an easier way.

# Answer
> 1 votes
Actually, the code isn't that hard to recreate from migration\_tools. Here is my controller class:

```
<?php

namespace Drupal\custom_migration\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\migrate\MigrateExecutable;
use Drupal\migrate\MigrateMessage;

class MigrateController extends ControllerBase {

  public function process() {

    $migration = \Drupal::service('plugin.manager.config_entity_migration')->createInstance('upgrade_d6_field_instance');
    $executable = new MigrateExecutable($migration, new MigrateMessage());
    $executable->import();

    return ['#markup' => 'Migrate Debugging'];
  }
}

```

# Answer
> 0 votes
I've found debugging drush commands in PhpStorm pretty easy - at least when not running them in a VM (still struggling with setting that up). One key point is that in Preferences-\>Languages & Frameworks-\>PHP-\>Debug, be sure to bump up "Max simultaneous connections" (I have mine set to 10), a value of 1 will *not* work with drush.

---
Tags: 8, migrations
---


title: Multiple shipping addresses

text:
# Question
Title: Multiple shipping addresses
We're building a Drupal 7 website with Drupal Commerce and our client would like to give the customer the ability to add multiple shipping addresses on the registration page.

The customer would then be given the option to select one of these addresses during checkout.

Is this native functionality or can we deliver this via a module?

# Answer
> 0 votes
Lucky you, someone built exactly that:

Commerce Addressbook Extra

> This module for Drupal Commerce extends Commerce Addressbook module and allows to add customer profiles from Register form.

It sits on top of Commerce Addressbook

> Commerce Addressbook is a module that allows authenticated customers to reuse previously entered addresses during checkout. They can manage all entered addresses in their user panel (user/%user/addressbook).

---
Tags: commerce
---


# Question
Title: Where are the primary and secondary tab blocks?
I installed drupal 8 using the **minimal** install profile. For the admin pages I enabled the seven admin theme, but in the blocks admin screen I cannot find the **Primary tabs** and **Secondary tabs** blocks.

# Answer
They are available under other names (I think one is called "Tabs") when you used the the **minimal** installation profile.

But you can import the blocks by entering the code of the files

```
profiles/standard/config/install/block.block.seven_primary_local_tasks.yml
profiles/standard/config/install/block.block.seven_secondary_local_tasks.yml

```

into the Single config import located at

```
admin/config/development/configuration/single/import

```

(this requires the config management module to be enabled)
> 2 votes

# Answer
I had the same problem, and I've just found the problem (bug).

In Drupal 8 (at least 8.3), there are 4 blocks ('Primary tabs', 'Secondary tabs', 'Page title', and 'Primary admin actions') that are all "install configs" within the standard install profile. In other words, they get created when you install drupal.

But they all have a **dependency of the Seven theme**. In other words, when you delete Seven, they are deleted. And they don't get re-created when you install Seven, because they aren't install configs of Seven, they're install configs of the Standard install profile.

**Try this:**

Use Drush or Drupal console or the built-in Configuration Synchronisation to export your current configuration. Then copy the config files...

* `core/profiles/standard/config/install/block.block.seven_local_actions.yml`
* `core/profiles/standard/config/install/block.block.seven_page_title.yml`
* `core/profiles/standard/config/install/block.block.seven_primary_local_tasks.yml`
* `core/profiles/standard/config/install/block.block.seven_secondary_local_tasks.yml`

... into your config folder - which is probably `/sites/default/files/config_[hashcode]/sync/`. Then do a config import (using one of those 3 tools above).
> 2 votes

---
Tags: 8, blocks
---


# Question
Title: Multiple modules extending form in OOP way, with no hook_form_alter()
I know very well how `hook_form_alter()` is working in Drupal 7 and in Drupal 8, but the main topic here is how to do things OOP way.

How would you solve the following problem the OOP way?

Suppose you have a random form, for example the user login form.

* custom\_module\_A adds a checkbox to the form and a custom validation handler
* custom\_module\_B adds a textfield to the same form and another custom validation handler

The OOP way of altering the form is:

1. intercepts the original **UserLoginForm** and directs to a **CustomModuleNewForm**\- an extended class from user\_login\_form class
2. Write a class that extends the user login form

I am unable to "grokh" how this can be solved the OOP way, by extending the form in custom\_module\_A and not having custom\_module\_A as a dependency for custom\_module\_B.

Basically, I am looking for OOP `hook_form_alter()` replacement.

# Answer
> 4 votes
Good question. The alter hooks will eventually be replaced, not by extending form classes, but by symfony events. Events are coded in OOP and they have a proper priority handling. See https://www.previousnext.com.au/blog/alter-or-dispatch-drupal-8-events-versus-alter-hooks

# Answer
> 2 votes
A way to do it is with this module.

https://www.drupal.org/project/hook\_event\_dispatcher

I still have to test it in detail.

Another interesting resource I've found. https://www.sitepoint.com/drupal-8-hooks-symfony-event-dispatcher/

# Answer
> 1 votes
Since Drupal 8 is still using `hook_form_alter()` and `hook_form_FORM_ID_alter()`, altering a form just using a class is not yet possible. Allowing all the modules to change the class associated to a form is a bad idea, since that would just create conflicts between modules that are not that easy to resolve, if not by using complicated `if()` statements to verify which module has earlier replaced the class handling the form. Plus, there would be a conflict with Drupal core, which still allow modules to use `hook_form_alter()` and `hook_form_FORM_ID_alter()`.

As 4k4 said, the right direction is using events, but for that we need to wait for a future Drupal version, which will probably replace hooks with events and event handlers. (I am not sure all the hooks are going to be replaced, thought; maybe the alter hooks will be kept, even if I hope we are going to use just events and event handlers, which are more OOP than the actual code.)

Drupal 9 didn't replace hooks with events; `hook_form_alter()` is still the way to alter forms implemented by other modules.

---
Tags: 8, forms
---


title: Multiple image field in block form

text:
# Question
Title: Multiple image field in block form
I wanna add in a block configuration form an image field that can take several images, just like in a node form, with all the drag'n drop stuff, etc. Any advices or solutions?

# Answer
> 0 votes
The solution is an image field configured in a custom block type.

Block forms are configuration and don't support image fields. Custom block types are content and they support the same field types as nodes.

If you can't do what you want with a custom block type, you can create your own block plugin which uses a block content entity.

For background information see these questions Adding custom block problems and Blocks: Old vs. "Custom" and Config vs. Fields.

---
Tags: forms, blocks, media
---


# Question
Title: How to debug a configuration object, when testing?
I write tests for a custom module using Drupal\simpletest\WebTestBase. I can not find a method, how to debug the configuration object.

I tried e.g. the following commands:

```
$config = \Drupal::config('mymodule.settings');

debug($config); // AJAX-HTTP-Error
debug(get_object_vars($config)); // Empty array
debug($config->getRawData()); // Empty array
debug($config->getOriginal()); // Empty array
dump($config); // AJAX-HTTP-Error
var_dump($config); // Needs extremely long time
ksm($config); // Nothing is shown
kint($config); // Nothing is shown
dpm($config); // ServiceNotFoundException
dpm($config->toArray()); // AJAX-HTTP-Error
dsm(get_object_vars($config)); // ServiceNotFoundException
print_r($config); // Needs extremely long time

```

The debug() command works fine for arrays and strings (and is nice integrated in the test report).

```
 debug($var, 'Label');

```

# Answer
You can use `Config::get()`, for which:

> If no key is specified, then the entire data array is returned.

e.g.

```
debug(\Drupal::config('mymodule.settings')->get());

```
> 2 votes

---
Tags: 8, testing
---


# Question
Title: How to obtain only published entities from field collection items in database, insted I've get all entities
I want to obtain values from field collection and put it into an array an then display it in my twig template using for loop.

```
// MYTHEME.theme

/*

    Get social media links from sql

*/
  function MYTHEME_theme_preprocess_block__socialmedia(&$variables) {

      // Get data
      $get_links = db_query('
        SELECT DISTINCT
          social_media_select.entity_id                         as social_media_id,
          social_media_select.field_social_media_select_value   as social_media_select_val,
          social_media_link.field_social_media_link_value       as social_media_link_val,
          social_media_title.field_social_media_title_value     as social_media_title_val

        FROM field_collection_item__field_social_media_select social_media_select
        JOIN field_collection_item__field_social_media_link social_media_link ON social_media_select.entity_id = social_media_link.entity_id
        JOIN field_collection_item__field_social_media_title social_media_title ON social_media_select.entity_id = social_media_title.entity_id
      ');

      foreach ($get_links as $link) {

         // store array into global drupal $variables
         $variables['social_media_links'][] = array(
            'link_id' => $link->social_media_id,
            'selected' => $link->social_media_select_val,
            'url' => $link->social_media_link_val,
            'title' => $link->social_media_title_val,
         );
      } // endforeach

  }

```

And in TWIG template I've use this to display all fields and it works as it should. But there is problem becouse it shows all entities ever entered. If I remove some social links from drupal it still shows up in my frontend and if I look into database it is still there.

How to menage to display only active-published fields from field collection item?

```
// block--socialmedia.html.twig

{% for link in social_media_links %}

<li>
    <a href="{{ link.url }}" target="_blank" title="{{ link.title }}">
        <i class="demo-icon"></i>
    </a>
</li>

{% endfor %}

```

# Answer
SOLVED! I find out the solution, hope someone will find useful.

When you use sql to directly retreive fields/entities from drupal there is one more thing to do in order to display only active fields with latest revision.

You need to check is that particular field has recent revisions and then to display his latest revision. In oposite case it will display all fields ever made no meter if they was deleted or changed.

You need JOIN revision table as well

```
# find out revision_id and connect with node_revision
JOIN field_collection_item_revision field_revision ON social_media_select.entity_id = field_revision.item_id
JOIN node_revision__field_social_media revision ON field_revision.revision_id = revision.field_social_media_revision_id
JOIN node_field_revision ON revision.revision_id = node_field_revision.vid

# get only latest revision
JOIN node ON node.vid = node_field_revision.vid

```

So now my code now looks like this.

```
// MYTHEME.theme

/*

Get social media links from sql

*/
function MYTHEME_theme_preprocess_block__socialmedia(&$variables) {

  // Get data
  $get_links = db_query('
    SELECT DISTINCT
      social_media_select.entity_id                         as social_media_id,
      social_media_select.field_social_media_select_value   as social_media_select_val,
      social_media_link.field_social_media_link_value       as social_media_link_val,
      social_media_title.field_social_media_title_value     as social_media_title_val

    FROM field_collection_item__field_social_media_select social_media_select
    JOIN field_collection_item__field_social_media_link social_media_link ON social_media_select.entity_id = social_media_link.entity_id
    JOIN field_collection_item__field_social_media_title social_media_title ON social_media_select.entity_id = social_media_title.entity_id

    /* I've addeded this code below -------------------------------- */

      # find out revision_id and connect with node_revision
      JOIN field_collection_item_revision field_revision ON social_media_select.entity_id = field_revision.item_id
      JOIN node_revision__field_social_media revision ON field_revision.revision_id = revision.field_social_media_revision_id
      JOIN node_field_revision ON revision.revision_id = node_field_revision.vid

      # get only latest revision
      JOIN node ON node.vid = node_field_revision.vid

   /* ------------------------------------------------------ */

  ');

  foreach ($get_links as $link) {

     // store array into global drupal $variables
     $variables['social_media_links'][] = array(
        'link_id' => $link->social_media_id,
        'selected' => $link->social_media_select_val,
        'url' => $link->social_media_link_val,
        'title' => $link->social_media_title_val,
     );
  } // endforeach

```

}
> 0 votes

---
Tags: database, entities
---


# Question
Title: How to create file repository from which I can link files to other content types?
I want to be able to "link" files to my content types. Two different nodes in two different content types can link to the same file, so I don't want use file upload field to avoid content duplication.

I also want to have publicly available "repository" where there is a list of all available files and for each file there is a list of articles / nodes to which this file is linked.

What is the simplest way to achieve this. Is there a reference field or something like that?

I would like to have little search field when linking files to content.

# Answer
> 1 votes
You could use the excellent File Browser (https://www.drupal.org/project/file\_browser) which provides a very slick interface (see DropzoneJS), for both uploading new files as well as re-using (referencing) existing ones.

As a side-note: Content duplication will not be a problem, if you offer your users the option to upload and re-use. That way, you can stick to the standard reference direction, Content -\> File, instead of implementing a File -\> Content (which is also valid, but, less used in my experience).

# Answer
> 1 votes
As said in the comments:

Media module is just the thing you are looking for. We are also using it in our project, it's pretty good and solves all the problems you listed.

It's maybe also important to mention that this is going to be part of the core very soon (8.4.x).

---
Tags: 8, files, navigation, entities
---


title: Adding read more link

text:
# Question
Title: Adding read more link
I have 1 blog block in the home page where i am displaying the title and body of the body of the blog up to 2 lines.After that I want to add read more link which redirect to the blog content type.I am using views there in the preview it is read more link is showing correctly. but not displaying in the content page. I used this code below in node.content type.tpl.php to display the read more link. But the read more link is not adding to the blog . but to some other content in that page. Please suggest how to do this?

```
<div class="content"<?php print $content_attributes; ?>> <?php hide($content['links']); hide($content['links']['#links']['node-readmore']); print render($content); if($teaser) { print l(t('Read more'), 'node/' . $nid, array('attributes' => array('class' => t('node-readmore-link')))); }?></div> <?php print render($content['links']); ?>

```

# Answer
> 0 votes
All you have to do is add a field to the view output that is the node link, and give it the label of "Read more". You don't have to add anything to a template file for this unless you are using a view mode and telling Views to output a rendered entity.

If you are using a view mode, you don't need to add a field to the content type anyway. You can just edit the view mode template (`node--node_type--view_mode.tpl.php` if I am not mistaken) and output the node path as:

`<?php print l('Read More', $node->nid); ?>`

Note that since you are doing view mode templates, there is no reason to check for `if ($teaser)` \- because you know you are working within a designated view mode template. I would advise creating a view mode like "Sidebar Item" so you know exactly what it is for. In this example, the template would be `node--node_type--sidebar_item.tpl.php` where `node_type` is page, article... whatever the node type is.

The code in your question is actually over complicating it in my opinion, and you can rectify this in just a couple of minutes by simplifying it.

# Answer
> 0 votes
According to the my understanding of your question you want to display the some characters of the body on the node content page then GO to the content type body field in "manage display" Select the trimmed option with limit of characters

See the screenshot:

---
Tags: 7, views
---


# Question
Title: How to preserve element type validation upon adding custom element validation?
I have ConfigFormBase. It has a form element with `'#type' => 'entity_autocomplete'`.

**When I add my custom element validation** by `'#element_validate' => [[get_class($this), 'validateReferencedItemExistence']]` **the original element validation** which comes by the element type (`Drupal\Core\Entity\Element\EntityAutocomplete::validateEntityAutocomplete`) **won't be added anymore**.

After spending hours in the jungle of the `FormBuilder` class code I finally found the corresponding lines:

```
   if (isset($element['#type']) && empty($element['#defaults_loaded']) && ($info = $this->elementInfo->getInfo($element['#type']))) {
      // Overlay $info onto $element, retaining preexisting keys in $element.
      $element += $info;
      $element['#defaults_loaded'] = TRUE;
    }

```

I find this kinda bad approach, that you cannot extend the list of the validation items. What is the reason behind it?

**How could I make a workaround / solve this issue?**

(Just by calling `Drupal\Core\Entity\Element\EntityAutocomplete::validateEntityAutocomplete` in my custom validation I would create an unnecessary depedency in my code. (Just think about if they change their way of validation with a different function))

# Answer
You need add the definitions defined in the getInfo() method of that type explicitly yourself, there is currently no other way to do that.
> 1 votes

---
Tags: 8, forms
---


# Question
Title: How can I get module configuration for testing
I write tests for a form in a custom module using Drupal\simpletest\WebTestBase. I want to test, if the module settings are displayed in the configuration form. But the problem is, that I can not get the saved settings:

```
$config = $this->config('mymodule.settings');
debug($config->get(), 'Configuration object'); // Returns an empty array

```

I have found, that the same problem is e.g. in the demo module described in an article on Sitepoint, see: https://github.com/upchuk/d8-demo-modules/blob/master/demo/src/Tests/DemoTest.php#L59

> E.g. $config-\>get('demo.email\_address') returns always ''.

The tests seem to work well, but when I add debug($config-\>get()), then I also receive an empty array. It means, that all the test cases use empty variables and return false positive results.

I have also tried:

```
debug(\Drupal::config('mymodule.settings')->get()); // Empty array
debug(\Drupal::configFactory()->getEditable('mymodule.settings')->get()); // Empty array
debug(\Drupal::config('system.site')->get()); // Correct array with site settings

```

---

The module and the form are working correctly and all the settings are stored in the database.

# Answer
The tests do not care about the settings, which are saved in the database. They work with settings in config/import/mymodule.settings.yml

The file can look like this:

```
var1: 'Some text'
var2: 1
var3: http://example.org

```

More info: https://www.drupal.org/docs/8/creating-custom-modules/include-default-configuration-in-your-drupal-8-module
> 1 votes

---
Tags: 8, testing
---


# Question
Title: Is there a way to manage public API documentation?
I have created a custom module for my site that includes a public REST API. We've also written public documentation for the API. It's currently written in Markdown for convenience and easy export. We maintain the documentation in version control so that it stays up-to-date along with changes to the endpoint in the module itself.

We would like to publish this documentation to the site in a way that is publicly accessible. I've found documentation on `hook_help` but that seems to be targeted towards site admins (e.g. documenting settings for the module). Instead, we're looking to document the API endpoint for an end user. We know we could simply create Page content to hold the documentation but we were looking for something more automatic when the module code is updated.

Is `hook_help` still the right way to add this content to the site? Is there a way to make only portions of the Help section public? Or is there another way to publish API documentation as part of the module?

We are currently on Drupal 7 if it is relevant.

EDIT:

Additional Info:

* We are using the Services module to manage the API endpoint(s)
* We are less looking for documentation generation and more looking for a way to publish the documentation that we have already written in a way that it is updated automatically when the module is updated. We maintain our documentation in version control so that it is updated as part of development. By doing it manually, it is more comprehensive and directly useful than generated documentation (IMO). We would just like the work done during development to be displayed publicly without having to do the extra step of copy-pasting to a Page (a step which is easily forgotten).

# Answer
> 1 votes
So far as I know for community driven modules only the Services module has support to autogenerate API documentation via the Services Documention module. If you've been the D7 public API without using Services ... then you may be out of luck.

> The Services Documentation module generates API documentation for your site’s Services resources. Most of the documentation is generated automatically, using the resource information provided by Services. However, this module provides you with the ability to easily extend that documentation.
>
> We make the following assumptions about your usage of the Services module:
>
> * You are providing an API to a third party, which allows them to access your data via Services.
> * You would like to provide a page to API consumers that documents your API endpoints, resources, etc.
>
> Documentation will be made available on your Drupal site at /developers. It will be organized by API version (arbitrarily defined by you), and subsequently displayed hierarchically according to resource, method type, method name, arguments, etc.

# Answer
> 1 votes
One solution you should look at is the combination of RAML and publishing via Hitch.

While it would require you to create a new RAML from scratch (AFAIK there are no generators for Drupal) you get a lot of advantages when using RAML including:

1. Ability to generate a test suite.
2. Parsers allow you to generate stubs or test changes really easily.
3. You can publish PDF/HTML versions of your documentation using tools such as raml2pdf and raml2md.
4. You can use schemas to validate your examples and ensure internal consistency.
5. RAML 1.0 is pretty expressive and you can generate internal templates and use things like inheritance to make building RAML files fairly straight-forward and less time consuming.

As an example, it's possible to define "types":

```
types:
  BaseObject:
    description: A base object.
    type: object
    properties:
      id: number
      created: number
      update: number

  AnotherType:
    type: BaseObject
    properties:
      new_property: string

```

Then within your RAML file you can say that a certain type of request accepts an `AnotherType` or returns `AnotherType[]`.

Once you've got a RAML file, you can then upload it to something like Hitch which can post updates to interested parties and helps spread the word about your services.

Yes, this would require extra-Drupal resources and time, but in my experience this has been worth it.

---
Tags: hooks
---


title: How do I add a Twig Filter?

text:
# Question
Title: How do I add a Twig Filter?
I made a custom module that extends TwigExtension, where I define all sort of custom twig filters. It worked well until the update to 8.3, where TwigExtension changed slightly:

```
/**
* Constructs \Drupal\Core\Template\TwigExtension.
*
* @param \Drupal\Core\Render\RendererInterface $renderer
*   The renderer.
* @param \Drupal\Core\Routing\UrlGeneratorInterface $url_generator
*   The URL generator.
* @param \Drupal\Core\Theme\ThemeManagerInterface $theme_manager
*   The theme manager.
* @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
*   The date formatter.
*/
public function __construct(RendererInterface $renderer,
  UrlGeneratorInterface $url_generator, ThemeManagerInterface
  $theme_manager, DateFormatterInterface $date_formatter) {
  $this->renderer = $renderer;
  $this->urlGenerator = $url_generator;
  $this->themeManager = $theme_manager;
  $this->dateFormatter = $date_formatter;
}

```

My service yaml looked like this:

```
services:
  custom_twig.twig.extension:
    arguments: ['@renderer']
class: Drupal\custom_twig\TwigExtension\LabTwigExtension
tags:
  - { name: twig.extension }

```

And I changed the services to have the new required ones.

```
services:
  custom_twig.twig.extension:
    arguments: ['@renderer', '@url_generator', '@theme.manager','@date.formatter']
class: Drupal\custom_twig\TwigExtension\LabTwigExtension
tags:
  - { name: twig.extension }

```

Although I set the correct arguments, Drupal throws an error:

> Recoverable fatal error: Argument 2 passed to Drupal\Core\Template\TwigExtension::\__construct() must implement interface Drupal\Core\Routing\UrlGeneratorInterface, none given, called in /A

I am fairly certain that url\_generator implement UrlGeneratorInterface. Is there anything else I got wrong?

# Answer
> 0 votes
If you are using Twig Extender , try updating it to version 8.x-2.0-rc1. It worked for me

---
Tags: 8
---


# Question
Title: rest namespace not recoginzed in custom REST API class
I'm working on creating my first custom REST resource in D8, and following this blog post, I have the following class in the /modules/custom/video\_export/src/Plugin/rest/resource directory:

```
<?php
/**
 * @file
 * Custom Rest resource for video nodes.
 */

namespace Drupal\video_export\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Drupal\Core\Session\AccountProxyInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Psr\Log\LoggerInterface;

/**
 * Provides a resource for database watchdog log entries.
 *
 * @RestResource(
 *   id = "video_export_source",
 *   label = @Translation("Video Export Source"),
 *   uri_paths = {
 *     "canonical" = "/videos/feed/{site}"
 *   }
 * )
 */

class VideoExportResource extends ResourceBase {
  /**
   *  A curent user instance.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
    * @param array $configuration
    *   A configuration array containing information about the plugin instance.
    * @param string $plugin_id
    *   The plugin_id for the plugin instance.
    * @param mixed $plugin_definition
    *   The plugin implementation definition.
    * @param array $serializer_formats
    *   The available serialization formats.
    * @param \Psr\Log\LoggerInterface $logger
    *   A logger instance.
    * @param \Drupal\Core\Session\AccountProxyInterface $current_user
    *   A current user instance.
  */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    array $serializer_formats,
    LoggerInterface $logger,
    AccountProxyInterface $current_user) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);

    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('rest'),
      $container->get('current_user')
    );
  }

  /**
    * Responds to GET requests.
    *
    * Returns a list of video nodes to be imported into the target site.
    *
    * @return \Drupal\rest\ResourceResponse
    *   The response containing a list of bundle names.
    *
    * @throws \Symfony\Component\HttpKernel\Exception\HttpException
 */
  public function get($site = NULL) {
    $response = ['message' => 'Hello, this is a rest service'];
    return new ResourceResponse($response);
  }
}

```

However, I'm having multiple problems trying to use this code:

First, my IDE (PHPStorm) is not recognizing the `namespace` keyword. In addition, in my the `rest` dir in that path is highlighted in red, and it shows an error message on the `resource` keyword that says

> Undefined constant resource: declaration of referenced constant is not found in built-in library and project files.

I've verified that I have the RESTful Web Services module enabled.

Also, I have the REST UI module enabled, and it lists my resource, but when I try to enable it, it tells me `undefined namespace Drupal\video_export\Plugin\rest\resource'`, which I'm sure is because of the other errors.

I've looked this over and over and can't see what's wrong

# Answer
As indicated by the comment by @ssibal, I just had to remove the line and then manually add it back in. The second time it took fine, and my resource works now.
> 0 votes

---
Tags: 8
---


# Question
Title: How to get 3 fields from 3 different tables in the database
I need to pull LATITUDE from the latitude table, LONGITUDE from the longitude table. I also want to pull the TITLE from the standard node\_field\_data table where the NID matches the entity\_id from either the longitude or latitude table. I should also mention that this is Drupal 8, so it's not easy to find this info on any forums yet. I didn't use the usual db\_query, because it's deprecated.

The below is what I have so far, but I cannot figure out how to get the LATITUDE and LONGITUDE based on the NID of the Title.

I have to get three fields from three different tables in the database. TABLENAME FIELDNAME node\__field\_latitude field\_latitude\_value node\__field\_longitude field\_longitude\_value node\_field\_data title

This is the query I have now

```
  $db = \Drupal::database();
  $query1= $db
    ->select('node__field_latitude','t')
    ->fields('t',array('field_latitude_value'));
  $query2= $db
    ->select('node__field_longitude','b')
    ->fields('b',array('field_longitude_value'));
  $titles= $db
    ->select('node_field_data','c')
    ->fields('c',array('title'));

  $query1->union($query2, 'UNION ALL');
  $query1->join('node_field_data','alias','alias.nid = t.entity_id');

  $query1->union($titles, 'UNION ALL');

```

It works, but it gets all titles in the node\_field\_data table. There are only three that I need and the nid matches the entity\_id in either the latitude table or the longitude table.

How can I fix this query to pull only the titles associate with the latitudes and longitudes I am pulling?

BONUS,

For some reason when I try to var\_dump the results to an array, the array is creating two empty values. See my loop and the corresponding var\_dump

```
  $result=$query1->execute();
  $test = array();
  if ($result) {
    while ($row = $result->fetchAssoc()) {
      $test[] = $row['field_latitude_value'];
      $test[] = $row['field_longitude_value'];
      $test[] = $row['title'];
    }
  }

array(45) {
  [0]=>
  string(17) "32.79690170288086"
  [1]=>
  NULL
  [2]=>
  NULL
  [3]=>
  string(16) "32.7942008972168"
  [4]=>
  NULL
  [5]=>
  NULL
  [6]=>
  string(18) "32.711700439453125"
  [7]=>
  NULL
  [8]=>
  NULL
  [9]=>
  string(19) "-117.25499725341797"
  [10]=>
  NULL
  [11]=>
  NULL
  [12]=>
  string(19) "-117.25599670410156"
  [13]=>
  NULL
  [14]=>
  NULL
  [15]=>
  string(19) "-117.15699768066406"
  [16]=>
  NULL
  [17]=>
  NULL
  [18]=>
  string(27) "2$ off beers, kids eat free"
  [19]=>
  NULL
  [20]=>
  NULL
  [21]=>
  string(12) "Taco Tuesday"
  [22]=>
  NULL
  [23]=>
  NULL
  [24]=>
  string(16) "House Wine Night"
  [25]=>
  NULL
  [26]=>
  NULL
  [27]=>
  string(12) "Taco Tuesday"
  [28]=>
  NULL
  [29]=>
  NULL
  [30]=>
  string(24) "Backyard Kitchen and Tap"
  [31]=>
  NULL
  [32]=>
  NULL
  [33]=>
  string(23) "Pacific Beach Shoreclub"
  [34]=>
  NULL
  [35]=>
  NULL
  [36]=>
  string(13) "Knotty Barrel"
  [37]=>
  NULL
  [38]=>
  NULL
  [39]=>
  string(13) "Deals Near Me"
  [40]=>
  NULL
  [41]=>
  NULL
  [42]=>
  string(16) "Craft beer night"
  [43]=>
  NULL
  [44]=>
  NULL
}

```

EDIT: Jaypan helped me figure this out, here is the final code:

```
$result = \Drupal::database()->query('SELECT node.title, latitude.field_latitude_value, longitude.field_longitude_value '.
  'FROM {node_field_data} AS node '.
  'JOIN {node__field_latitude} AS latitude '.
  'ON latitude.entity_id = node.nid '.
  'JOIN {node__field_longitude} AS longitude '.
  'ON longitude.entity_id = node.nid '.
  'JOIN {node__field_postal_code} AS zipcode '.
  'ON zipcode.entity_id = node.nid '.
  'WHERE zipcode.field_postal_code_value = '.$postal_code);

```

# Answer
If I understand you correctly, you want:

```
$data = \Drupal::database()->query(
  'SELECT node.title, latitude.field_latitude_value, longitude.field_longitude_value ' .
  'FROM {node_field_data} AS node ' .
  'JOIN {node__field_latitude} AS latitude ' .
  'ON latitude.entity_id = node.id ' .
  'JOIN {node__field_longitude} AS longitude ' .
  'ON longitude.entity_id = node.id ' .
  'WHERE node.nid = :nid',
  [':nid' => $nid]
)->fetchAssoc();

```

Set $nid to the node ID you want, and you should be good.
> 0 votes

---
Tags: database
---


# Question
Title: Theme Upgrade for an existing D7 site - block and config management
Working on developing a new Bootstrap theme for an existing D7 site. **How can I make sure that the blocks are assigned to specific regions when the new theme is installed.**

Because I would be working in Dev where the theme config would be stored.(cannot update the prod db from dev).

Would really appreciate your inputs.

Thanks!

# Answer
You need to ensure that your new theme has the same regions defined in the info file as the current theme, otherwise the blocks will lose their assignment when the new theme is installed. The blocks are assigned in the database and they will stay assigned to those regions, as long as those regions are available.
> 0 votes

---
Tags: 7, theming, blocks
---


title: hook_preprocess and theme_preprocess

text:
# Question
Title: hook_preprocess and theme_preprocess
I need to `preprocess_comment`.

I did :

```
theme_preprocess_comment($vars) {
 ...
 dsm($vars['content']['links']['comment']['#links']['comment-edit']['href']);
}

```

But I need to do this in a custom module to override links depending about this module's configuration so I did :

```
mymodule_preprocess_comment($vars) {
 $vars['content']['links']['comment']['#links']['comment-edit']['href'] = '/com';
}

```

Problem :

* `dsm()` returns `'/com'` but front is still
    + `<a href="/comment/26/edit"></a>` instead of `<a href="/com"></a>`

# Answer
> 2 votes
You need to pass by reference to modify the variable value:

```
function mymodule_preprocess_comment(&$vars) {
 $vars['content']['links']['comment']['#links']['comment-edit']['href'] = '/com';
}

```

Note the `&` before `$vars`.

---
Tags: theming, comments
---


title: Immediately delete managed files

text:
# Question
Title: Immediately delete managed files
I have a use case (in D8) where file and corresponding directory needs to be deleted from the file system. The standard mechanism suggested by Drupal is to mark file as temporary and let cron take care of deletion. This means, in my case, that I need to keep track of the file deletion and only then delete the corresponding directory, if it empty. This can be easily avoided by simply using `file_delete()`.

Why is this method not recommended?

The standard cron based deferred deletion causes other side effects with file replacement, etc.

# Answer
> 1 votes
> Why is this method not recommended?

The function comments do give a nod to the reason:

> Instead of directly deleting a file, it is strongly recommended to delete file usages instead. That will automatically mark the file as temporary and remove it during cleanup.

But perhaps the "file usage" part of that could have been expanded upon, if you're not aware there's proper reference tracking going on it could be confusing...

Put simply, multiple entities/things can reference a single file. Those references are stored as file usage records, which are consulted when the system wants to know if it's safe to delete a file. If a record exists, for the target file, it can't be deleted without breaking a link, so the system doesn't do it.

Rather than go through that process of checking usage then deleting every time a file is dereferenced, the system batches it up on a cron job for convenience.

If it's not convenient for your use case, and you are comfortable that the file delete is 'safe' with the above in mind, then you can happily ignore the recommendation and use `file_delete` directly.

If you do, make sure you clear up the file usage records at the same time, or you might end up with inconsistent data some time down the line.

---
Tags: files
---


# Question
Title: Mass-adding user fields using Bulk Creator
I am new to open atrium and Drupal and I am building a new site to manage volunteers. I have about 200 fields to add to my users' profiles (So new fields below password, picture, display name, etc...)

Doing this from the `Administration » Configuration » People » Account parameters` panel will be a cumbersome process so I want to avoid it and instead use a script to create all my fields. This is the best approach because all those fields are very similar, they are there to store multiple integer values for all days within 5 weeks (Notably catering information : number of meals for morning/noon/evening)

After a few researches, I found this module which seems to do exactly what I want : Bulk Creator

The issue is that I don't really understand how I can specify that the fields I want to add are related to user profile. The only way I can think off is to specify it in the *content\_type* parameter, however I can't find any content type related to users in the configuration.

Any other solution to batch create my hundreds of user fields is welcome. I've thrown an eye to the DB tables in order to do it using SQL instructions, but I quickly understood that it was not a good idea :)

# Answer
> 2 votes
Rather than creating 200 fields on one entity (this will definitely slow down Drupal), you could group the repeating fields using field collections.

Since you mention there are several fields per day, I'd combine all similar fields into a collection.

So start of with the user and add a field collection field which you name 'weeks' or something and configure it to take 5 values (one for each week).

Now edit the newly created field collection (admin \> structure \> field collections) and add a new field collection which you name 'days'. This field can contain 7 values.

Again, edit the created field collection and add all fields you need for one day. So one field for the room, one for the amount of breakfasts, etc.

You now have a structure like this:

```
User
  - 5 week field collection
    - 7 days field collection
      - room
      - # of breakfasts
      - ...

```

This is structure you can create by hand it would be about 10 fields.

Reading and printing the data can be easy done with views, but there are quite some tutorials out there already. If you can't figure it out, feel free to ask a new question.

---
Tags: users, distributions
---


# Question
Title: Need help changing out theme based picture on front page, can only be done through host site, not admin panel
I have been taking care of the basic updates on a website for an old friend. I can do everything through the admin panel except update the main picture on the front page. You can see it at www.foxviewfarms.com. It is running Drupal 7.0. I do know this can only be done through the host site, but I am just a rookie self taught person...I have never done anything like this.

I do understand I should backup before any changes.

So from the host, I found two places that the home image resides. The first pic here shows my folders. I went into the public one:

Now I pointed to the two places I found the image and I circled its file name. It would seem to me that I would upload a new picture to each folder, then delete the old picture that resides in the sites/all/foxview/images folder (while keeping it in the themes/foxview/images in case I want to use it again). The themes/foxview/images folder has the current image and past images, while the sites/all/foxview/images folder has just the new image.

Am I looking at this right? Is there anything else I would need to change to update this picture? Any help is greatly appreciated.

# Answer
> 0 votes
I would guess that the current image is hardcoded into the template. Best would be create a content type, add an image field, (upload new image), and set that new node page as the home page in the system site settings.

# Answer
> 0 votes
Solved! I found the image coding in the page.tpl.php file within content/sites/all/themes/foxview. Looking within this finally showed me the coding used to change the homepage picture. It is referencing the files in themes/foxview/images. I switched it to an old picture and then back as a test and it worked.

---
Tags: theming, media
---


# Question
Title: What happens when two files with the same name are uploaded?
On Monday, I upload dogs.png as my profile picture on my Drupal site.

On Tuesday, I change the image to something else (but keep the name "dogs.png") and upload it as my associate's profile picture.

What will Drupal do to resolve this conflict?

# Answer
> 12 votes
It will rename the second file for you. If dogs.png exists, Drupal will try dogs\_0.png, dogs\_1.png and so on, until it finds an unused filename.

The behaviour comes from the `$replace` parameter to `file_save_data()`, which can be one of the following:

* FILE\_EXISTS\_REPLACE \- Replace the existing file. If a managed file with the destination name exists then its database entry will be updated. If no database entry is found then a new one will be created.
* FILE\_EXISTS\_RENAME \- Append \_{incrementing number} until the filename is unique.
* FILE\_EXISTS\_ERROR \- Do nothing and return FALSE.

The default is `FILE_EXISTS_RENAME`, which is used for managed file form elements like the user profile picture, and file field widgets too.

---
Tags: media
---


# Question
Title: How can I use regex in a migration query condition?
I have data in a table that looks like this:

```
|-------------------------------------------------------|
|ID|              Data                                  |
|--|----------------------------------------------------|
| 1|{"key":"value",...,"image":"1234567",..."key:value"}|
| 2|{"key":"value",...,"image":"",..."key:value"}       |
| 3|{"key":"value",...,"image":"9876543",..."key:value"}|

```

In my migration I only want to import items that have an image ID in the Data column.

Previously I was doing this in my migration class query() method:

```
class myMigration extends SqlBase {

  public function query() {
    return $this->select('data_table', 'd')
      ->distinct()
      ->fields('d', ['ID', 'Data'])
      ->condition('Data', '%' . db_like('"image":') . '%', 'LIKE');
  }

  public function fields() {

    $fields = [
      'ID' => t('ID'),
    ];

    return $fields;
  }

  public function getIds() {
    return [
      'ID' => [
        'type' => 'string',
      ],
    ];
  }

```

This was also selecting rows where the image value was empty in the Data column.

This query in SQL works for selecting the correct data, but I cannot get it to work with the query() method in my migration:

```
SELECT ID, Data
FROM data_table
WHERE Data REGEXP '"image":"\d*[^>"]';

```

# Answer
I was able to use `REGEXP` operator in a normal `condition()` method, although it is not stated in the documentation.

The answer was found on this example.

Solution:

```
  public function query() {
    return $this->select('data_table', 'd')
      ->distinct()
      ->fields('d', ['ID', 'Data'])
      ->condition('Data', '"image":"\d*[^>"]', 'REGEXP');
  }

```
> 3 votes

# Answer
You should be able to use the `where()` method:

```
return $this->select('data_table', 'd')
    ->distinct()
    ->fields('d', ['ID', 'Data'])
    ->where('Data REGEXP \'"image":"\d*[^>"]\'');

```
> 2 votes

# Answer
Don't use SqlBase Class and do yourself the query. Your Class can extends SourcePluginBase.

```
  use Drupal\Core\Database\Database;

  $database = Database::getConnection('default', $your_database_key_in_settings_php);
  $query = $database->query($sql_query);
  $data = $query->fetchAll(\PDO::FETCH_ASSOC);

```
> 0 votes

---
Tags: 8, database, migrations
---


title: Need to run cron as authenticated user

text:
# Question
Title: Need to run cron as authenticated user
Hi on my server I need to be running cron as an authenticated user in order for the directories that I need to access during a specific function to be writable. How can I make cron or at least part of this cron run be run as an authenticated user for drupal 8. I found some documentation but only for drupal 7 . thanks

# Answer
You can run your custom cron methods as an authenticated user as follows:

```
use Drupal\user\Entity\User;

/**
 * Implements hook_cron().
 */
function my_module_cron() {
  // Login as user 1
  $user = User::load(1);
  user_login_finalize($user);

  // Your custom cron functions

  // Login as user 0 (anonymous)
  $user = User::load(0);
  user_login_finalize($user);
}

```
> 2 votes

---
Tags: cron
---


# Question
Title: How can we add a date picker in a date field exposed filter?
In Drupal 8 am trying to add date pickup popup calendar in our custom search form. Search Page is created by Views page and adding DOB field by the date field expose.

But there is no option to add date popup calendar in views. While date pop up calendar is showing in the "Add Content" page in admin area.

Any idea how can we show datepicker calendar on date field?

# Answer
Try the contrib module Better Exposed Filters. At the 'Exposed form' settings in your view you can select 'Better Exposed Filters' after enabling BEF. After selecting the exposed form method you should have more options per field, a datepicker is one of them (on date fields).
> 2 votes

# Answer
This is a discussion in Use form element of type date instead textfield when selecting a date in an exposed filter.

> **Problem/Motivation**
>
> When adding a datetime exposed filter I cannot simply select a date - I have to manually enter a date which is very bad UX.

I have installed the patch #71 with Drupal 8.2.6 and it works.
> 1 votes

---
Tags: views, datetime
---


# Question
Title: How to highlight new added links on front page with cookies?
My front page contains say 3 different views and each view has 10 rows. My requirement is Links which were not published to the frontpage the last time the user loaded it should be highlighted. I am using common template file for field shown on front page. (that is title file with anchor tag having link to some URL) Example in image :

I am having no idea how I can achieve this, I tried searching lot but I have idea that this can be possible with cookies.

Please suggest that will be very helpful !!

Thanks :)

**UPDATE :**

I have set nid values in cookie with below logic :

```
function custom_views_pre_render(&$view) {

  //frontpage highlight

  if (current_path() == "frontpage") {
    if (!empty($view->result)) {
      $nids = array();
      foreach ($view->result as $res) {
        $nids[] = $res->nid;
      }
      if(!isset($_COOKIE['FrontPage'])) {
        setcookie("FrontPage[$view->name]", implode(',', $nids), time() + (3600 * 24 * 5), '/');
      }
    }
}

```

Now I need to compare values of each row nid with in this array.

# Answer
> 2 votes
You could do this in a limited way where you store each item's nid and updated date in a cookie. The cookie would get updated each time the user loads the front page by JavaScript that reads the nid and date from the DOM.

Before the cookie is updated it is used to set a highlight class on any items that aren't set in the cookie.

In order for the cookie to not grow too large the items could be pruned by date if the front page only shows most recent.

For an demo take a look at https://jsfiddle.net/rnc2eLxr/2/

I've included the code below.

JS libraries:

HTML:

```
<body>
  <div class="view">
    <ul>
      <li class="link"><a href="http://google.com" data-nid="1" data-date="2017-01-01">Google</a></li>
      <li class="link"><a href="http://reddit.com" data-nid="2" data-date="2017-01-02">Reddit</a></li>
    </ul>
  </div>
</body>

```

Javascript:

```
// Get cookie value.
var linksString = $.cookie('frontLinks'),
  links = [];
if (linksString != undefined) {
  links = JSON.parse(linksString);
}

// Highlight any links not found in cookie.
$('li a').each(function(i, v) {
  var $link = $(v),
    tuple = {
      "date": $link.data('date'),
      "nid": $link.data('nid'),
    },
    match = findByNid(links, tuple.nid, true);
  if (!match) {
    $link.addClass('highlight');
    links.push(tuple)
  }
});

// Find array object by nid property.
function findByNid(inArr, nid, exists) {
  for (i = 0; i < inArr.length; i++) {
    if (inArr[i].nid == nid) {
      return (exists === true) ? true : inArr[i];
    }
  }
}

// Store links in cookie.
$.cookie('frontLinks', JSON.stringify(links))

```

CSS:

```
li a.highlight {
  border: red 1px solid;
}

```

---
Tags: views, theming, cookies
---


# Question
Title: How to display comment form and comments per node in a view
I am trying to display comments + comment form per node in a view of nodes following this answer. So I'm trying full content display with row style options, which works perfectly on another site I am working on, but on this one, I don't have the "Display comments" toggle box

So I have reinstall the site and disable every thing I could : contrib modules / themes and templates / custom code / libraries / fields & comment fields / all content types trying with new ones / uninstall & reinstall comment modules / combination of permissions for all/just admin in view-post-skip options. Still nothing.

Anyone has seen this before?

# Answer
Check if you've comment module installed, if yes, also check if you've comments enabled for that content type
> 0 votes

---
Tags: 7, views, comments
---


# Question
Title: Limit entity reference field formatter to certain entity types
I've created an entity reference field formatter. It works fine. However, the field formatter will only work properly on entities of type user, so if the referenced entity type is different, I don't want the formatter to appear in the list of options.

I tried adding `entity_types = { user }` to my annotation for the formatter, but this didn't work. I'm suspecting it cannot even be done, but I thought I'd ask here before opening up an issue in core, to suggest it for future development.

Does anyone know if this can be done, and if it can, how?

# Answer
> 9 votes
I think this will work...

There is an isApplicable() method in Drupal\Core\Field\FormatterBase. You can implement it in your FieldFormatter class like this:

```
public static function isApplicable(FieldDefinitionInterface $field_definition) {
  return ($field_definition->getFieldStorageDefinition()->getSetting('target_type') == 'user');
}

```

---
Tags: 8, entities
---


title: Module can't update after updating core

text:
# Question
Title: Module can't update after updating core
I updated my Drupal 8 website from 8.2 to 8.3. I have a module that has a block and includes a configuration form which has various data form fields. The block of the module appears to work fine. But when I try to update any of the configuration data it simply doesn't change anything! Something to do with not updating the database, maybe?

Example: I want to change the modules block name. The old name is "oldname" and I want it to be "newname". After typing in the new name on the configuration page and clicking save the name will still remain "oldname".

There is not a single error within Drupal or my servers log file that would explain this. Is there anywhere else I can look to find what the problem is?

What's changed with the new version of Drupal that might cause this?

After searching for awhile and cleaning out some old modules from the database I've finally come across an error relating to forms. It' quite long but here's the first part: Warning: strip\_tags() expects parameter 1 to be string, array given in Drupal\favorites\Form\AddForm-\>buildForm()

# Answer
Use drush config-edit, as stated in the docs.

Or implement an upgrade path for you module, see hook\_update\_N.
> 0 votes

---
Tags: updating
---


# Question
Title: Generate unique ID in hook_redirect_form
I'm trying to write custom payment method for a custom bank gateway (off-site method). bank service expect me to send unique ID for each pay request per `bpPayRequest()` call.

currently I sending `$order->order_id`, but its wrong because: if first request fails this `orderId` is not unique for second `bpPayRequest()` call. so I should create unique ID which is related to $orders. Is there any commerce way for this question?

```
$parameters = array(
  ...
  'orderId' => $order->order_id,
  ...
);
$result = $client->call('bpPayRequest', $parameters, $namespace);

```

# Answer
```
$unique_id = $order->order_id . '-' . microtime();

```

The advantage of this is you can explode on the - later and get the order id back again.
> 0 votes

---
Tags: 7, commerce
---