title: Change account settings in db

text:
# Question
Title: Change account settings in db
All sites on our server is currently getting spam users registering for new accounts.

Since none of the sites needs the option available for user to sign up, we would like to change the account setting "Who can register accounts?" being "Administrators only" for all sites.

The issue is we have around 800 sites, and i would rather not do this manually for all sites.

Is it possible to change this setting directly through the database?

Like one sql command that update alle databases and set the setting to being "Administrators only"?

# Answer
> 1 votes
You want to modify a **user\_register** variable and set it to **0**. You can set it in code:

```
variable_set('user_register', USER_REGISTER_ADMINISTRATORS_ONLY);

```

by drush:

```
drush vset user_register 0

```

or directly in database (note that in variable table are stored serialized values):

```
UPDATE variable SET value = 's:1:"0";' WHERE name = 'user_register';

```

but this requires cleaning cache.

```
DELETE FROM cache_bootstrap WHERE cid = 'variables';

```

# Answer
> 1 votes
## For Drupal 8

## Code:

```
$config_factory = \Drupal::configFactory();
$config = $config_factory->getEditable('user.settings');
$config->set('register', 'admin_only');
$config->save(TRUE);

```

## Drush:

`drush cset user.settings register admin_only`

## Database query:

Straight database query is tricky, because config is serialized in the database.

It'll be in the form of:

```
collection: ''
name: user.settings
data: a:X:{ ... s:8:"register";s:8:"visitors"; ...}

```

You need to grab the current config for `user.settings`, unserialize it, amend the `register` part of this config, re-serialize it, and then run an UPDATE query. At this point, it's probably easier to just use Drupal's API (see Code section above).

---
Tags: database
---


# Question
Title: How to programmatically set a Views display to override style options
I am working on the Charts module and have a stubborn issue that I'm trying to resolve.

Charts provides a Views style plugin and a Views display plugin called Chart Attachment. The display plugin extends the Attachment display plugin and sets the View's format to Charts. However, I run into an issue where I really need the Chart Attachment's formatting settings to apply to its display only ("This chart\_extension (override)"). If it applies to all displays, it ends up breaking the Chart because the whole idea behind the Chart Attachment is for it to be different than its parent.

Here is what the Format settings should look like immediately after clicking "Add" -\> "Chart attachment" in the View displays section:

Note the italic font on Chart and Settings within the Format section.

When you click on Chart from that attachment, this is what you should see without clicking anything else:

So how can one code the Display plugin to enforce style format options to "This chart\_extension (override)"?

Or, if there is another approach that accomplishes the same thing, I would be open to that.

# Answer
> 3 votes
This is how you can achieve that:

```
diff --git a/src/Plugin/views/display/ChartsPluginDisplayChart.php b/src/Plugin/views/display/ChartsPluginDisplayChart.php
index 3dbad31..68048ce 100644
--- a/src/Plugin/views/display/ChartsPluginDisplayChart.php
+++ b/src/Plugin/views/display/ChartsPluginDisplayChart.php
@@ -29,6 +29,10 @@ class ChartsPluginDisplayChart extends Attachment {
     $options['style_plugin']['default'] = 'chart';
     $options['inherit_yaxis'] = ['default' => '1'];

+    // Set the default style plugin to 'chart'.
+    $options['style']['contains']['type']['default'] = 'chart';
+    $options['defaults']['default']['style'] = FALSE;
+
     return $options;
   }

```

API docs: https://api.drupal.org/api/drupal/core%21modules%21views%21src%21Plugin%21views%21display%21DisplayPluginBase.php/function/DisplayPluginBase%3A%3AdefineOptions/8.2.x

---
Tags: views, 8, charts
---


# Question
Title: How to read-modify-write a multivalue entity-reference field
I have some D8 entity code that does read-modify-write on a multivalue entity-reference field. The modification required is to change references to one entity to refer to another, without changing other references.

I get an exception thrown in `$entity->set(...)` saying that the *Value is not an entity*. I presume I'm calling the wrong thin somewhere but I don't see what the correct call pattern would be.

What I have at present is, and here $field\_values is a EntityReferenceFieldItemList:

```
  $field = '...';
  $entity = $storage->load(...);

  $field_values = $entity->{$field};
  foreach ($field_values as $k => &$item) {
    $target_id = $item->get('target_id')->getValue();
    if ($target_id === $old_value->id()) {
      $changed = TRUE;
      $item->set('target_id', $new_value);
    }
  }
  if ($changed) {
    var_dump($field_values);
    $entity->set($field, $field_values);
    $entity->save();
  }

```

where $old\_value and $new\_value are both EntityInterface objects and $field\_values is an EntityReferenceFieldItemList.

# Answer
```
  foreach (entity->get($field) as $k => $item) {
    $target_id = $item->target_id;
    if ($target_id == $old_value->id()) {
      $changed = TRUE;
      $item->target_id = $new_value;
    }
  }

  if ($changed) {
    $entity->save();
  }

```

That's it. You don't need to set any values, they are objects, your loop already updates them. You also don't need to loop over it by reference.

I just simplified it a bit because you can access target\_id as a property through \__set() and \__get(), which has the advantage that you directly get the value and don't need to call getValue() on it.

See https://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet for more information for example.
> 1 votes

---
Tags: 8, entities
---


# Question
Title: Limit Change to Read More Link in Node Teaser to One Content Type
Building on this answer:

```
/**
 * Implements hook_preprocess_links().
 */
function bartik_preprocess_links(&$variables) {
    if (isset($variables['links']['node-readmore'])) {
      $variables['links']['node-readmore']['link']['#title'] = t('Read more custom text');
    }
}

```

does anyone know how to build the if statement to further limit the change in the read more link to a particular content type? I'm working in Drupal 8, not 7.

# Answer
> 2 votes
Add following to your THEMENAME.theme file

```
/**
 * Implements hook_preprocess_HOOK() for node.html.twig.
 */
function THEMENAME_preprocess_node(&$variables) {
    // ...
    if ($variables['teaser']) {
    $node_type = &drupal_static('node_type');
    $node_type = $variables['node']->getType();
  }
}

/**
 * Implements hook_preprocess_links().
 */
function THEMENAME_preprocess_links(&$variables) {
  $node_type = &drupal_static('node_type');
    if (isset($variables['links']['node-readmore'])) {
        // Change link title according to machine name of node_type
        if ($node_type == 'article') {
            $variables['links']['node-readmore']['link']['#title'] = t('Custom Text');
        }
    }
}

```

Clear Cache.

# Answer
> 0 votes
I was able to make this work by getting the bundle from the URL object that's part of the link:

```
function THEMENAME_preprocess_links(&$variables) {
  if (isset($variables['links']) && (isset($variables['links']['node-readmore'])) && (isset($variables['links']['node-readmore']['link'])) && (isset($variables['links']['node-readmore']['link']['#url']))) {
    if ($entity = $variables['links']['node-readmore']['link']['#url']->getOption('entity')) {
      if (($bundle = $entity->bundle()) && ($bundle == 'article')) $variables['links']['node-readmore']['link']['#title'] = t('Read the article');
    }
  }
}

```

---
Tags: theming, 8
---


# Question
Title: How to pass/link the node id of the result of a view (say, content type A) to another view of content type B, which are referenced in content type A?
I have three content types: Newspaper, Headlines, and Local. All entities have standard Title/Body fields. Newspaper has two additional multiple value fields named Headlines and Local that are referencing the respective content types.

I ultimately would like two very similar RSS views (one for Headlines and one for Local) that would show respective nodes that are linked from a Newspaper content. I am able to do this using Views Relationships. The problem is how to display only referenced nodes that are linked from the latest Newspaper content type.

I also contemplated on the possibility of first creating a separate view that displays the latest Newspaper, but I can't figure out how to pass it to another view, if it's even possible.

Here's some concrete information: Say for example, I have the following content

**Newspaper**

* June 19, 2018
* June 18, 2018

**Headlines**

* Blah
* Bleh
* Meh

**Local**

* Something Happened
* Nothing Happened
* Nothing Happened again

Here's a visual on what I'm trying to get.

The whole reason for this is that I'm working with a newsletter application whose templates can take in several feeds. The particular template has a different style per section. I was planning to pull in a separate feed per section so the section can be styled independently. Even though the would-be feeds are separate, I need them to be in sync with one another and make sure they're pulling from the same Newspaper content.

# Answer
You can do this with the help of the Views Field View module by embedding one View display into another.

In your case you want to have one View showing only the one latest Newspaper, and the other helper Views Display listing Headlines referring to the latest Newspaper that will be embedded into the first Display.

Here are the steps how to do it:

1. Create a Newspaper View
2. Add Sort criteria "Authored on" (Descending)
3. Use pager: Display a specified number of items | 1 item

You should now have only your latest Newspaper node listed as a result. You don't need any Relationships or Contextual filters here.
4. Add a new field `Content: ID`, Exclude it from display and Rearrange fields so this one is on top
5. Create a new Views Display of type **Embed** in the same Views
6. Keep the filters (Newspaper) but override the Pager to show all items
7. Add a new Field `Content: Headline` and under **Multiple field settings** make sure you're NOT using `Display all values in the same row`, it should not be ticked
8. Add a new Contextual filter `Content: ID` for this display only and configure it:
When the filter value is NOT available
**Provide default value**
**Content ID from URL**

Now if you enter the node ID of the latest Newspaper node into the View Preview argument field you should see a list of Headlines referencing that node.
9. Save the View (Important! The next step won't work without it)
10. Edit the original View Display (from step 1 above) and add a new Field `Global: View` (Embed a view as a field.)
11. Under `View settings` for this field select the View you're currently editing. You may need to Save the View again at this point.
12. Then under `Display` option under it choose **Embed** and fill in the **Contextual filters** fields with the node ID token from the Replacement patterns below it. It will probably be something like `{{ raw_fields.nid }}`

You should now have a list of the latest Newspaper node with Headlines referring it also listed.

Even though the View is set to display Newspaper nodes, through the Entity reference field and an ID contextual filter you only see Headlines listed.

Descendant sorting and pager limited to one is making sure it's related only to the latest Newspaper.

Using a different View display to show Headline nodes enabled us to list them one Headline per view row. If we did that in the original Display we'd had to list them all on the same row, because if we didn't we might not get all the Headlines listed because of Pager limit. And Headline count per Newspaper probably varies so we can't predict anyway.

In the end Views Field View enabled us to embed one view into another one and pass argument to it.

Now repeat all the steps for the Local content type (clone and edit).

Your original Views Display will probably be Feed, but it would have been too complicated to include it in this explanation.
> 0 votes

---
Tags: views, nodes, entities
---


# Question
Title: Is there a way to park a domain name to a single Drupal node?
Is it possible to set up a Drupal website so that other domain names can go to specific nodes but show the domain name instead of the natural URL in the address bar? Can I use the Domain module, or some other method, so that example2.com goes to example.com/page2 but still shows example2.com in the address bar?

Any internal links still go to example.com/whatever, and that's fine. The page is designed as a one page unbranded website.

I already have the domain (example2.com) pointed to our servers (example.com) and have some familiarity with setting up vhosts in apache if needed as part of the Domain module set up. I'm not sure if I'm understanding what this module does and if it will do this job. I've also posted on Server Fault but am not getting anywhere because I think I'm not asking the question properly.

Drupal 7.59. Debian and Apache

# Answer
I was able to set different domain-based landing pages for existing nodes of our main site using the Domain module. This module is fairly complex and will either be exactly what you need, or not.

Our use case is that we have multiple one-page partner projects, such as campaigns, that need their own domain name but that share content from our regular website, such as our blogs.

The following are the steps taken for Drupal 7.

Be sure to read the entire readme file, the quick install and the install instructions before starting. There are many variables specific to your use case and environment.

**Step 1**

In order to use it, you will need to be able to configure the domains on the server to reference the primary website's docroot. In my case, that means I needed to point the domains over to the same server, and set up different vhost files as follows:

```
<VirtualHost *:80>
        DocumentRoot "/var/www/html/example/docroot"
        ServerName example2.com
</VirtualHost>

```

**Step 2**

You will then need to add some code to your `sites/default/settings.php`. Make sure the path is correct, according to your set up.

```
/**
 * Add the domain module setup routine.
 */
include DRUPAL_ROOT . '/sites/all/modules/contrib/domain/settings.inc';

```

**Step 3**

Once this is done, install the domain module and enable only the domain module, but none of the submodules yet. Then rebuild permissions (`/admin/reports/status/rebuild`). Then enable the `domain_conf` and`domain_settings` and any others. Once enabled, set your primary domain to default.

**Step 4**

Add your new domains by clicking on "Create domain"

**Step 5**

In order for the blog and other relative links to go back to the primary domain, I needed to set the following in advanced settings (Structure \> Domains \> Settings):

(Here, FosterClub is my primary domain).

After this, there are other sub-modules you can enable to further customize what you need to accomplish. Be sure to set your permissions. You are also able to assign domain access to specific roles and users, which allows them to edit and create content restricted to specific domains, using the "edit domain content" permission, with the `domain_content` sub-module:  This is a screenshot of settings under a specific user.
> 1 votes

---
Tags: 7
---


# Question
Title: User roles and permission for 1 can publish and 1 can't
I have 2 user roles which I created

```
1] Article Creator  -> Can Create/Update/Delete
2] Article Publisher -> Can Create/Update/Delete/Publish

```

Article Creator can create content, but can't publish. While Article publisher can do that.

Can we manage it without any module or any custom coding?

Can manage from default Drupal Admin?

# Answer
You are looking for Workflows and Content moderation. Those are features available out-of-box in Drupal 8 (stable form 8.4)
> 1 votes

---
Tags: 8, users
---


title: IP address to trusted_host_patterns

text:
# Question
Title: IP address to trusted_host_patterns
I tried to add IP address to for example : 172.20.0.3 I get this error : The provided host name is not valid for this server.

Here my settings

```
$settings['trusted_host_patterns'] = array(
  '^172\.20.\0.\3$',
  '^localhost$',
);

```

# Answer
Your regex is incorrect. You placed the second and third `\` after the `.` instead of before.

```
$settings['trusted_host_patterns'] = array(
  '^172\.20\.0\.3$',
  '^localhost$',
);

```
> 4 votes

---
Tags: 7
---


# Question
Title: How to create a simple Drupal module that updates a custom node field
I have a custom node type "**product**" which has a custom Decimal type field "**field\_price**".

I would like to create a simple module in Drupal 8 to set this value to 10.75 every time I **create or update** a node.

**edit**

I have now restructured the module as follows. These are the files / folder structure I have (excluding the .info.yml) :

Module folder: **/modules/updateprices**

Routing.yml: **/modules/updateprices/update\_prices.routing.yml**

```
Routing.yml code:
update_prices:
    path: /updateprices
    defaults:
        _controller: 'Drupal\updateprices\Controller\UpdatePricesController::update_prices_node_presave'
    requirements:
        _permission: 'access content'

```

Controller code: **/modules/updateprices/src/Controller/UpdatePricesController.php**

```
<?php
namespace Drupal\updateprices\Controller;
use Drupal\Core\Entity\EntityInterface;

class UpdatePricesController  {
        function update_prices_node_presave(EntityInterface $entity) {

          $entity_type = 'node';
          $bundles = ['product'];

          $fld_price = 'field_price';
          if ($entity->getEntityTypeId() != $entity_type || !in_array($entity->bundle(), $bundles)) {
            return;
          }
             $entity->{$fld_price}->setValue(10.75);
        }
}

```

I am now getting an error:

> ReflectionException: Class Drupal\updateprices\Controller\UpdatePricesController does not exist in ReflectionMethod-\>\__construct() (line 123 of /home/website.com/core/lib/Drupal/Core/Entity/EntityResolverManager.php).

# Answer
Hooks, in a module, only work inside the .module file.

You don't need a controller nor a routing file here, these are used for creating pages.

/modules/updateprices/**updateprices.module**

```
<?php

use Drupal\Core\Entity\EntityInterface;

function update_prices_node_presave(EntityInterface $entity) {

  $entity_type = 'node';
  $bundles = ['product'];

  $fld_price = 'field_price';
  if ($entity->getEntityTypeId() != $entity_type || !in_array($entity->bundle(), $bundles)) {
    return;
  }
  $entity->{$fld_price}->setValue(10.75);

}

```
> 1 votes

---
Tags: 8, hooks
---


# Question
Title: Ajax callback called on textfield typing
I'm trying to reach exactly the same state as autocomplete field does. When user is typing in textfield I'd like ajax to wait with its callback so the user can write all the text.

I'm trying to achieve it with help of this question. But I'm failing. Maybe because I'm playing with JavaScript in drupal for the first time. Anyway here is my code.

form\_alter in .module (I have form generated with features)

```
if (empty($form['nid']['#value'])) {

    drupal_add_js(drupal_get_path('module','MY_MODULE') . 'my_script.js');

    $form['field_my_field']['und'][0]['value']['#ajax'] = array(
        'callback' => '_test_callback',
        'event' => 'finishedinput',
    );
}

```

my\_script.js (from the link above)

```
(function ($, Drupal) {
Drupal.behaviors.MY_MODULE = {
    attach: function (context, settings) {
      var typingTimer;
      var doneTypingInterval = 10;

  $('.andtimer').on('keyup', function (e) {
    clearTimeout(typingTimer);
    if ($(this).val) {
      var trigid = $(this);
      typingTimer = setTimeout(function(){
        trigid.triggerHandler('finishedinput');
      }, doneTypingInterval);
    }
  });
}
};
}(jQuery, Drupal));

```

And I have script attached to my .info file.

# Answer
here my solution:

first you've to create (or alter) a text field

```
$form['user_search'] = array(
  '#type' => 'textfield',
  '#title' => t('Search'),
  '#description' => t('Cool description'),
  '#ajax' => array(
    'callback' => 'MODULE_ajax_user_search',
    'wrapper' => 'user-search-replace',
    'event' => 'finished_input', // custom event called by js code
    'effect' => 'fade',
  ),
  '#attributes' => array(
    'class' => array(
      'delayed-search-submit' // custom class to attach behavior to
    ),
    'data-delay' => '300', // custom property to set submit delay
    //'data-event' => 'finished_input', // custom event name, default is "finished_input"
  ),
);

```

then you'll have to create some js code to attach to your form

```
(function($){
  $(function(){
    Drupal.behaviors.delayedSearchSubmit = {
      attach: function (context, settings) {
        $('input.delayed-search-submit').once('event', function (){
          var $self = $(this);
          var timeout = null;
          var delay = $self.data('delay');
          var triggerEvent = $self.data('event');
          if (!delay) {
            delay = 1000;
          }
          if (!triggerEvent) {
            triggerEvent = 'finished_input';
          }
          // Every time a keyup event is fired
          // timer is reset
          $self.bind('keyup', function(){
            clearTimeout(timeout);
            timeout = setTimeout(function(){
              $self.trigger(triggerEvent);
            }, delay);
          });
        });
      }
    }
  });
})(jQuery);

```

now attach js file to your form

```
drupal_add_js(drupal_get_path('module', 'MODULE') . '/js/MODULE.textsearch.js');

```
> 4 votes

# Answer
I could not get @Kladrian version to work on Drupal 8, so I have rewrote slightly. Maybe this will help other people.

PHP `buildForm`

```
$form['user_search'] = [
  '#type'       => 'textfield',
  '#title'      => $this->t('Search'),
  '#ajax'       => [
    'callback' => [$this, 'MODULE_ajax_user_search'],
    'event'    => 'end_typing', // custom event called by custom js
    'progress' => [
      'type'    => 'throbber',
      'message' => $this->t('Searching'),
    ],
  ],
  '#attributes' => [
    'class'      => [
      'delayed-input-submit' // custom class to attach behaviour to
    ],
    'data-delay' => '500', // the delay information
  ],
];

```

Javascript

```
(function ($, Drupal, undefined) {
  Drupal.behaviors.delayed_submit = {
    attach: function (context, settings) {
      $('input.delayed-input-submit').each(function () {
        var $self = $(this);
        var timeout = null;
        var delay = $self.data('delay') || 1000;
        var triggerEvent = $self.data('event') || "end_typing";

        $self.unbind('keyup').keyup(function () {
          clearTimeout(timeout);
          timeout = setTimeout(function () {
            $self.trigger(triggerEvent);
          }, delay);
        });
      });
    }
  }
})(jQuery, Drupal);

```
> 2 votes

---
Tags: forms, ajax, javascript
---


# Question
Title: add custom markup on a specific element/filter in a exposed filter (views)
I'm trying to learn how I can add or modify a markup for a specific filter on my exposed filter. I'm currently rendering the exposed filter using a block it has a lot of Drupal Generated Markup.

So far I've managed to identify the ID of the form, have been researching throughout the day for some examples but so far haven't had any progress

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

    print_r($form_id);
}

```

Let say for example I have to add a `label` with a `class` and a custom class on the `select` element and wrap it with a `div`. Is there a way to build or construct that modified markup?

# Answer
You can override the twig template responsible for that particular HTML output. You already see debug hints so you can see which template to check out.

Then copy that template to your subtheme and edit it there. Don't edit the core Drupal theme to avoid messing up your project maintainability.

Working With Twig Templates

You might be after select.html.twig and function template\_preprocess\_select.
> 1 votes

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


title: Create nodes out of Webform submissions

text:
# Question
Title: Create nodes out of Webform submissions
We are using Drupal 8 and trying to solve this problem: A form shall be presented to website visitors that asks them to submit questions (in our case: concerning nutrition) and give some structured background information like the region the user comes from etc.

The submitted information shall then be transformed into a node of a given content type to make it easier for the editorial staff to edit that question in the backend, add an answer to it and publish the whole thing.

The forms shall be used by anonymous users and we do not want to let them create nodes directly via /node/add - for security reasons on one hand and with regard to the complexity of the creation form which is not needed at that point on the other hand.

I have read this: How to create a node with submissions of a webform? but I am not sure whether that would be a solution to our task. It says: "Hide the toolbar for other users and give them permission to add new content. Lastly, adapt the node form to your needs with a template file and style it with CSS." Would I have to expose parts of the backend to anonymous users and give them the right to create new nodes? We would like to avoid that due to security concerns.

# Answer
> 0 votes
I did this previously on Drupal 7 and it might be possible to adapt the process I used:

Via `hook_form_alter` add an additional submission handler (i.e. `form['#submit'][] = '_webform_submit_handler';`)

Inside the submission handler function:

1. Create a new node (i.e. `$node = new stdClass();`)
2. Assign the relevant fields (i.e. `$node->title = 'Title';`, `$node->type = "type";`, etc.)
3. Save the node (i.e. `$node = node_submit($node);` and `node_save($node);`)

---
Tags: 8, webforms
---


# Question
Title: How do I programmatically change the user ID in a order?
I programmatically created a user using the following code.

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

/**
 * Helper function to create a new user.
 */
function create_new_user() {
  $user = User::create();
  $user->setPassword('<password>');
  $user->enforceIsNew();
  $user->setEmail('<email>');
  $user->setUsername('<username>');
  $user->save();
  drupal_set_message("User with uid " . $user->id() . " saved!\n");
}

```

Now I need to set the ID of the created user into an order.

I've loaded the order using the following code.

```
$ord_id = 10;
$order = \Drupal::entityTypeManager()->getStorage('commerce_order')->load($ord_id);

```

I want to update the user ID of this order. How can I achieve this?

# Answer
> 6 votes
It should be as simple as:

```
$order->setCustomer($user)->save();

```

Or if you only have the user ID and don't want to load the account object:

```
$order->set('uid', $uid);
$order->save();

```

---
Tags: 8, users, commerce
---


# Question
Title: Error occurs every time I try to log in after updating
I cloned a site locally, imported the database and run: "composer update --with-dependencies",

Got the following:

> \[RuntimeException\]
> Could not scan for classes inside "/home/www/sites/site/web/vendor/drexarj/disqus-php/disqusapi/" which does not appear to be a file nor a folder

then I run "drush updb -y".

There were a couple warnings:

> The following module is missing from the file system: aspambot bootstrap.inc:268
> The following module is missing from the file system: phpmailer bootstrap.inc:268

Then I uninstalled recaptcha by typing:

"drush pm-uninstall recaptcha"

Tried to log in, but got the following unexpected error:

> The website encountered an unexpected error. Please try again later. Error: Call to undefined function Drupal\commerce\_price\bcmul() in Drupal\commerce\_price\Calculator::multiply() (line 75 of modules/contrib/commerce/modules/price/src/Calculator.php). Drupal\commerce\_price\Calculator::multiply('107.000000', '1.00') (Line: 140) Drupal\commerce\_price\Price-\>multiply('1.00') (Line: 259) Drupal\commerce\_order\Entity\OrderItem-\>recalculateTotalPrice() (Line: 133) Drupal\commerce\_order\Entity\OrderItem-\>setUnitPrice(Object) (Line: 144) Drupal\commerce\_order\OrderRefresh-\>refresh(Object) (Line: 92) Drupal\commerce\_order\OrderStorage-\>doPreSave(Object) (Line: 389) Drupal\Core\Entity\EntityStorageBase-\>save(Object) (Line: 820) Drupal\Core\Entity\Sql\SqlContentEntityStorage-\>save(Object) (Line: 391) Drupal\Core\Entity\Entity-\>save() (Line: 114) Drupal\commerce\_order\OrderStorage-\>postLoad(Array) (Line: 249) Drupal\Core\Entity\EntityStorageBase-\>loadMultiple(Array) (Line: 231) Drupal\commerce\_cart\CartProvider-\>loadCartData(Object) (Line: 184) Drupal\commerce\_cart\CartProvider-\>getCartIds(NULL) (Line: 172) Drupal\commerce\_cart\CartProvider-\>getCarts() (Line: 221) Drupal\commerce\_cart\Plugin\Block\CartBlock-\>getCacheTags() (Line: 86) Drupal\block\BlockViewBuilder-\>viewMultiple(Array, 'full', NULL) (Line: 71) Drupal\block\BlockViewBuilder-\>view(Object) (Line: 151) Drupal\block\Plugin\DisplayVariant\BlockPageVariant-\>build() (Line: 259) Drupal\Core\Render\MainContent\HtmlRenderer-\>prepare(Array, Object, Object) (Line: 117) Drupal\Core\Render\MainContent\HtmlRenderer-\>renderResponse(Array, Object, Object) (Line: 90) Drupal\Core\EventSubscriber\MainContentViewSubscriber-\>onViewRenderArray(Object, 'kernel.view', Object) call\_user\_func(Array, Object, 'kernel.view', Object) (Line: 111) Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher-\>dispatch('kernel.view', Object) (Line: 156) Symfony\Component\HttpKernel\HttpKernel-\>handleRaw(Object, 1) (Line: 68) Symfony\Component\HttpKernel\HttpKernel-\>handle(Object, 1, 1) (Line: 57) Drupal\Core\StackMiddleware\Session-\>handle(Object, 1, 1) (Line: 47) Drupal\Core\StackMiddleware\KernelPreHandle-\>handle(Object, 1, 1) (Line: 99) Drupal\page\_cache\StackMiddleware\PageCache-\>pass(Object, 1, 1) (Line: 78) Drupal\page\_cache\StackMiddleware\PageCache-\>handle(Object, 1, 1) (Line: 47) Drupal\Core\StackMiddleware\ReverseProxyMiddleware-\>handle(Object, 1, 1) (Line: 52) Drupal\Core\StackMiddleware\NegotiationMiddleware-\>handle(Object, 1, 1) (Line: 23) Stack\StackedHttpKernel-\>handle(Object, 1, 1) (Line: 666) Drupal\Core\DrupalKernel-\>handle(Object) (Line: 19)

My question is: what can I do about this? I've repeated the process two times and got the same error.

# Answer
> Call to undefined function Drupal\commerce\_price\bcmul() in Drupal\commerce\_price\Calculator::multiply()

Drupal Commerce requires the BC Math PHP extension \- you don't have it in your current environment.

To fix, rebuild PHP with support for the BC Math extension.
> 4 votes

---
Tags: 8
---


# Question
Title: Get views contextual filter's argument value in thousand
I have a Civicrm set up in Drupal 7. I am showing Civicrm data using two different views.

In one of the view I have set contextual filter to get the contact IDs. From another view I am passing contact IDs as the contextual argument.

Now the issue is, the filter is not working for those IDs which are in thousand. For e.g. 1,223.

Further, when i used the Views php module to pass php value to remove that comma, it is creating Ajax internal server error.

Below is the code, I used in views php field.

```
<?php echo str_replace(',', '', $row->contact_id); ?>

```

I have checked below link, but that is also not working in this case

Thousands separator (comma) in term id

Please suggest a solution which will work without any ajax issue.

# Answer
> 0 votes
```
/**
 * Implements hook_views_data_query_alter().
 *
 * @param $view
 *   Information about Views' tables and fields.
 *
 * @param $query
 *   Information about query used in this views.
 */
function my_module_views_query_alter(&$view, &$query) {
  // Only edit your view whose contextual filter need to be edited.
  if ($view->name == 'your_view_name'){

    // Get your contextual filter field and use your code to strip comma.
    // str_replace(',', '', $row->contact_id);
  }
}

```

---
Tags: civicrm, views
---


title: How to add html to the form?

text:
# Question
Title: How to add html to the form?
I am creating a custom module. I have a form that I would like to add some HTML to, but I don't know what the best way to do this.

In this example, I have a page with a textbox, dropdown list, and text area. I want to add a a div between the dropdown list and text area. But, I'm not sure how to add raw html to a web form.

Here is what I have:

```
function myModule_add_form($form_state){
  try{
    $form = array();
    $form['myModule_title'] = array(
      '#title' => 'Title',
      '#type' => 'textfield',
      '#size' => '30',
      '#weight'=>1,
    );

    $form['myModule_type_list']=array(
      '#type'=>'select',
      '#title' => 'Type List',
      '#options' => $someArray,
      '#multiple' => false,
      '#attributes'=>array('size'=>1),
      '#weight'=>2,
    );

    $form['myModule_description'] = array(
      '#title' => 'Description',
      '#type' => 'textarea',
      '#size' => '255',
      '#weight'=>3,
    );

    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => 'Submit',
      '#weight'=>4,
    );

    return $form;
  } catch(Exception $e){
      $errrmsg = "Error with creating form: " .$e->getMessage();
      throw New Exception($errrmsg);
  }
}

```

Thanks jason

# Answer
> 0 votes
You need `#type => markup` here as per Form API.

```
$html = '<strong>My HTML</strong>';

$form['mymarkup'] = array(
  '#type' => 'markup'
  '#value' => $html,
);

```

# Answer
> 6 votes
No need to declare a form element as #type = 'markup', as this is the default type.

```
$html = '<strong>My HTML</strong>';

$form['mymarkup'] = array(
  '#markup' => $html,
);

```

Refer to: https://api.drupal.org/api/drupal/developer%21topics%21forms\_api\_reference.html/7.x

# Answer
> 2 votes
Try this instead:

```
$html = '<strong>My HTML</strong>';

$form['mymarkup'] = array(
  '#type' => 'markup',
  '#markup' => $html,
);

```

Refer to: https://api.drupal.org/api/drupal/developer%21topics%21forms\_api\_reference.html/7.x

---
Tags: forms, 6, webforms
---


title: Maintenance mode and user session

text:
# Question
Title: Maintenance mode and user session
When I put site in maintenance mode and after turn site back all users sessions are not active (is need to log in account), but I put session to work 2 month and it work.

How to prevent users logout when put site in maintenance?

# Answer
> 2 votes
This is intended behavior, if user does not have "access site in maintenance mode" permission, then user is logged out.

For Drupal 7 take look on user\_menu\_site\_status\_alter

For Drupal 8 take look on Drupal\user\EventSubscriber\MaintenanceModeSubscriber

---
Tags: maintenance-mode
---


# Question
Title: Filter View by Entity Reference Value From Current Node
I've been trying to figure this out for a while now, I believe that this should be easy but I still can't solve it. I'm a beginner at this. -\_-

**I have 3 Content types**

1. Venue
2. Food
3. Package

I have a List of Venue that will be used as reference for the Food. So, The Food content type has an entity reference field -\> field\_venue

**The Food will only be available to the venue it referenced.**

The **Package** Content type has the entity reference **Venue** and **Food**. It shows the venue and the food available.

I use **Entity Reference View Widget** for the Entity reference on Package Content Type. The Venue is working well.

**My Problem is the Food.**

I need an Entity Reference View Widget (VIEW) that **shows the available food for the Venue**.

On the form, the user will only be able to answer the **Venue field**. After that the form will be **saved** and the entity reference field for Food will display on the page, that is the place where the user will answer that field.

On the entity reference view widget **Food**, I have the following:

**Filter Criteria:** Content Type: Food

**Relationship:** Entity Reference: Referenced Entity (field\_venue) marked as required

The **problem is that the view shows all the food even if the chosen venue is not available for that food**. I don't know where to put that condition. Either on contextual filter or Filter Criteria. I'm not sure. I just need the view to get the **Answer of the Venue** from that same form/node so that the Food will **filter automatically**.

Is there anyone that will be able to help?

Thank you very much!!!

# Answer
> 1 votes
I got this working with this set up:

**Contextual Filter**: field\_venue -\> Provide default value -\>PHP Code -\> PHP contextual filter code

> $node=menu\_get\_object(); return $node-\>field\_venue\_for\_catering\['und'\]\[0\]\['target\_id'\];

* "field\_venue" is the venue field from "Food"
* "field\_venue\_for\_catering" is the venue field from "Package".

# Answer
> 0 votes
Not exactly what you want, but you could try adding a filter criterion on Venue to the Food View and expose the criterion. That way the user can filter Food *manually* in the widget.

# Answer
> 0 votes
I needed to filter a view based on a Taxonomy field in a content type. I found a way to do that and it's very easy.

1- make a contextual filter -\> select provide default value.

2- select type -\> Taxonomy term id from url, you will get new checkboxes appeared below it.

3- check the following: Load default filter from term page, Load default filter from node page, that's good for related taxonomy blocks, Limit terms by vocabulary.

4- select the Vocabulary you want to filter based on.

5- Multiple-value handling: Filter to items that share all term.

---
Tags: views, entities
---


# Question
Title: Programmatically set class on extended field type
Earlier I created an extended version of the Node class. I called it AbleNode and it extended BaseNode. In order to set all nodes to this node type I added this to my custom .module file

```
function ablecore_entity_type_build(&$entity_types){
    if(isset($entity_types['node'])){
        $entity_types['node']->setClass('Drupal\ablecore\Plugin\Node\AbleNode');
    }
}

```

This works fine but I'm not sure how to do this with an extended field type. Here is the code for my field class that is extending the BaseFileFieldItemList class

```
<?php
namespace Drupal\ablecore\Plugin\Field\FieldType\FileFieldItemList;
/**
 * @file AbleNode.php
 */
use Drupal\file\Plugin\Field\FieldType\FileFieldItemList as BaseFileFieldItemList;

class AbleFileFieldItemList extends BaseFileFieldItemList {
    public function style($image_style) {
        $image_style = \Drupal\image\Entity\ImageStyle::load($image_style);
        if (!empty($image_style)) {
            return $image_style->buildUrl($this->getEntity()->getFileuri());
        } else {
            return false;
        }
    }
}

```

I see how I was able to turn all nodes into AbleNodes, but I'm not sure how to make all FileFieldItemLists into AbleFileFieldItemLists. Is there a hook I can use to setClass on the field whenever I encounter it? Keep in mind that I'm not trying to create a brand new field, I just want to give more functionality to existing field types.

# Answer
> 3 votes
This is untested, but I'm pretty sure you just need to change the list class for the field types using `hook_field_info_alter()`:

```
function ablecore_field_info_alter(&$info) {
  foreach ($info as &$field) {
    if ($field['list_class'] == '\Drupal\file\Plugin\Field\FieldType\FileFieldItemList') {
      $field['list_class'] = '\Drupal\ablecore\Plugin\Field\FieldType\AbleFileFieldItemList';
    }
  }
}

```

---
Tags: 8, entities
---


title: Change theme template for one form

text:
# Question
Title: Change theme template for one form
I try to change a the theme template for one form. I do not want to use theme suggestions as I only want to use a different theme in one case, and if I add a suggestion, it is always used. (maybe I'm wrong.)

I'm doing:

in my controller:

```
$form = \Drupal::service('entity.form_builder')->getForm($entity);

$form['#theme_wrappers'][] = 'user_register_form_01';

return $form;

```

in my .module

```
function mymodule_theme() {
  return [
    'user_register_form_01' => [
      'render element' => 'form',
      'template' => 'user-register-form-01',
    ],
  ];
}

```

in user-register-form-01.html.twig:

```
<form{{ attributes }}>

  {{ form.field_1 }}
  {{ form.field_2 }}
  {{ form.account.pass }}
  {{ form.account.mail }}

  {{ form.form_build_id }}
  {{ form.form_id }}
  {{ form.actions }}

</form>

```

Everything seems to be rendered correctly, but the form does not work/submit. I think it is because attributes does not contain any action information. There is one more attributes variable inside form but I don't know how to call it as when I dump it it is prefixed with #

dump(form|keys) returns

```
array (size=49)
  0 => string '#attributes' (length=11)
  1 => string '#attached' (length=9)
  ...
  47 => string '#children' (length=9)

```
1. I don't know how to access this as form.#attributes doesn't work and form.attributes results empty.
2. Also this #attributes seems not to contain the needed form submission information. But it seems that inside #children the #attributes does.

I am thankfull for any hint or help.

# Answer
> 0 votes
Have you looked into the Context module for this (https://www.drupal.org/project/context)? One of the "reactions" is to change the theme. You can do it by system path.

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


# Question
Title: create panel page for taxonomy term page
How to create panel for taxonomy term page using Page Manager in Drupal 8. I've created page with path `/taxonomy/term/{taxonomy_term}` but it doesn't work and displays default taxonomy page template.

# Answer
I was able to get this to work with the latest dev versions of `Panels` and `Page Manager`. Here are the key pieces:

* Disable the `Taxonomy term` view.
* Set the path on the panels page to `/taxonomy/term/%`.
* Clear cache.
* View page at `taxonomy/term/{tid}`.
* I verified that this also works with URL aliases.

One thing to keep in mind: If you use selection conditions (e.g. by Vocabulary), terms that don't satisfy the selection conditions return a 404 (which may or may not be what you want). There is an issue on Drupal.org for providing a default fallback.
> 4 votes

# Answer
In Drupal 8.4.4 and Page Manager I have set path for page to /taxonomy/term/{taxonomy\_term} and disable view "Taxonomy term" and page works (for one taxonomy term).
> 1 votes

# Answer
As dobrzyns implied, the panels taxonomy page template in Panels conflicts with the Views Taxonomy page. However, rather than disabling the goodness of the Views Taxonomy Page view, you can change the default Views Taxonomy Page View path to something like 'view/taxonomy/term/%'. This gives you the flexibility of adding the the Views Taxonomy Page view as content within your Panels pages.
> 0 votes

---
Tags: 8, panels
---


# Question
Title: Panel with a view that is filtered dynamically by taxonomy term
I'm using D7 with the panels3 and views 3.

I've got a view of medical procedures which are categorized by medical specialty. I have doctors becoming members of the site and, using profile2, I'm having them choose a specialty from that some tax vocab. I have a view of these procedures and I want it to be filtered by the specialty(ies) that the logged in user has in their profile. i.e. I want only doctors who selected the 'surgeon' specialty to see procedures also tagged with the 'surgeon' term.

I've got a view content pane set up and I have a page created with page manager which holds this in a panel but I just can't figure out how to configure Contexts to get the filtering to work.

In the view's configurations under pane settings -\> argument input I have selected "From Context". As the Contextual Filters I have chosen: Has taxonomy term ID.

Please help!!

:)

# Answer
> 0 votes
To allow panels to provide the context, Under the pane settings, set the 'Required context' to 'Term ID' and besure that the 'Context is optional' setting is unchecked.

---
Tags: views, panels
---


title: How to use Colorbox with external link?

text:
# Question
Title: How to use Colorbox with external link?
I have a site built with Drupal 8.3.7.
Modules 'Colorbox', 'Colorbox Load', 'Colorbox Inline' and 'NG Lightbox' are activated.
I can't make this kind of thing work:

```
<a class="colorbox-load" href="http://maps.google.com/maps/ms?msa=0&ie=UTF8&t=p&vpsrc=6&msid=216664623938073990188.0004abcd95a296bf10c39&ll=48.552978,-0.736084&spn=3.636247,8.778076&z=7&output=embed&width=800&height=400&iframe=true"><img alt="" src="/falzon/sites/default/files/201107/J1.png" style="height:400px; max-width:none; width:800px" title="Cliquer pour ouvrir dans Google Maps" /></a></p>

```

giving that:
while it works perfectly in Drupal 7.
Any idea?

# Answer
> 2 votes
You could load external content replacing your href by

```
javascript:void jQuery.colorbox({html:'<iframe width=854 height=480 src=http://maps.google.com/maps/ms?parameters=example frameborder=0 allowfullscreen></iframe>'})

```

It will be something like:

```
<a href="javascript:void jQuery.colorbox({html:'<iframe width=854 height=480 src=http://maps.google.com/maps/ms?parameters=example frameborder=0 allowfullscreen></iframe>'})">colorbox-load external link</a>

```

---
Tags: 8, javascript
---


# Question
Title: How to convert a timestamp field into a date field?
Is there a way to convert the data of a timestamp field into a regular date field in Drupal 8? preferably without coding or making a new module.

# Answer
> 0 votes
## Export/import with Feeds

Feeds module can help to export the existing Timestamp field data and import it into a new Date field.

## Feeds Tamper to convert from timestamp to ISO date format

I'm not sure if you can export timestamp into the ISO format directly. If you can't, then you may convert the timestamp to ISO format externally once you have it in a CSV file for example, or you use Feeds Tamper module to convert it during import.

`Unix timestamp to Date` is on the Feeds Tamper plugin list.

Setting up Feeds can take patience and time, so arm yourself with those, backup everything before starting to meddle with it, and test everything on a local/dev instance. (This always applies, but I find it's good to remind when dealing with Feeds.)

After you have the Date field correctly filled with data, you'll want to delete the Timestamp field.

## Delete old Timestamp field

To do that you need to delete the Timestamp data and then the field from your system. You won't be able to delete the field that has some data in it.

To delete the Timestamp data you can use another Feeds import to update the nodes and make that field empty.

You could also delete the data with the help of Views Bulk Operations (VBO) or work directly on the database through some other SQL tool but that is probably out of scope here.

When the Timestamp field is empty you can delete it from your content type through the usual Drupal interface.

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


# Question
Title: Data returned from the controller is not showing in the template file
I am sending data from a custom module controller to a template file using the following code.

### module.info.yml

```
name: Module
description: Module description
package: Custom
type: module
version: 1.0
core: 8.x

```

### module.module

```
function module_theme($existing, $type, $theme, $path) {
  return [
    'module_template' => [
      'variables' => [
        'var' => [],
        'title' => ''
      ]
    ]
  ];
}

```

### module.routing.yml

```
module.event:
  path: '/path/{dynamic}'
  defaults:
    _controller: '\Drupal\module\controller::RunQuery'
    _title: 'Module'
  requirements:
    _permission: 'access content'

```

### module-template.html.twig

```
<p> test {{ title }}</p>
<ul>
{% for user in var %}
  <li> {{ user.title }} </li>
{% endfor %}
</ul>
test 2

```

### controller.php

```
namespace Drupal\module;

class controller {

  public function RunQuery($dynamic) {

    // Some query here which work fine and return what I want
    $ok = 'Some value';

    return [
      '#theme' => 'module_template',
      '#var'   => $ok,
      '#title' => 'Title',
    ];
  }

}

```

This will return only *test* and *test 2* in the template file, so the template file is called by the module controller, but it does not show `{{ title }}` and `{{ user.title }}`.

# Answer
I don't know what exactly you are trying to do as `var` never seems to be passed an array or object but I'll give you a working example. Your controller should extend `ControllerBase` and use `public function content()` to output stuff. Also pay attention to reference the correct `namespace` and pay attention to upper and lower case writing as well.

**module.info.yml**

```
name: Module
description: Module description
package: Custom
type: module
version: 1.0
core: 8.x

```

**module.module**

```
function module_theme($existing, $type, $theme, $path) {
  return [
    'module_template' => [
      'variables' => [
        'var'   => NULL,
        'title' => NULL,
      ],
    ],
  ];
}

```

**module.routing.yml**

```
module.event:
  path: '/path/{user}'
  defaults:
    _controller: '\Drupal\module\Controller\Controller::content'
    _title: 'Module'
  requirements:
    _permission: 'access content'

```

**templates/module-template.html.twig**

```
<p> test {{ title }}</p>
<div>{{ var.getUsername }}</div>
test 2

```

**src/Controller/Controller.php**

```
namespace Drupal\module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Session\AccountInterface;

class Controller extends ControllerBase {

  public function content(AccountInterface $user) {

    return [
      '#theme' => 'module_template',
      '#var'   => $user,
      '#title' => 'Title',
    ];
  }

}

```

---

Now you can access `/path/1` or whatever user ID you want to get this user's name printed.

With the Devel sub-module Kint installed you can use `{{ kint() }}` or `{{ kint(var) }}` inside the template to check out what else you can get and print.
> 1 votes

---
Tags: 8, theming
---


# Question
Title: How to update custom content type fields value in bulk?
Is their any way to provide the bulk edit in the custom content type fields values by csv or in bulk.?

# Answer
> 1 votes
Without a lot of detail about your problem I suggest you research these modules:

VBO works through Views: you create a list of the nodes you want to edit. VBO provides a field through which you can select nodes (checkbox) and then you can perform operations on them.

Feeds can update existing nodes from a CSV file (create new nodes too). They're a bit trickier to configure, mapping must be tested thoroughly and you need to make sure the entries are unique, but once you have them set up correctly you can use them over and over again.

# Answer
> 0 votes
You could use Migrate Source CSV

> The basic Migrate framework went into core for Drupal 8 - but not all of it. The core migrate module will implement the underlying framework, while the migrate\_drupal module will support simple upgrades from Drupal 6 and Drupal 7. The rest of the migration functionality from Drupal 7 will be left to contrib to implement. This project is the contrib functionality for CSV files. Over in #2931739: Bring migrate\_source\_csv to core, it was decided to port this module for use in core. Eventually, this module will sunset

Here is a link to the documentation

---
Tags: 8, nodes, entities, database
---


# Question
Title: "The file phpC128.tmp could not be saved. An unknown error has occurred. File upload error. Could not move uploaded file."
I have Drupal 8.4 running on Windows Server 2016, and when trying to use an upload field on a content type I get this error

> The file phpC128.tmp could not be saved. An unknown error has occurred.
> File upload error. Could not move uploaded file.

I deleted the *files* folder and the account PHP is running under, recreated it for this month as expected, but this still errors out. I see the file in c:\windows\temp, but it doesn't make it to my site folder. The account has full control to the *files* and *2018-06* folders.

In IIS, the AppPool is running under *ApplicationPoolIdentity* as well.

# Answer
Moving the file path from \`c:\windows\temp' to another location, and after setting the IUSR permissions on that new folder, it worked as expected!
> 0 votes

---
Tags: files
---


# Question
Title: How do I use a display mode for anonymous users, and another one for logged-in users?
I would like to change the display mode only for entity.node.canonical, so that a logged-in user would see something completely different than anonymous users.

For example, an entity displayed by an entity reference field should be displayed in teaser mode for anonymous users, and in full mode for logged-in users.

How can I achieve this?

# Answer
This is similar to How do I change the node view mode before rendering?, only that you want to add conditions for the route name and the current user:

```
/**
 * Implements hook_entity_view_mode_alter().
 */
function mymodule_entity_view_mode_alter(&$view_mode, $entity, $context) {
  if ($entity->getEntityTypeId() == 'node' && $entity->bundle() == 'article') {
    if (\Drupal::routeMatch()->getRouteName() == 'entity.node.canonical') {
      if (\Drupal::currentUser()->isAnonymous()) {
        $view_mode = 'teaser';
      }
    }
  }
}

```
> 2 votes

---
Tags: 8, entities
---


title: Why is jQuery dependency not working?

text:
# Question
Title: Why is jQuery dependency not working?
I'm extending core Classy theme so I have included my JavaScript code in `theme.libraries.yml` file like this:

```
js:
  js/blogger-list.js: {}
dependencies:
  - core/jquery

```

but still browser console shows error: jQuery is not defined

blogger-list.js is really simple:

```
(function ($) {
  $(".views-col a").hover(function() {
    $(this).css('background','red');
  });
})(jQuery);

```

I'm using Drupal 8

What do I need to do?

# Answer
First of all: DON'T EDIT ANY CORE FILE! EVER!!! Simply create a sub-theme or a very simple module to add your custom stuff.

---

I doubt a little bit that it really is this exact file that raises that error. But if so (your `theme.libraries.yml` looks incomplete somehow), please try to follow the docs as close as possible and use `Drupal.behaviors` to add JS functionality. See JavaScript API overview.

**MYMODULE/MYTHEME.libraries.yml**

```
foobar:
  js:
    js/blogger-list.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once

```

**js/blogger-list.js**

```
(function ($, Drupal) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function (context, settings) {
      $('.YOUR-VIEW-ID-OR-WHATEVER', context).once('myCustomBehavior').each(function () {

        $(".views-col a").hover(function () {
          $(this).css('background', 'red');
        });

      });
    }
  };
})(jQuery, Drupal);

```

And last but not least don't forget to attach your library to a render array or your theme's info file. See Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme.
> 2 votes

---
Tags: javascript
---


# Question
Title: How can I use the field_ui_table element in a custom module?
How can I use the field\_ui\_table element in a custom module? Is it even possible to use it?

The following code doesn't show anything.

```
$form['menu_builder']['list1'] = array(
  '#type' => 'field_ui_table',
  '#header' => $header,
  '#options' => $options,
  '#empty' => t('No content available.'),
  '#attributes'=>array('id'=>'menu-builder-table'),
);

```

# Answer
Looking at `theme_field_ui_table()`, the function that renders the *field\_ui\_table* element, and `field_ui_display_overview_form()`, a form builder that uses that form element, I can say that:

* Neither *#options* nor *#rows* is used from the rendering function
* Leaving out those two element attributes, the code you shown contains just the declaration of the table; it still needs to define the elements to render in the table, which the render function expects to be a list of fields.

The code adding the fields to be listed as rows of the table is quite complex.

```
  foreach ($instances as $name => $instance) {
    $field = field_info_field($instance['field_name']);
    $display = $instance['display'][$view_mode];
    $table[$name] = array(
      '#attributes' => array(
        'class' => array(
          'draggable',
          'tabledrag-leaf',
        ),
      ),
      '#row_type' => 'field',
      '#region_callback' => 'field_ui_display_overview_row_region',
      '#js_settings' => array(
        'rowHandler' => 'field',
        'defaultFormatter' => $field_types[$field['type']]['default_formatter'],
      ),
      'human_name' => array(
        '#markup' => check_plain($instance['label']),
      ),
      'weight' => array(
        '#type' => 'textfield',
        '#title' => t('Weight for @title', array(
          '@title' => $instance['label'],
        )),
        '#title_display' => 'invisible',
        '#default_value' => $display['weight'],
        '#size' => 3,
        '#attributes' => array(
          'class' => array(
            'field-weight',
          ),
        ),
      ),
      'parent_wrapper' => array(
        'parent' => array(
          '#type' => 'select',
          '#title' => t('Label display for @title', array(
            '@title' => $instance['label'],
          )),
          '#title_display' => 'invisible',
          '#options' => $table['#parent_options'],
          '#empty_value' => '',
          '#attributes' => array(
            'class' => array(
              'field-parent',
            ),
          ),
          '#parents' => array(
            'fields',
            $name,
            'parent',
          ),
        ),
        'hidden_name' => array(
          '#type' => 'hidden',
          '#default_value' => $name,
          '#attributes' => array(
            'class' => array(
              'field-name',
            ),
          ),
        ),
      ),
      'label' => array(
        '#type' => 'select',
        '#title' => t('Label display for @title', array(
          '@title' => $instance['label'],
        )),
        '#title_display' => 'invisible',
        '#options' => $field_label_options,
        '#default_value' => $display['label'],
      ),
    );

    // ...

  }

```

Yes, it is possible to use that form element, using the correct data. Since it has been written for a very specific purpose, it's easier to write code for a custom form element, if the task is not showing a table with the same degree of complexity. If the code is then used for a single form, it's even easier to create a custom table in a form.
> 0 votes

---
Tags: forms
---


# Question
Title: Problem with database migrating Drupal 8 site from local to web host (multiple databases)
I'm trying to migrate over a Drupal 8 site developed on my local PC to the web host. Everything is fine with the files transferred over (/site/files, /modules, /themes, etc.), the database has been transferred successfully, but it's not being read by Drupal (the new site is blank but with the CSS working fine). My web host insists that everything is fine with the settings.php and other files and suggested that I look here for solutions.

The only lead I have is that I notice that the local site I created on Bitnami/Xampp has five different databases: "bitnami\_drupal8", "information\_schema", "mysql", "performance\_schema", and "sys".

I've been trying to export and import back in the "bitnami\_drupal8" database because that seemed to be the main database. There is only one database on my web server (I'm only allowed two).

Do I need to export/import these five databases and merge them into the one on my web host? If not, are there any other suggestions?

Note too: I've tried the Backup & Migrate module with backups of the entire site, imported that in, and it still didn't show anything. It's like there's some incompatibility between the local and web host databases.

Thanks a lot

# Answer
> 0 votes
Okay I figured it out. It was the database prefix value in the settings.php file that was the problem.

I set up the site on another web host and got it to work there, then I compared the two settings.php files and noticed that the working one had the database prefix blank. The problem occurred with InMotion Hosting but it worked fine on Bluehost.

Thanks for the help.

---
Tags: database
---


# Question
Title: How can I use HTML in a field of paragraphs module
I am using the paragraphs module. And I add a text field (plain,long). In this field I want to add e.g.

```
<i class="fas fa-circle fa-stack-2x"></i>

```

After rendering the output in browser is in quotation marks like this

```
"<i class="fas fa-circle fa-stack-2x"></i>"

```

How can I avoid it?

# Answer
Make it a body field, and then edit the source - put your HTML in there
> 1 votes

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


# Question
Title: showing errors even though display_errors is off
I want to hide all error messages to the users. I did all the three steps below

1. Set display\_errors = off and error\_reporting = 32767 in php.ini
2. Made sure this config `$config['system.logging']['error_level'] = 'verbose';` not exist in settings.php
3. Admin-\>Configuration-\>Development-\>Logging and Errors -\> set `None` for `Error messages to display` config.

Still it is showing all the errors, but on first time load only (E.g If there was an error in previous page, those errors are displayed in current page. If i do refresh, those errors are gone from the pages).

How really can hide all the error messages in Drupal 8? I just want to log the messages not to display.

# Answer
> 1 votes
Drupal 8 hide error messages by default unless you enable dev mode.

Check and remove services.yml and settings.local.php files in sites/default folder.

---
Tags: 8, debugging
---


title: Tracking field deletion

text:
# Question
Title: Tracking field deletion
How to track user activity to find the user behind the field deletion.

As an admin, I want to track user activity so that I can find the user who deletes the field from particular content type.

I have tried with following modules but there is no option to track field.

1. Entity delete log.
2. track field changes.
3. Message and rule.

# Answer
I recommend the Blame module, it logs all of the form submitted data of any form submitted on your website, whether that be a node form, an admin settings form, etc.
> 1 votes

# Answer
With the right setup all you need is a little DevOps juice to find out.

I mean, why in the first place would you let anybody delete fields on live? Field UI, Views UI and certain other modules should be disabled on live. Now you can delete fields from within Drupal only by triggering certain (update-)functions that would need to be committed into a Git repo. With Git you can blame pretty easily and find the person who committed the corresponding lines of code.

With DevOps juice I mean that you should better setup continuous integration or some other automated deployment routine connected to your Git repo to do the admin jobs on live triggered by a Git release or Git merge to run a predefined set of commands (or a script) instead of you or anybody else clicking through the UI or login to the server to do this kind of stuff (via `drush` or similar).
> 0 votes

---
Tags: entities
---


# Question
Title: How to render a form in custom template?
I'm looking to add a form inside a custom template. The form, if I open the path registered inside the file cmodule.routing.yml, works but if i try to use it inside a custom template it doesn't work: with a dump(form) or dump(form.anyfield) i get NULL.

cmodule.routing.yml:

```
cmodule.manageform:
  path: '/cmodule/manageform'
  defaults:
    _title: 'Documents'
    _form: '\Drupal\cmodule\Forms\RequestForm'
  requirements:
    _permission: 'access content'
cmodule.manage:
  path: '/cmodule/manage'
  defaults:
    _controller: '\Drupal\cmodule\Controller\CmoduleController::manageAction'
    _title: 'Custom Documents'
  requirements:
    _permission: 'access content'

```

RequestForm.php:

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

    $form['type'] = array(
        '#type' => 'radios',
        '#options' => array(
            '0' =>t('DOC'),
            '1' =>t('PDF')
        ),
    );
    $form['pid'] = array(
        '#type' => 'textfield',
        '#title' => t('ID:'),
        '#required' => FALSE
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => $this->t('Submit'),
        '#attributes'=> ['class'=>['glyphicon', 'glyphicon-search']],
    );

    return $form;
}

```

cmodule.module:

```
/**
 * Implements hook_theme().
 */
function cmodule_theme(){

    $templates = array(
        'manage_cmodule_page' => array(
            'variables' =>
                [
                    'id' => NULL,
                    'form' => NULL
                ],
            'template' =>'manage_cmodule',
            'render element' => 'form'
        )
    );

    return $templates;
}

```

the controller contains:

```
public function manageAction() {

        $id = 1;

        $form = \Drupal::formBuilder()->getForm('Drupal\cmodule\Forms\RequestForm');

        $form['type']['#title_display'] = 'invisible';

        return [ '#theme' => 'manage_cmodule_page',
            '#form' => $form,
            '#id' => $id,
        ];
    }

```

and then the template/view (contains):

```
<div>
 {{ form.form_token }}
{{ form.form_build_id }}
{{ form.form_id }}
{{form.type}}
{{form.submit}}
</div>
etc..

```

But as I said above the template doesn't show the form, but show (if i print it) the #id value passed through the controller. Do you have any suggestions?!

---

**UPDATE #1** I tried also to follow the suggestion of Beebee, and then this and this so the code is:

controller:

```
controller contains:

public function manageAction() {

        $form = \Drupal::formBuilder()->getForm('Drupal\cmodule\Forms\RequestForm');

        $render['#form'] = $form;
        $render['theme'] = 'manage_cmodule_page';
        return $render;;
    }

```

and the implementation of hook\_theme in .module file is:

```
return [
    'manage_cmodule_page' => [
        'template' =>'manage_cmodule',
        'render element' => 'form',
    ]
];

```

The result is an empty page with an error inside the apache log:

> \[php7:error\] \[pid 12660:tid 1592\] \[client ::1:59521\] PHP Fatal error: Out of memory (allocated 270532608) (tried to allocate 266354688 bytes) in C:\drupal\vendor\twig\twig\lib\Twig\Extension\Debug.php on line 60, referer: http://localhost/drupal/

if I remove the following row from the controller

```
$render['theme'] = 'manage_atps_page';

```

the page loads, but it is empty (without any form).

**UPDATE #2**

I fixed my issue following also the idea of Alex Kuzava. Thus I used the code of UPDATE 1, with the new directory of the form, and then I added these 3 lines inside the part of my template (otherwise the submit button doesn't work).

```
{{ form.form.form_build_id }}
{{ form.form.form_id }}
{{ form.form.form_token }}

```

# Answer
> 6 votes
> 'render element' =\> 'form'

Your render element is **form** which means all provided variables will be passed there.

In your twig template you can render your form like here

```
<div>{{ form.form }}</div>

```

---

**UPDATE #1**

Wow man, you have wrong namespace **Drupal\cmodule\Forms\RequestForm**

Should be **Drupal\cmodule\Form\RequestForm**

Please rename Forms to Form (the same for directory) and clear cache. It should help you.

# Answer
> 3 votes
See: https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!theme.api.php/function/hook\_theme/8.2.x

> Each information array must contain either a 'variables' element (for using a #theme element) or a 'render element' element (for render elements), **but not both**.

Your `manage_cmodule_page` expects both `variables` and `render element` which is not allowed. Removing `variables` array from your hook\_theme should make this work, provided the rest of the code is functional.

---
Tags: 8, forms
---


# Question
Title: Special characters in form element #title
I am trying to write a custom form for my own search facet. In the form, the labels of the elements are dinamically generated based on the indexed values, and they can contain special Hungarian characters, which are not displayed correctly. This is my code:

```
  $form['facets'][$current_property] = array(
    '#type' => 'select',
    '#title' => $current_property,
    '#multiple' => TRUE,
    '#options' => $myoptions,
    '#default_value' => $widget->buildDefaultValue($element),
    '#attributes' => array('class' => array('facetapi-multiselect', $form_state['facetapi_multiselect']['facet_class'])),
    '#post_render' => array('_facetapi_multiselect_modified_disable_options'),
    );

```

So, for example, if $current\_property is Belső memória/tárhely, then Bels? memória/tárhely is displayed in the search facet.

Can you suggest any ways how to do this correctly? Thank you very much in advance.

# Answer
> 0 votes
Based on the version of drupal you are using, you can use one of functions below :

```
decode_entities($text) for Drupal 7

```

or

```
Html::decodeEntities($text) for Drupal 8

```

so in case of using drupal 7, Your code will looks like this:

```
$form['facets'][$current_property] = array(
  '#type' => 'select',
  '#title' => decode_entities($current_property),
  '#multiple' => TRUE,
  '#options' => $myoptions,
  '#default_value' => $widget->buildDefaultValue($element),
  '#attributes' => array('class' => array('facetapi-multiselect',
    $form_state['facetapi_multiselect']['facet_class'])),
  '#post_render' => array('_facetapi_multiselect_modified_disable_options'),
);

```

# Answer
> 0 votes
Maybe there is a problem in collation settings when you want to get data from database

1. Try to use another collation like **utf8mb4\_bin** or **utf8\_bin**.
2. Try to debug the value of $current\_property and see what you have there.
3. Maybe your font doesn't support special symbols.

Good luck!

---
Tags: forms, search
---


# Question
Title: Views to display nodes based on ACL permission
I'm trying to use Flexiaccess with ACL to build a view based on node that the user has access granted by Flexiaccess.

I found this on Drupal.org, it's the same use case, but is not working for me maybe because is for Drupal 6. (http://drupal.org/node/549412):

> > Here's how to do it:
>
> Under Arguments, create a new argument: "Node: Nid"
>
> Under "Action to take if argument is not present", select "Provide default argument"
>
> Set the "Default argument type" to "PHP Code", and enter the following:
>
> global $user; return db\_result(db\_query("SELECT GROUP\_CONCAT(CAST(an.nid AS CHAR) SEPARATOR ',') FROM {acl\_user} au INNER JOIN {acl\_node} an ON au.acl\_id = an.acl\_id WHERE an.grant\_view = 1 AND au.uid = %d", $user-\>uid));
>
> Then check "Allow multiple terms per argument", and click "Update".

I follow those steps but my view shows nothing.

Any help is really appreciated.

# Answer
> 0 votes
According to: https://www.drupal.org/node/1255426, Drupal 7 does not have db\_result function. You have to replace it with db\_query().

Code which worked in my special case:

```
<?php
global $user;
$query = db_query("SELECT GROUP_CONCAT(CAST(an.nid AS CHAR) SEPARATOR ',') FROM {acl_user} au INNER JOIN {acl_node} an ON au.acl_id = an.acl_id WHERE an.grant_view = 1 AND au.uid = :uid", array(':uid' => $user->uid));
$result = $query->fetchObject();
return reset($result);
?>

```

# Answer
> -1 votes
Use Contextual Filters instead of arguments in Drupal 7 and check "Provide default value" and in PHP code insert like this.

```
global $user;
$query = db_query("SELECT GROUP_CONCAT(CAST(an.nid AS CHAR) SEPARATOR ',') FROM {acl_user} au INNER JOIN {acl_node} an ON au.acl_id = an.acl_id WHERE an.grant_view = 1 AND au.uid = :uid", array(':uid' => $user->uid));

$result = $query->fetchObject();
 return reset($result);

```

You can also get users allowed to view against each node like this by adding field for "views PHP" with this code

```
$query = db_query("SELECT GROUP_CONCAT(CAST(au.uid AS CHAR) SEPARATOR ',') FROM acl_user as au INNER JOIN acl_node as an ON au.acl_id = an.acl_id WHERE an.grant_view = 1 AND an.nid =$row->nid ");
$result = $query->fetchObject();
$res = reset($result);

$myArray = explode(',', $res);
//print_r($myArray);
foreach($myArray as $key=>$value){
                     $user_id = $value;
                     $query_user = db_query("SELECT name FROM users WHERE uid = $user_id");
                    $result_u = $query_user->fetchObject();
                    print "<span>" .$result_u->name. "  </span>";

          }

```

---
Tags: 7, views, users
---


# Question
Title: Shipping county value showing as a number
Using Drupal 7 with Drupal commerce.

During the checkout in the shipping section I can choose a county from a drop-down list (a string value). However, on the review order phase it is represented as a number (please see attached image). Moreover, it is printed as a number on the order pdf.

Any ideas on why is it so?

# Answer
The issue here is common to countries whose administrative areas don't render with abbreviations, which is the case in other countries like the U.S. and Canada where States and Provinces are abbreviated when printed (e.g. SC, NC, TN, etc.). Many of those countries use simple numeric codes or nonsensical alphanumeric codes as an administrative designation but should have the full names of the areas printed for display.

In the Address Field module, we introduced a configuration option for such countries' address formats called *render\_administrative\_area\_value* that must be set to TRUE to do so. I've opened an issue for Estonia that will also ensure we've done this for the other countries we know about:

https://www.drupal.org/project/addressfield/issues/2983142

I'll have a patch up there shortly. : )
> 1 votes

---
Tags: commerce
---


# Question
Title: Fire a rule only when a specific webform has been submitted
I am using the latest version of both drupal 8 and webform 8

Here is my use case:

I have on my drupal 8 website 3 different webforms (webform A, Webform B and Webform C)

Now, I want to fire a rule ONLY when "Webform A" is submitted.

I understand that we should use condition to limit the rule to one webform only.

For example in drupal 8 if i want to show a message on the website when a new content of type article is saved, i do the below:

1) EVENT: After saving new content (rules\_entity\_insert:node)

2) CONDITION: Node is of type; Node is of type: node; Content Types: article

3) ACTION: Show a message on the site.

And it is working pretty good when saving a content of type ARTICLE.

Now, i want ot do the same but using a webform instead of a node.

Here what i did so far:

1) EVENT: After saving a new webform submission (rules\_entity\_insert:webform\_submissiom)

2) ACTION: Show a message on the site.

After saving a new webform submission, the message is indeed showing on the website which is perfect.

However, the problem is that the message is showing for any SUBMITTED WEBFORM.

In order to limit the rules to be fired only when the webform A is sumbitted, a condition should be added to the rule in question.

I have used the below conditions

"Entity is of type"

"Node is of type"

"Webform"

"Webforms"

trying to limit the rule for only one webform and all above conditions resulted an error on the site after trying to submit any webform:

(The website encountered an unexpected error. Please try again later)

And when i remove the condition added, the site work properly again.

Any idea what is going on ?

Or maybe i am using the wrong condition to specify only one webform ?

Main question:

What is the condition to be used in order to fire a rule ONLY when one specific webform has been submitted.

Thank you in advance,

# Answer
I got this to work but i don't know if my answer will be the best approach for what i need:

Let's say, we want the rule to be fired ONLY for the webform ID: "contact"

1) EVENT: After saving a new webform submission (rules\_entity\_insert:webform\_submission)

2) CONDITION: Data Comparision;

Data to compare: webform\_submission.webform\_id.target\_id;

Operator: ==

Value: contact

3) ACTION: Show a message on the site.

Hope it will help somebody else as well, especially that there is no documentaion yet for rules 8.

Cheers,
> 1 votes

---
Tags: 8, rules, webforms
---


title: Drupal 8 secure session

text:
# Question
Title: Drupal 8 secure session
In Drupal 8.5.X I see that the session cookie is only HTTPOnly and not secure. Any idea how to enforce the session cookie to be always secured?

# Answer
The HTTP flag is being set by your browser as you're accessing Drupal over HTTP (and thus vulnerable to cookie hijacking). Drupal creates 2 different cookies (an unsecure HTTP one, and a secure HTTPS one) depending on what protocol it detects.

If you want only secure sessions, force HTTPS at the web server or application level (depending on your stack configuration).
> 2 votes

---
Tags: security
---


# Question
Title: Brackets in URL Field Get Reformatted to %5B%5D
I have a Drupal 7 site with a content type that includes a link field. The intention is for staff to add a link that can link to an outside website. But if that link contains brackets \[ \], the module uses %5B %5D instead. It also, cuts out parts of the URL.

So, ....

...Search/Results?lookfor=&basicType=Keyword&type=Keyword&filter\[\]=local\_time\_since\_added

would translate to

...Search/Results?type=Keyword&filter%5B%5D=local\_time\_since\_added

Would anyone be able to advise me as to why the link field in a content type would not only remove parts of my URL but also replace brackets?

I see a lot of chatter about this with views, but not on a link field in a content type.

# Answer
Though I have not come up with an answer to my question, the easy work-around I created was to add a text field instead of a URL field in my content type.

I then used the Linked Field Module to link the text field to the outside website. This preserved all of the crazy characters that were needed.

For those not familiar with the Linked Field Module, after you have added a text field to your content type, go into:

1. Manage Display for your content type
2. Set the Format to Default
3. Click on the Gear Symbol
4. Say No to link to content
5. Check the box to Link the field
6. For Destination use the field item name with dashes, like this \[node:field-online-link-to-resource\]
7. Use the Advanced section to add a title, link text, etc.

FYI that I would only allow trusted content editors to add data to this type of field.
> 0 votes

---
Tags: entities
---


title: View of events repeats month

text:
# Question
Title: View of events repeats month
I have an events content type, and from it, I have a view that lists events. We're using a bootstrap theme, and the format of the display I'm concerned with is Bootstrap List Group. This allows us to use a field as a grouping header.

Since we want the end user to see events grouped by month, we have the display of the grouping field set to `Year Month`. So for example, one header would be "July 2018".

We also have the view paged, so that it shows 15 events per page. We've added a "Show More" button at the bottom.

However a problem arises when the next page of events start in the same month as the previous set ended in. So for example, the user might see this:

```
 August 2018
  - Labor Day Holiday
  - a cookout
  - a meeting

[ Load More ]

```

Then when they hit "Load More", they see this:

```
 August 2018
  - Labor Day Holiday
  - a cookout
  - a meeting

 August 2018
  - Ice Cream Social
  - a party
  - ...

[ Load More ]

```

How can I prevent the Grouping header from repeating on loading more?

# Answer
> 1 votes
Your description makes it sound like you have ajax views enabled which is probably going to be very challenging to get working correctly.

There may be a better backend way to do this, but one way that occurs to me is to fix this on the client side with javascript, by merging lists after ajax finishes loading.

1. Copy the Bootstrap List Group view display template into your theme's `templates` folder.
2. Add a custom data attribute to mimic the text value of the grouping's row title, and attach a custom javascript behavior to do the work on the client side.

```
{{ attach_library('yourtheme/prevent_duplicate_list_group') }}
<ul id="{{ id }}" {{ attributes.addClass(classes) }}>
  {% for key, row in rows %}
    <li class="list-group-item">
      {% if row.title %}
        <h4 class="list-group-item-heading" data-grouping="{{ row.title }}">{{ row.title }}</h4>
      {% endif %}
      <p class="list-group-item-text">{{ row.content }}</p>
    </li>
  {% endfor %}
</ul>

```
3. Create a library in `yourtheme.libraries.yml` to add a JS behavior.

```
prevent_duplicate_list_group:
  js:
     js/prevent_duplicate_list_group.js

```
4. Write some custom javascript logic to look for all instances of the duplicate grouping and move the values from the second list into the first.

I've not used bootstrap views thus don't know the exact dom structure you'll need to work with, but here is something completely untested to get you started.

```
/**
 * @file
 * Behavior to merge duplicate List Group titles loaded from ajax-enabled views.
 */

(function ($) {
  'use strict';

  Drupal.behaviors.prevent_duplicate_list_group = {
    attach: function (context, settings) {
      $('.list-group-item-heading', context)
        .each(function (idx, element) {
          var title = $(element).attr('data-grouping'),
            duplicates = $('[data-grouping="'+ title + '"]');
          if (duplicates.length == 2) {
            var first = duplicates.eq(0).closest('ul');
            var second = duplicates.eq(1).closest('ul');
            // snagged from https://stackoverflow.com/a/28487699/413538
            // you may need to overhaul this to only walk through
            // list items from the second list up until it gets to a list item that contains an h4 and hide each individual li
            var i=1;
            $('li', first).each(function(){
              $(first).append($('li:nth-child('+i+')', second).clone());
              i++;
            });
            second.remove();
          }
        }
      );
    }
  };
})(jQuery);

```

---

---
Tags: views, 8
---


# Question
Title: Views Contextual Filters - User Name in URL
I have a view set up to function as a blog, and a contextual filter set up to filter by author of the blog post.

The point is to be able to click on the blog post author link and go to a page that lists all the blog posts by that person. This is facing anyone who visits the site, and any visitor (non-logged in) can view the blog listing of any of the authors.

The current set up is to have a `Relationship` to the `author` table, and filter by `User: name`. Then when visiting a url `/blog/author/John Smith`, you see all posts by John Smith. (I realise that's an invalid URL.)

---

The filter itself is working and the blog posts are being pulled through for all the authors, however, I'm having issues to transform spaces to dashes and to lowercase the URL.

When you visit `/blog/author/John Smith`, you are redirected to `/blog/author/John%20Smith`, and then the blog posts by John Smith are visible, but this isn't good enough for us in terms of URLs.

So instead of `/blog/author/John%20Smith`, I need the URL to be `/blog/author/john-smith`.

The problem is that the default checkboxes and options which work for taxonomy terms do not seem to work with Author names. Ticking `transform spaces to dashes in URL` and using `case in path: lower` does not affect the filter the way I want it to - it has no effect at all.

---

> I'm considering creating a new field in the user entity and then using that to filter instead. Like `john-smith` for the `John Smith` user. I'm not sure if that'll work, but I'll try it out right now.

The above has worked, and I do have the URL's I want and they query for the right items. I'm not sure if it's the cleanest solution though.

# Answer
You should remove the "User: name" Relationship on the view and add a new relationship "User: uid". Then you can access the author view with /blog/author/123.

Then create a URL alias for "/blog/author/123" and set it to "/blog/author/john-smith". You will then be able to access the view with both the uid 123 or using john-smith.
> 0 votes

---
Tags: views, path-aliases
---


# Question
Title: Where are entities stored in MySQL by default?
Drupal 8 has a powerful entity API that manages all the content of the entities.

How can these entities be accessed outside of Drupal? Which are the tables and what is the format?

# Answer
> 4 votes
There's no default as such; each entity type defines its base table and field data table via the `*EntityType` annotation. See Structure of an entity annotation for examples.

The Entity API and its power don't just live in the database, there's also plenty of code involved to prepare things sensibly for the system to use inside a request.

With that in mind, you might consider that using the built-in REST API is a more efficient way to communicate with Drupal than direct database manipulation, which won't give you the full picture of an entity without re-implementing at least some of the PHP logic in SQL

---
Tags: entities, database
---


# Question
Title: How to use token as a filter value in views
I'm looking for a solution that would allow me to use tokens in views filter values. For example, if I have text field 'my\_custom\_text' I would like to have a filter that would allow me to use 'Is equal to' operator and a token value instead of hardcoded string.

Note that I can't use contextual filters because I have few filters that needs to be ORed.

Is there a module for that, or do I have to code that myself from ground up?

# Answer
So here is what I've came up with eventually.

1. I did not want to use `global php filter` because it only limits the results that are already loaded from the DB. In my case this would mean loading 1000 rows just to display 2 of them. Not too wise I'd say.
2. I did not want to use `hook_views_query_alter` as this would mean that I'd have to dig into the code every time someone wants to change or create a view.

I ended up writing my own views handler that extends one of the exiting. I've also used `hook_field_views_data_alter` to hook up my handler instead of default.

This solution works quite nice. Custom handler is very robust solution and quite simple to implement... once you know how to do it ;)
> 0 votes

# Answer
Use Contextual Filters instead of Filter Criteria.

In Drupal 8, at the time of writing this, you also have to install the views\_argument\_token module.

When adding a contextual filter, at the pop up window, select "Provide default value" option. From there on the remaining settings should be intuitive.
> 3 votes

# Answer
You can use `hook_views_query_alter` to done your job,

implement this hook in your custom module and with if statement restrict to your views name and edit views query,
> 0 votes

# Answer
Would the Token Filter module be helpful? Here is a quote about it (from the module's project page):

> ... is a very simple module to make token values available as an input filter.
>
> The module now supports native tokens (e.g. \[site:name\]) and all global tokens by default. It even allows some contextual tokens like node or user to be replaced, but currently does not encourage users to use them in the filter help text.
> -1 votes

---
Tags: 7, views, tokens
---


title: How do I create multiple blocks?

text:
# Question
Title: How do I create multiple blocks?
I would like to create multiple blocks using the data rendered from the variable table in Drupal 8. I was able to achieve it in Drupal 7, but I can't find a way to do the same in Drupal 8.

The code I use for Drupal 7 is the following.

```
/**
 * Create a block that will display the calendar feed
 * Implements hook_block_info
 */
function my_module_block_info() {
  $blocks = array();
  $block_urls = variable_get('my_module_content');
  $block_regions = variable_get('my_module_content_block_region');
  $number_of_blocks = count($block_urls);
  if ( $number_of_blocks > 0 ) {
    foreach ( $block_urls as $key => $block_url ) {
      $blocks['eventblock-' . $key] = array(
        'info' => t('my_module_widget_block_' . $key),
        'status' => TRUE,
        'region' => $block_regions[$key],
        'cache' => DRUPAL_NO_CACHE,
      );
    }
  }
  return $blocks;
}

/**
 * Render the my_module block
 * Implements hook_block_view
 */
function my_module_block_view($delta = '') {
  $block = array();
  $block_urls = variable_get('my_module_content' , array());
    foreach ( $block_urls as $key => $block_url ) {
      switch ($delta) {
        case 'eventblock-' . $key:
          $widgetURL= $block_urls[$key];
          $block['content'] = my_module_content_generate($widgetURL); // Some function to generate block content.
          break;
        }
    }

  return $block;
}

```

# Answer
In order to create blocks dynamically in Drupal 8, you will have to define a plugin derivative. Plugin Derivatives.

This way you can create multiple instances of the same block. Hope this helps.

Block Derivatives Example

Remember to respect the folder structure when creating your derivative and block class.

**Derivative**

```
<?php

namespace Drupal\YOUR_MODULE_NAME\Plugin\Derivative;

use Drupal\Component\Plugin\Derivative\DeriverBase;

class YOUR_DERIVATIVE_NAME extends DeriverBase {

/**
 * {@inheritdoc}
 */
public function getDerivativeDefinitions($base_plugin_definition) {
// @todo might as well include your configuration here and assign a value.
  $block_urls = ['1', '2', '3'];

  foreach ($block_urls as $block_url) {
    $this->derivatives[$block_url] = $base_plugin_definition;
    $this->derivatives[$block_url]['admin_label'] = 'Sample Label ' . $block_url;
  }

  return $this->derivatives;
  }

}

```

**Block**

```
<?php

namespace Drupal\YOUR_MODULE_NAME\Plugin\Block;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Session\AccountInterface;

/**
 * Provides a block.
 *
 * @Block(
 *   id = "YOUR_BLOCK_ID",
 *   admin_label = @Translation("YOUR_BLOCK_ID"),
 *   deriver = "Drupal\YOUR_MODULE_NAME\Plugin\Derivative\YOUR_DERIVATIVE_NAME"
 * )
 */

class YOUR_BLOCK_NAME extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $id = $this->getDerivativeId();

    $build = [
      '#markup' => $this->t('Your Block Content with ID' . $id),
    ];

    return $build;
  }

  /**
   * {@inheritdoc}
   */
  protected function blockAccess(AccountInterface $account) {
    return AccessResult::allowedIfHasPermission($account, 'access  content');
  }

}

```

Rename **YOUR\_MODULE\_NAME, YOUR\_BLOCK\_NAME, YOUR\_BLOCK\_ID, YOUR\_DERIVATIVE\_NAME** accordingly.
> 5 votes

---
Tags: 8, blocks
---


title: Custom Field Plugin With Image Field

text:
# Question
Title: Custom Field Plugin With Image Field
I have been working on a custom field plugin with which the aim is to create a custom field to be used for content and will consist of a **link field** and a **file field** through which a thumb image is to be uploaded. I'm ok with the first part is i.e. the link field for which I have declared a **uri data definition** with a **varchar storage schema** and a **url type** for the form element. But I cannot (based on the available documentation) figure out the proper way to manage the **file field**. I have used a **managed\_field type** as for the form element but cannot figure out what is the correct **datatype** and **storage schema** to use.

Edit: The documentation I have found deals with three parts,

1. The field class where the propertyDefinitions method is overridden and the properties are defined (ex. $properties\['link'\] = DataDefinition::create('uri')-\>setLabel(t('Video Link'));)
2. Also in the field class where the schema method is overridden and the storage properties are defined (ex. $columns\['link'\] = \[ 'type' =\> 'varchar', 'length' =\> 255, \];)
3. the widget class where the formElement method is overridden to define the input form (ex. $element\['link'\] = \[ '#type' =\> 'url', '#title' =\> t('Link'), '#default\_value' =\> isset($items\[$delta\]-\>link) ? $items\[$delta\]-\>link : null, '#empty\_value' =\> '', '#placeholder' =\> t('Insert a url'), \];)

what should the equivalent parts for an image/file field property be defined?

any input would be appreciated, thanks

# Answer
> -1 votes
Why don't you try the Paragraphs module? This looks like a simple combination existing of field types, which is exactly Paragraphs' point.

# Answer
> 0 votes
I hope I understood correctly:

```
FileItem.php

```

Have a look at `public static function defaultStorageSettings()` and `public static function schema(FieldStorageDefinitionInterface $field_definition)`

---
Tags: 8, entities
---


# Question
Title: How to autocomplete taxo term (inside a paragraph) when using a filter in a view
Here is a node structure which is storing cooking recipes

**recipe** (node)

-title (string)

-field\_ingredient\_quantity (paragraph) =\> see below the definition

-... (other fields)

**field\_ingredient\_quantity** (paragraph)

-field\_ingredient (taxonomy term)

-field\_quantity (float)

Let say that I woul like to filter in a view all recipes containing mustard with the autocomplete filter on field\_ingredient (inside the paragraph type field\_ingredient\_quantity)

Is it possible?

# Answer
> 0 votes
Why not try to define a relationship towards the `field_ingredient_quantity` and then add the `field_ingredient` in the fields of the view(should be available after defining the paragraph relationship). Afterwards just add the exposed filter with the autocomplete functionality.

---
Tags: 8, views
---


# Question
Title: How to prevent CKEditor from replacing spaces with  ?
I'm using CKEditor 4.2 with D7 and the editor is replacing every space with an HTML non-breaking space. For instance, if I type: *This is a paragraph* and then either save or view source, I'll get the following:

```
<p>This is a paragraph.</p>

```

I don't have any HTML correctors/prettifiers running as filters and I'm banging my head against the wall trying to figure out what's causing this.

Oh, I also have *Convert all applicable characters to HTML entities.* unchecked, so that's not it.

Has anyone seen this before? Any solutions out there?

# Answer
> 6 votes
I solve this with a text filter

```
/**
 * Implements hook_filter_info().
 */
function MYMODULE_filter_info() {
  $filters = array();

  $filters['kill_nbsp'] = array(
    'title' => t('Kill Non-Breaking Spaces'),
    'description' => t('Remove non-breaking spaces.'),
    'process callback' => '_MYMODULE_filters_kill_nbsp',
    'tips callback' => '_MYMODULE_filters_kill_nbsp_tips',
  );

  return $filters;
}

/**
 * Filter callbacks.
 */
function _MYMODULE_filters_kill_nbsp($text, $filter) {
  return preg_replace('/ /', ' ', $text);
}

/**
 * Filter tips.
 */
function _MYMODULE_filters_kill_nbsp_tips($filter, $format, $long = FALSE) {
  if (!$long) {
    // This string will be shown in the content add/edit form.
    return t('Don\'t use non-breaking spaces.  Ever.');
  }
  else {
    // And this one on the "Filter Tips" page.
    return t('Non-breaking spaces are evil and will be eradicated.');
  }
}

```

The code simply searches for non-breaking spaces and replaces them with normal spaces.

Stuff this in a custom module, and then assign the filter to the input formats that have WYSIWYG enabled. This does assume that you never want actual non-breaking spaces in your output, which is good for my sites.

# Answer
> 0 votes
Try this it will remove leading white spaces for ckeditor

var val = CKEDITOR.instances.\[name\_of\_field\].getData();//get data

val = $(val).text().trim();//remove white spaces

---
Tags: 7, wysiwyg
---


title: Should I use separated servers?

text:
# Question
Title: Should I use separated servers?
I have to use Solr to improve my customer search engine, on Drupal 7 website.

On the development environment, I've set Tomcat and web server on the same machine and it works, but I did not inject the whole content database. It contains about 25,000 nodes; I'm not sure if I need to deploy the SolR instance (Tomcat + Solr + configs) on a separated server, or if this won't be useful.

# Answer
> 1 votes
In terms of Drupal integration with solr or its performance it does not matter you host solr on same instance or not.

However, to decide you might want to consider following:-

1. Your server resources and its consumption: You need to evaluate if your server resources are well enough to serve the traffic on your website, since solr is going to share the same resources.
2. Maintenance of solr: Running solr instance will require some level of maintenance in terms of monitoring its running status, tweaking the solr configuration as per your need, running it as background process.
3. Cost: Of course, it has cost implications hosting solr on separate instance or subscribing to paid solr hosting services will cost you extra bucks.

Hope that helps!

---
Tags: search
---